code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Is the node pointed to by @ref path an unknown object?''' node = self.get_node(path) if not node: return True return node.is_unknown
def is_unknown(self, path)
Is the node pointed to by @ref path an unknown object?
5.730979
3.306561
1.733214
'''Is the node pointed to by @ref path a zombie object?''' node = self.get_node(path) if not node: return False return node.is_zombie
def is_zombie(self, path)
Is the node pointed to by @ref path a zombie object?
4.908183
3.017457
1.626596
'''Call a function on the root node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the va...
def iterate(self, func, args=None, filter=[])
Call a function on the root node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref...
8.016936
1.281265
6.257046
'''Load the name servers environment variable and parse each server in the list. @param filter Restrict the parsed objects to only those in this path. For example, setting filter to [['/', 'localhost', 'host.cxt', 'comp1.rtc']] will ...
def load_servers_from_env(self, filter=[], dynamic=None)
Load the name servers environment variable and parse each server in the list. @param filter Restrict the parsed objects to only those in this path. For example, setting filter to [['/', 'localhost', 'host.cxt', 'comp1.rtc']] will prevent...
8.936611
1.739476
5.137531
'''Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. @return The created port object...
def parse_port(port_obj, owner)
Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. @return The created port object.
3.164372
1.85378
1.706983
'''Connect this port to other ports. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection. If N...
def connect(self, dests=[], name=None, id='', props={})
Connect this port to other ports. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection. If None, a suit...
3.86045
2.051722
1.881566
'''Disconnect all connections to this port.''' with self._mutex: for conn in self.connections: self.object.disconnect(conn.id) self.reparse_connections()
def disconnect_all(self)
Disconnect all connections to this port.
8.925128
8.468664
1.0539
'''DEPRECATED. Search for a connection between this and another port.''' with self._mutex: for conn in self.connections: if conn.has_port(self) and conn.has_port(dest): return conn return None
def get_connection_by_dest(self, dest)
DEPRECATED. Search for a connection between this and another port.
6.377121
3.595787
1.773498
'''Search for all connections between this and another port.''' with self._mutex: res = [] for c in self.connections: if c.has_port(self) and c.has_port(dest): res.append(c) return res
def get_connections_by_dest(self, dest)
Search for all connections between this and another port.
4.189246
3.265319
1.282952
'''Search for all connections involving this and all other ports.''' with self._mutex: res = [] for c in self.connections: if not c.has_port(self): continue has_dest = False for d in dests: if...
def get_connections_by_dests(self, dests)
Search for all connections involving this and all other ports.
3.276719
2.487429
1.317312
'''Search for a connection on this port by its ID.''' with self._mutex: for conn in self.connections: if conn.id == id: return conn return None
def get_connection_by_id(self, id)
Search for a connection on this port by its ID.
5.294402
3.989701
1.327017
'''Search for a connection to or from this port by name.''' with self._mutex: for conn in self.connections: if conn.name == name: return conn return None
def get_connection_by_name(self, name)
Search for a connection to or from this port by name.
5.986901
3.891469
1.538468
'''A list of connections to or from this port. This list will be created at the first reference to this property. This means that the first reference may be delayed by CORBA calls, but others will return quickly (unless a delayed reparse has been triggered). ''' ...
def connections(self)
A list of connections to or from this port. This list will be created at the first reference to this property. This means that the first reference may be delayed by CORBA calls, but others will return quickly (unless a delayed reparse has been triggered).
13.784989
2.79304
4.935478
'''Connect this port to other DataPorts. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection. ...
def connect(self, dests=[], name=None, id='', props={})
Connect this port to other DataPorts. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection. If None, a ...
3.659559
1.990831
1.838207
'''Connect this port to other CorbaPorts. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection....
def connect(self, dests=None, name=None, id='', props={})
Connect this port to other CorbaPorts. After the connection has been made, a delayed reparse of the connections for this and the destination port will be triggered. @param dests A list of the destination Port objects. Must be provided. @param name The name of the connection. If None, a...
4.32164
2.102803
2.05518
'''Get an interface of this port by instance name.''' with self._mutex: for intf in self.interfaces: if intf.instance_name == name: return intf return None
def get_interface_by_instance_name(self, name)
Get an interface of this port by instance name.
4.192009
3.802951
1.102304
'''The list of interfaces this port provides or uses. This list will be created at the first reference to this property. This means that the first reference may be delayed by CORBA calls, but others will return quickly (unless a delayed reparse has been triggered). ''' ...
def interfaces(self)
The list of interfaces this port provides or uses. This list will be created at the first reference to this property. This means that the first reference may be delayed by CORBA calls, but others will return quickly (unless a delayed reparse has been triggered).
13.419911
2.862157
4.688741
'''Get the polarity of this interface as a string. @param add_colour If True, ANSI colour codes will be added to the string. @return A string describing the polarity of this interface. ''' with self._mutex: if self.polarity == self.PROVIDED...
def polarity_as_string(self, add_colour=True)
Get the polarity of this interface as a string. @param add_colour If True, ANSI colour codes will be added to the string. @return A string describing the polarity of this interface.
4.659227
3.536755
1.317373
'''Disconnect this connection.''' with self._mutex: if not self.ports: raise exceptions.NotConnectedError # Some of the connection participants may not be in the tree, # causing the port search in self.ports to return ('Unknown', None) # fo...
def disconnect(self)
Disconnect this connection.
6.04319
6.096107
0.99132
'''Return True if this connection involves the given Port object. @param port The Port object to search for in this connection's ports. ''' with self._mutex: for p in self.ports: if not p[1]: # Port owner not in tree, so unknown ...
def has_port(self, port)
Return True if this connection involves the given Port object. @param port The Port object to search for in this connection's ports.
8.335623
5.366504
1.553269
'''The list of ports involved in this connection. The result is a list of tuples, (port name, port object). Each port name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if this Connection object is owned by a Port, which is in turn owned by a Component in the tree. O...
def ports(self)
The list of ports involved in this connection. The result is a list of tuples, (port name, port object). Each port name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if this Connection object is owned by a Port, which is in turn owned by a Component in the tree. Otherwise, o...
6.310858
2.178298
2.897151
if self._analysis is not None: return self._analysis if self.cache_dir is not None: path = os.path.join(self.cache_dir, self.checksum) try: if self.refresh_cache: raise IOError with open(path + '.pickle', 'rb') as pickle_file:...
def analysis(self)
Get musical analysis of the song using the librosa library
2.459432
2.325318
1.057675
breeding = get_object_or_404(Breeding, pk=breeding_id) PupsFormSet = inlineformset_factory(Breeding, Animal, extra=10, exclude=('Notes','Alive', 'Death', 'Cause_of_Death', 'Father', 'Mother', 'Breeding')) if request.method == "POST": formset = PupsFormSet(request.POST, instance=breeding) ...
def breeding_pups(request, breeding_id)
This view is used to generate a form by which to add pups which belong to a particular breeding set. This view is intended to be used to add initial information about pups, including eartag, genotype, gender and birth or weaning information. It takes a request in the form /breeding/(breeding_id)/pups/ and ret...
2.312833
2.380317
0.971649
breeding = Breeding.objects.select_related().get(id=breeding_id) strain = breeding.Strain PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes')) if request.method =="POST": formset = PupsFormSet(request.POST, instance=breedi...
def breeding_change(request, breeding_id)
This view is used to generate a form by which to change pups which belong to a particular breeding set. This view typically is used to modify existing pups. This might include marking animals as sacrificed, entering genotype or marking information or entering movement of mice to another cage. It is used to show...
2.440752
2.407674
1.013738
breeding = Breeding.objects.get(id=breeding_id) strain = breeding.Strain PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes','Rack','Rack_Position','Strain','Background','Genotype','Death','Cause_of_Death','Backcross','Generation')) ...
def breeding_wean(request, breeding_id)
This view is used to generate a form by which to wean pups which belong to a particular breeding set. This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-change page. It takes a request in the form /bree...
2.839624
2.783293
1.020239
if request.method == "POST": form = MultipleAnimalForm(request.POST) if form.is_valid(): count = form.cleaned_data['count'] for i in range(count): animal = Animal( Strain = form.cleaned_data['Strain'], Background = form.cleaned_data['Backgro...
def multiple_pups(request)
This view is used to enter multiple animals at the same time. It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
2.277262
2.260406
1.007457
breeding = Breeding.objects.get(id=breeding_id) if request.method == "POST": form = MultipleBreedingAnimalForm(request.POST) if form.is_valid(): count = form.cleaned_data['count'] for i in range(count): animal = Animal( Strain = breeding.Strai...
def multiple_breeding_pups(request, breeding_id)
This view is used to enter multiple animals at the same time from a breeding cage. It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes. This view requres an input of a breeding_id to generate the correct form.
2.524078
2.602647
0.969812
oldest_animal = Animal.objects.filter(Born__isnull=False).order_by('Born')[0] archive_dict = {} tested_year = oldest_animal.Born.year while tested_year <= datetime.date.today().year: archive_dict[tested_year] = Animal.objects.filter(Born__year=tested_year).count() tested_year =...
def date_archive_year(request)
This view will generate a table of the number of mice born on an annual basis. This view is associated with the url name archive-home, and returns an dictionary of a date and a animal count.
2.6994
2.398457
1.125474
eartag_list = Animal.objects.filter(Born__lt=(datetime.date.today() - datetime.timedelta(days=settings.WEAN_AGE))).filter(MouseID__isnull=True, Alive=True) genotype_list = Animal.objects.filter(Q(Genotype='N.D.')|Q(Genotype__icontains='?')).filter(Alive=True, Born__lt=(datetime.date.today() - datetime...
def todo(request)
This view generates a summary of the todo lists. The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html.
3.556975
3.097712
1.148259
return super(AnimalList, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
7.590773
6.753496
1.123977
context = super(AnimalListAlive, self).get_context_data(**kwargs) context['list_type'] = 'Alive' return context
def get_context_data(self, **kwargs)
This add in the context of list_type and returns this as Alive.
5.755508
2.965128
1.941066
return super(AnimalCreate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
8.660265
6.942723
1.247387
return super(AnimalUpdate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
8.323241
6.949991
1.19759
return super(AnimalDelete, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
9.464264
7.847569
1.206012
context = super(StrainList, self).get_context_data(**kwargs) context['strain_list_alive'] = Strain.objects.filter(animal__Alive=True).annotate(alive=Count('animal')) context['cages'] = Animal.objects.filter(Alive=True).values("Cage") return context
def get_context_data(self, **kwargs)
This add in the context of strain_list_alive (which filters for all alive animals) and cages which filters for the number of current cages.
5.013646
2.569251
1.951404
strain = super(StrainDetail, self).get_object() context = super(StrainDetail, self).get_context_data(**kwargs) context['breeding_cages'] = Breeding.objects.filter(Strain=strain) context['animal_list'] = Animal.objects.filter(Strain=strain).order_by('Background','Genotyp...
def get_context_data(self, **kwargs)
This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages.
3.719706
3.067215
1.212731
return super(StrainCreate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
10.413685
8.124376
1.281783
return super(StrainUpdate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
9.503263
8.66889
1.096249
return super(StrainDelete, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
11.266181
9.568872
1.177378
context = super(BreedingList, self).get_context_data(**kwargs) context['breeding_type'] = "Active" return context
def get_context_data(self, **kwargs)
This adds into the context of breeding_type and sets it to Active.
5.207298
2.448296
2.126907
query = self.request.GET.get('q', '') context = super(BreedingSearch, self).get_context_data(**kwargs) context['breeding_type'] = "Search" context['query'] = query if query: context['results'] = Breeding.objects.filter(Cage__icontains=query).distinct() ...
def get_context_data(self, **kwargs)
This add in the context of breeding_type and sets it to Search it also returns the query and the queryset.
2.920482
2.217542
1.316991
return super(BreedingCreate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
10.35025
8.534629
1.212736
return super(BreedingUpdate, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
9.679308
9.23477
1.048137
return super(BreedingDelete, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
11.862206
10.717817
1.106774
return super(AnimalYearArchive, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
13.459472
10.956478
1.228449
return super(AnimalMonthArchive, self).dispatch(*args, **kwargs)
def dispatch(self, *args, **kwargs)
This decorator sets this view to have restricted permissions.
13.822474
12.331232
1.120932
from mousedb.animal.models import CROSS_TYPE crosstype_reverse = dict((v, k) for k, v in CROSS_TYPE) try: crosstype = crosstype_reverse[self.kwargs['breeding_type']] except KeyError: raise Http404 strain = get_object_or_404(Strain, St...
def queryset(self)
This function sets the queryset according to the keyword arguments. For the crosstype, the input value is the the display value of CROSS_TYPE. This is done because the spaces in HET vs HET are not recognized. Therefore the queryset must be matched exactly (ie by case so Intercross not intercro...
4.478358
3.188713
1.404441
context = super(CrossTypeAnimalList, self).get_context_data(**kwargs) context['list_type'] = self.kwargs['breeding_type'] return context
def get_context_data(self, **kwargs)
This add in the context of list_type and returns this as whatever the crosstype was.
6.880825
4.056395
1.696291
'''Adds to the context all issues, conditions and treatments.''' context = super(VeterinaryHome, self).get_context_data(**kwargs) context['medical_issues'] = MedicalIssue.objects.all() context['medical_conditions'] = MedicalCondition.objects.all() context['medical_treatments'] = ...
def get_context_data(self, **kwargs)
Adds to the context all issues, conditions and treatments.
3.926872
2.365423
1.660114
if channels is None: channels = self.channels if channels == 1: out = np.zeros(n) elif channels == 2: out = np.zeros((n, 2)) else: print "Input needs to be 1 or 2 channels" return if n > self.remaining_frames()...
def read_frames(self, n, channels=None)
Read ``n`` frames from the track, starting with the current frame :param integer n: Number of frames to read :param integer channels: Number of channels to return (default is number of channels in track) :returns: Next ``n`` frames from the track, starting with ``current_fra...
2.311245
2.305018
1.002702
self.sound.seek(n) self._current_frame = n
def current_frame(self, n)
Sets current frame to ``n`` :param integer n: Frame to set to ``current_frame``
11.404387
13.086899
0.871435
tmp_current = self.current_frame self.current_frame = start_sample tmp_frames = self.read_frames(end_sample - start_sample) if self.channels == 2: frames = np.mean(tmp_frames, axis=1) elif self.channels == 1: frames = tmp_frames else: ...
def range_as_mono(self, start_sample, end_sample)
Get a range of frames as 1 combined channel :param integer start_sample: First frame in range :param integer end_sample: Last frame in range (exclusive) :returns: Track frames in range as 1 combined channel :rtype: 1d numpy array of length ``end_sample - start_sample``
2.816006
2.837308
0.992492
if duration == 0: duration = self.sound.nframes self.current_frame = start arr = self.read_frames(duration) # get the frame of the maximum amplitude # different names for the same thing... # max_amp_sample = a.argmax(axis=0)[a.max(axis=0).argmax()] ...
def loudest_time(self, start=0, duration=0)
Find the loudest time in the window given by start and duration Returns frame number in context of entire track, not just the window. :param integer start: Start frame :param integer duration: Number of frames to consider from start :returns: Frame number of loudest frame :rtype...
6.059705
6.62149
0.915157
n_in_samples = int(n * self.samplerate) search_start = n_in_samples - self.samplerate if search_start < 0: search_start = 0 frame = zero_crossing_last( self.range_as_mono(search_start, n_in_samples)) + search_start return frame / float(self.sam...
def zero_crossing_before(self, n)
Find nearest zero crossing in waveform before frame ``n``
5.101511
4.230179
1.20598
n_in_samples = int(n * self.samplerate) search_end = n_in_samples + self.samplerate if search_end > self.duration: search_end = self.duration frame = zero_crossing_first( self.range_as_mono(n_in_samples, search_end)) + n_in_samples return frame ...
def zero_crossing_after(self, n)
Find nearest zero crossing in waveform after frame ``n``
5.017103
4.079947
1.229698
if self.labels is None: return None prev_label = None for l in self.labels: if l.time > t: break prev_label = l if prev_label is None: return None return prev_label.name
def label(self, t)
Get the label of the song at a given time in seconds
2.734351
2.550911
1.071911
'''Set a parameter in this configuration set.''' self.data[param] = value self._object.configuration_data = utils.dict_to_nvlist(self.data)
def set_param(self, param, value)
Set a parameter in this configuration set.
10.20924
8.269607
1.23455
'''Reload the configuration set data.''' self._object = object self._description = description self._data = data
def _reload(self, object, description, data)
Reload the configuration set data.
8.011966
5.237853
1.529628
prog_type = self.__program.program_type return self._setting / self.SETTING_DIVIDES[prog_type]
def setting(self)
Load setting (Amps, Watts, or Ohms depending on program mode)
18.246284
13.553617
1.34623
cnt = 0 if len(self._prog_steps) >= start: # yields actual steps for encoding for step in self._prog_steps[start:start+5]: yield((step.raw_data)) cnt += 1 while cnt < 5: yield((0, 0)) cnt += 1
def partial_steps_data(self, start=0)
Iterates 5 steps from start position and provides tuple for packing into buffer. returns (0, 0) if stpe doesn't exist. :param start: Position to start from (typically 0 or 5) :yield: (setting, duration)
7.016268
6.390339
1.097949
if len(self._prog_steps) < 10: self._prog_steps.append(ProgramStep(self, setting, duration)) else: raise IndexError("Maximum of 10 steps are allowed")
def add_step(self, setting, duration)
Adds steps to a program. :param setting: Current, Wattage or Resistance, depending on program mode. :param duration: Length of step in seconds. :return: None
4.120795
3.819287
1.078944
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps)) offset = 5 for ind, step in enumerate(self.partial_steps_data(0)): struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
def load_buffer_one_to_five(self, out_buffer)
Loads first program buffer (0x93) with everything but first three bytes and checksum
5.281373
5.346557
0.987808
offset = 3 for ind, step in enumerate(self.partial_steps_data(5)): struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1]) struct.pack_into(b"< B x", out_buffer, 23, self._program_mode)
def load_buffer_six_to_ten(self, out_buffer)
Loads second program buffer (0x94) with everything but first three bytes and checksum
6.99948
6.553006
1.068133
new_val = int(round(resistance * 100)) if not 0 <= new_val <= 50000: raise ValueError("Load Resistance should be between 0-500 ohms") self._load_mode = self.SET_TYPE_RESISTANCE self._load_value = new_val self.__set_parameters()
def set_load_resistance(self, resistance)
Changes load to resistance mode and sets resistance value. Rounds to nearest 0.01 Ohms :param resistance: Load Resistance in Ohms (0-500 ohms) :return: None
4.612295
3.710604
1.243004
new_val = int(round(power_watts * 10)) if not 0 <= new_val <= 2000: raise ValueError("Load Power should be between 0-200 W") self._load_mode = self.SET_TYPE_POWER self._load_value = new_val self.__set_parameters()
def set_load_power(self, power_watts)
Changes load to power mode and sets power value. Rounds to nearest 0.1W. :param power_watts: Power in Watts (0-200) :return:
4.550391
4.290977
1.060456
new_val = int(round(current_amps * 1000)) if not 0 <= new_val <= 30000: raise ValueError("Load Current should be between 0-30A") self._load_mode = self.SET_TYPE_CURRENT self._load_value = new_val self.__set_parameters()
def set_load_current(self, current_amps)
Changes load to current mode and sets current value. Rounds to nearest mA. :param current_amps: Current in Amps (0-30A) :return: None
4.545107
3.839555
1.183759
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command)
def __set_buffer_start(self, command)
This sets the first three bytes and clears the other 23 bytes. :param command: Command Code to set :return: None
14.41106
13.963512
1.032051
checksum = self.__get_checksum(self.__out_buffer.raw) self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum)
def __set_checksum(self)
Sets the checksum on the last byte of buffer, based on values in the buffer :return: None
5.286808
6.367664
0.830259
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
def __clear_in_buffer(self)
Zeros out the in buffer :return: None
5.636445
6.130515
0.919408
bytes_written = self.serial.write(self.__out_buffer.raw) if self.DEBUG_MODE: print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw))) if bytes_written != len(self.__out_buffer): raise IOError("{} bytes written for output buffer of size {}".format(byte...
def __send_buffer(self)
Sends the contents of self.__out_buffer to serial device :return: Number of bytes written
3.397051
3.139686
1.081972
self.__clear_in_buffer() self.__send_buffer() read_string = self.serial.read(len(self.__in_buffer)) if self.DEBUG_MODE: print("Read: '{}'".format(binascii.hexlify(read_string))) if len(read_string) != len(self.__in_buffer): raise IOError("{} bytes...
def __send_receive_buffer(self)
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer :return: None
3.26247
3.101177
1.05201
self.__set_buffer_start(self.CMD_SET_PARAMETERS) # Can I send 0xFF as address to not change it each time? # Worry about writing to EEPROM or Flash with each address change. # Would then implement a separate address only change function. self.STRUCT_SET_PARAMETERS.pack_in...
def __set_parameters(self)
Sets Load Parameters from class values, including: Max Current, Max Power, Address, Load Mode, Load Value :return: None
11.019018
8.380141
1.314896
# I think retry should be in here. # Throw exceptions in __update_status and handle here cur_count = max(retry_count, 0) while cur_count >= 0: try: self.__update_status() except IOError as err: if self.print_errors: ...
def update_status(self, retry_count=2)
Updates current values from load. Must be called to get latest values for the following properties of class: current voltage power max current max power resistance local_control load_on wrong_polarity excessive_t...
3.533296
2.728549
1.294936
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5) array_program.load_buffer_one_to_five(self.__out_buffer) self.__set_checksum() self.__send_buffer() self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10) array_program.load_buffer_six_to_ten(self.__out_buffer) ...
def set_program_sequence(self, array_program)
Sets program up in load. :param array_program: Populated Array3710Program object :return: None
3.378978
3.28984
1.027095
self.__set_buffer_start(self.CMD_START_PROG) self.__set_checksum() self.__send_buffer() # Turn on Load if not on if turn_on_load and not self.load_on: self.load_on = True
def start_program(self, turn_on_load=True)
Starts running programmed test sequence :return: None
5.289204
5.509108
0.960084
self.__set_buffer_start(self.CMD_STOP_PROG) self.__set_checksum() self.__send_buffer() if turn_off_load and self.load_on: self.load_on = False
def stop_program(self, turn_off_load=True)
Stops running programmed test sequence :return: None
5.321751
5.437732
0.978671
logger.debug("Running %s check", self.name) try: result = self.perform() except Exception: logger.exception("Error while performing %s check", self.name) result = False logger.debug("Result: %s", result) self.results.append(result) ...
def run(self)
Calls the `perform()` method defined by subclasses and stores the result in a `results` deque. After the result is determined the `results` deque is analyzed to see if the `passing` flag should be updated. If the check was considered passing and the previous `self.fall` number of check...
3.020574
2.299276
1.313707
return list( itertools.islice( self.results, len(self.results) - n, len(self.results) ) )
def last_n_results(self, n)
Helper method for returning a set number of the previous check results.
3.311676
3.011105
1.099821
self.rise = int(config["rise"]) self.fall = int(config["fall"]) self.apply_check_config(config) if self.results.maxlen == max(self.rise, self.fall): return results = list(self.results) while len(results) > max(self.rise, self.fall): res...
def apply_config(self, config)
Sets attributes based on the given config. Also adjusts the `results` deque to either expand (padding itself with False results) or contract (by removing the oldest results) until it matches the required length.
3.173388
2.581496
1.229283
if "rise" not in config: raise ValueError("No 'rise' configured") if "fall" not in config: raise ValueError("No 'fall' configured") cls.validate_check_config(config)
def validate_config(cls, config)
Validates that required config entries are present. Each check requires a `host`, `port`, `rise` and `fall` to be configured. The rise and fall variables are integers denoting how many times a check must pass before being considered passing and how many times a check must fail ...
4.618864
3.60465
1.281363
doc_core_sems, all_concepts = self._extract_core_semantics(docs) shape = (len(docs), len(all_concepts)) vecs = np.zeros(shape) for i, core_sems in enumerate(doc_core_sems): for con, weight in core_sems: j = all_concepts.index(con) vec...
def vectorize(self, docs)
Vectorizes a list of documents using their DCS representations.
4.053419
3.985484
1.017046
# Prep doc = doc.lower() tagged_tokens = [(t, penn_to_wordnet(t.tag_)) for t in spacy(doc, tag=True, parse=False, entity=False)] tokens = [t for t, tag in tagged_tokens] term_concept_map = self._disambiguate_doc(tagged_tokens) concept_weights = self._weight_conce...
def _process_doc(self, doc)
Applies DCS to a document to extract its core concepts and their weights.
4.155661
3.658733
1.13582
# Group tokens by PoS pos_groups = {pos: [] for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADV]} for tok, tag in tagged_tokens: if tag in pos_groups: pos_groups[tag].append(tok) #print(pos_groups) # Map of final term -> concept mappings m...
def _disambiguate_doc(self, tagged_tokens)
Takes a list of tagged tokens, representing a document, in the form: [(token, tag), ...] And returns a mapping of terms to their disambiguated concepts (synsets).
3.405315
3.061813
1.112189
# Map the terms to candidate concepts # Consider only the top 3 most common senses candidate_map = {term: wn.synsets(term, pos=pos)[:3] for term in terms} # Filter to unique concepts concepts = set(c for cons in candidate_map.values() for c in cons) # Back to l...
def _disambiguate_pos(self, terms, pos)
Disambiguates a list of tokens of a given PoS.
4.039279
3.959227
1.020219
n_cons = len(concepts) sim_mat = np.zeros((n_cons, n_cons)) for i, c1 in enumerate(concepts): for j, c2 in enumerate(concepts): # Just build the lower triangle if i >= j: sim_mat[i,j] = self._semsim(c1, c2) if i != j else 1...
def _similarity_matrix(self, concepts)
Computes a semantic similarity matrix for a set of concepts.
2.750867
2.669389
1.030523
if c1 == c2: return 1. if (c1, c2) in self.concept_sims: return self.concept_sims[(c1, c2)] elif (c2, c1) in self.concept_sims: return self.concept_sims[(c2, c1)] else: need_root = c1._needs_root() subsumers = c1.low...
def _semsim(self, c1, c2)
Computes the semantic similarity between two concepts. The semantic similarity is a combination of two sem sims: 1. An "explicit" sem sim metric, that is, one which is directly encoded in the WordNet graph. Here it is just Wu-Palmer similarity. 2. An "implicit" sem sim met...
2.801435
2.514017
1.114327
desc1 = self._description(c1) desc2 = self._description(c2) raw_sim = 1/(sift4(desc1, desc2) + 1) return math.log(raw_sim + 1)
def _imp_semsim(self, c1, c2)
The paper's implicit semantic similarity metric involves iteratively computing string overlaps; this is a modification where we instead use inverse Sift4 distance (a fast approximation of Levenshtein distance). Frankly ~ I don't know if this is an appropriate substitute, so I'll...
5.100537
3.63838
1.40187
chain_scores = [self._score_chain(lex_chain, adj_submat, concept_weights) for lex_chain, adj_submat in lex_chains] scored_chains = zip(lex_chains, chain_scores) scored_chains = sorted(scored_chains, key=lambda x: x[1], reverse=True) thresh = (self.alpha/len(lex_chains)) * sum(c...
def _core_semantics(self, lex_chains, concept_weights)
Returns the n representative lexical chains for a document.
3.183008
3.068568
1.037294
all_concepts = [] doc_core_sems = [] for doc in docs: core_sems = self._process_doc(doc) doc_core_sems.append(core_sems) all_concepts += [con for con, weight in core_sems] return doc_core_sems, list(set(all_concepts))
def _extract_core_semantics(self, docs)
Extracts core semantics for a list of documents, returning them along with a list of all the concepts represented.
2.910375
2.559035
1.137294
concepts = list({c for c in term_concept_map.values()}) # Build an adjacency matrix for the graph # Using the encoding: # 1 = identity/synonymy, 2 = hypernymy/hyponymy, 3 = meronymy, 0 = no edge n_cons = len(concepts) adj_mat = np.zeros((n_cons, n_cons)) ...
def _lexical_chains(self, doc, term_concept_map)
Builds lexical chains, as an adjacency matrix, using a disambiguated term-concept map.
3.631979
3.585643
1.012923
scores = [] # Compute scores for concepts in the chain for i, c in enumerate(lexical_chain): score = concept_weights[c] * self.relation_weights[0] rel_scores = [] for j, c_ in enumerate(lexical_chain): if adj_submat[i,j] == 2: ...
def _score_chain(self, lexical_chain, adj_submat, concept_weights)
Computes the score for a lexical chain.
2.465425
2.429454
1.014806
weights = {c: 0 for c in term_concept_map.values()} for t in tokens: # Skip terms that aren't one of the PoS we used if t not in term_concept_map: continue con = term_concept_map[t] weights[con] += 1 # TO DO paper doesn't...
def _weight_concepts(self, tokens, term_concept_map)
Calculates weights for concepts in a document. This is just the frequency of terms which map to a concept.
6.228999
6.168427
1.00982
if concept not in self.descriptions: lemmas = concept.lemma_names() gloss = self._gloss(concept) glosses = [self._gloss(rel) for rel in self._related(concept)] raw_desc = ' '.join(lemmas + [gloss] + glosses) desc = [w for w in raw_desc.split()...
def _description(self, concept)
Returns a "description" of a concept, as defined in the paper. The paper describes the description as a string, so this is a slight modification where we instead represent the definition as a list of tokens.
3.34679
3.246069
1.031028
return concept.hypernyms() + \ concept.hyponyms() + \ concept.member_meronyms() + \ concept.substance_meronyms() + \ concept.part_meronyms() + \ concept.member_holonyms() + \ concept.substance_holonyms() + \...
def _related(self, concept)
Returns related concepts for a concept.
2.071361
1.993193
1.039217
# Make sure exist are set if "exists" not in env: env.exists = exists if "run" not in env: env.run = run if "cd" not in env: env.cd = cd if "max_releases" not in env: env.max_releases = 5 if "public_path" in env: public_path = env.public_path.rst...
def init_tasks()
Performs basic setup before any of the tasks are run. All tasks needs to run this before continuing. It only fires once.
4.331882
4.151301
1.0435
init_tasks() run_hook("before_setup") # Create shared folder env.run("mkdir -p %s" % (paths.get_shared_path())) env.run("chmod 755 %s" % (paths.get_shared_path())) # Create backup folder env.run("mkdir -p %s" % (paths.get_backup_path())) env.run("chmod 750 %s" % (paths.get_backu...
def setup()
Creates shared and upload directory then fires setup to recipes.
2.323053
2.11593
1.097888
init_tasks() if not has_hook("copy"): return report("No copy method has been defined") if not env.exists(paths.get_shared_path()): return report("You need to run setup before running deploy") run_hook("before_deploy") release_name = int(time.time()*1000) release_path = ...
def deploy()
Performs a deploy by invoking copy, then generating next release name and invoking necessary hooks.
3.570494
3.546226
1.006843
init_tasks() run_hook("before_rollback") # Remove current version current_release = paths.get_current_release_path() if current_release: env.run("rm -rf %s" % current_release) # Restore previous version old_release = paths.get_current_release_name() if old_release: ...
def rollback()
Rolls back to previous release
4.182578
3.934226
1.063126
init_tasks() max_versions = limit + 1 env.run("ls -dt %s/*/ | tail -n +%s | xargs rm -rf" % ( paths.get_releases_path(), max_versions) )
def cleanup_releases(limit=5)
Removes older releases.
10.285742
9.657994
1.064998
if force or db not in cls._cache: cls._cache[db] = cls._new_from_db(db) return cls._cache[db]
def from_db(cls, db, force=False)
Make instance from database. For performance, this caches the episode types for the database. The `force` parameter can be used to bypass this.
2.831313
2.963906
0.955264