code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class CanalSchema(SchemaObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.schema = 'Canal' | Schema Mixin for Canal
Usage: place after django model in class definition, schema will return the schema.org url for the object
A canal, like the Panama Canal. | 6259904d0c0af96317c57786 |
class itkBinaryThresholdImageFilterID3IF3_Superclass(itkInPlaceImageFilterAPython.itkInPlaceImageFilterID3IF3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkBinaryThresholdImageFilterPython.itkBinaryThresholdImageFilterID3IF3_Superclass___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def GetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkBinaryThresholdImageFilterPython.itkBinaryThresholdImageFilterID3IF3_Superclass_GetFunctor(self, *args) <NEW_LINE> <DEDENT> def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkBinaryThresholdImageFilterPython.itkBinaryThresholdImageFilterID3IF3_Superclass_SetFunctor(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkBinaryThresholdImageFilterPython.delete_itkBinaryThresholdImageFilterID3IF3_Superclass <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkBinaryThresholdImageFilterPython.itkBinaryThresholdImageFilterID3IF3_Superclass_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkBinaryThresholdImageFilterPython.itkBinaryThresholdImageFilterID3IF3_Superclass_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkBinaryThresholdImageFilterID3IF3_Superclass.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkBinaryThresholdImageFilterID3IF3_Superclass class | 6259904ebe383301e0254c66 |
class TestBenchIcarusOuter(TestBenchIcarusBase): <NEW_LINE> <INDENT> signal_names = ['clk', 'reset', 'in_data', 'in_nd', 'out_data', 'out_nd', 'error'] <NEW_LINE> def __init__(self, executable, in_samples=None, start_msgs=None, in_raw=None, sendnth=config.default_sendnth, width=config.default_width, output_msgs=True): <NEW_LINE> <INDENT> super(TestBenchIcarusOuter, self).__init__() <NEW_LINE> self.executable = executable <NEW_LINE> self.in_samples = in_samples <NEW_LINE> self.start_msgs = start_msgs <NEW_LINE> self.in_raw = in_raw <NEW_LINE> if (in_raw is not None) and (in_samples is not None or start_msgs is not None): <NEW_LINE> <INDENT> raise ValueError("Cannot specify both (in_samples and/or start_msgs) and in_raw") <NEW_LINE> <DEDENT> self.sendnth = sendnth <NEW_LINE> self.width = width <NEW_LINE> self.output_msgs = output_msgs <NEW_LINE> self.drivers = [self.clk_driver, self.get_output, self.send_input, self.prerun, self.check_error] <NEW_LINE> if self.in_raw is None: <NEW_LINE> <INDENT> self.in_raw = [] <NEW_LINE> if self.start_msgs is not None: <NEW_LINE> <INDENT> self.in_raw += self.start_msgs <NEW_LINE> <DEDENT> self.in_raw += [c_to_int(d, self.width/2-1) for d in self.in_samples] <NEW_LINE> <DEDENT> <DEDENT> def run(self, steps_rqd): <NEW_LINE> <INDENT> super(TestBenchIcarusOuter, self).run(steps_rqd) <NEW_LINE> header_shift = pow(2, self.width-1) <NEW_LINE> if self.output_msgs: <NEW_LINE> <INDENT> samples, packets = stream_to_samples_and_packets(self.out_raw) <NEW_LINE> for s in samples: <NEW_LINE> <INDENT> if s == config.errorcode: <NEW_LINE> <INDENT> raise ValueError("Errorcode detected.") <NEW_LINE> <DEDENT> <DEDENT> self.out_samples = [int_to_c(s, self.width/2-1) for s in samples] <NEW_LINE> self.out_messages = packets <NEW_LINE> <DEDENT> <DEDENT> def prerun(self): <NEW_LINE> <INDENT> self.first = True <NEW_LINE> self.done_header = False <NEW_LINE> self.doing_prerun = True <NEW_LINE> self.msg_pos = 0 <NEW_LINE> @always(self.clk.posedge) <NEW_LINE> def run(): <NEW_LINE> <INDENT> if self.first: <NEW_LINE> <INDENT> self.first = False <NEW_LINE> self.reset.next = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reset.next = 0 <NEW_LINE> self.doing_prerun = False <NEW_LINE> <DEDENT> <DEDENT> return run | A testbench to test a module using Icarus verilog.
Only a single data connection in and out.
Shared by data and messages.
No possibility to pass meta data currently.
Message can only be sent before sending samples.
Args:
executable: The Icarus executable
in_samples: The input samples.
start_msgs: Messages to send before sending samples.
in_raw: The raw input integers can be specified, instead of
in_samples and start_msgs.
sendnth: How often to send a new sample.
width: The bit width of the input data | 6259904eb830903b9686eea0 |
class RecordStream(object): <NEW_LINE> <INDENT> def __init__(self, graph, response): <NEW_LINE> <INDENT> self.graph = graph <NEW_LINE> self.__response = response <NEW_LINE> self.__response_item = self.__response_iterator() <NEW_LINE> self.columns = next(self.__response_item) <NEW_LINE> log.info("stream %r", self.columns) <NEW_LINE> <DEDENT> def __response_iterator(self): <NEW_LINE> <INDENT> producer = None <NEW_LINE> columns = [] <NEW_LINE> record_data = None <NEW_LINE> for key, value in self.__response: <NEW_LINE> <INDENT> key_len = len(key) <NEW_LINE> if key_len > 0: <NEW_LINE> <INDENT> section = key[0] <NEW_LINE> if section == "columns": <NEW_LINE> <INDENT> if key_len > 1: <NEW_LINE> <INDENT> columns.append(value) <NEW_LINE> <DEDENT> <DEDENT> elif section == "data": <NEW_LINE> <INDENT> if key_len == 1: <NEW_LINE> <INDENT> producer = RecordProducer(columns) <NEW_LINE> yield tuple(columns) <NEW_LINE> <DEDENT> elif key_len == 2: <NEW_LINE> <INDENT> if record_data is not None: <NEW_LINE> <INDENT> yield producer.produce(self.graph.hydrate(assembled(record_data))) <NEW_LINE> <DEDENT> record_data = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> record_data.append((key[2:], value)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if record_data is not None: <NEW_LINE> <INDENT> yield producer.produce(self.graph.hydrate(assembled(record_data))) <NEW_LINE> <DEDENT> self.close() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return next(self.__response_item) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return self.__next__() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.__response.close() | An accessor for a sequence of records yielded by a streamed Cypher statement.
::
for record in graph.cypher.stream("MATCH (n) RETURN n LIMIT 10")
print record[0]
Each record returned is cast into a :py:class:`namedtuple` with names
derived from the resulting column names.
.. note ::
Results are available as returned from the server and are decoded
incrementally. This means that there is no need to wait for the
entire response to be received before processing can occur. | 6259904e379a373c97d9a476 |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect) | Класс для управления пулямии выпущенными кораблем | 6259904e82261d6c527308ec |
class SmqtkProcess (object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.logfile = None <NEW_LINE> self.proc = None <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def logfile_name(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def args(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def run(self, log_dir): <NEW_LINE> <INDENT> self.logfile = open(os.path.join(log_dir, self.logfile_name()), 'w') <NEW_LINE> self.proc = subprocess.Popen(self.args(), stdout=self.logfile, stderr=self.logfile) <NEW_LINE> <DEDENT> def cleanup(self, *args): <NEW_LINE> <INDENT> if self.proc.poll() is None: <NEW_LINE> <INDENT> self.proc.send_signal(signal.SIGINT) <NEW_LINE> <DEDENT> if self.logfile: <NEW_LINE> <INDENT> self.logfile.close() <NEW_LINE> self.logfile = None | Base class of SMQTK System process encapsulation
| 6259904ecb5e8a47e493cbac |
class EmailCampaignTemplateAllOfSenderData(object): <NEW_LINE> <INDENT> openapi_types = { 'name': 'str', 'value': 'str' } <NEW_LINE> attribute_map = { 'name': 'name', 'value': 'value' } <NEW_LINE> def __init__(self, name=None, value=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._name = None <NEW_LINE> self._value = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if value is not None: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EmailCampaignTemplateAllOfSenderData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EmailCampaignTemplateAllOfSenderData): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259904e3617ad0b5ee0758b |
class Solution: <NEW_LINE> <INDENT> def findRadius(self, houses, heaters): <NEW_LINE> <INDENT> ret = 0 <NEW_LINE> houses.sort() <NEW_LINE> heaters.sort() <NEW_LINE> j = 0 <NEW_LINE> for i in range(len(houses)): <NEW_LINE> <INDENT> while j < (len(heaters) - 1): <NEW_LINE> <INDENT> diff_1 = abs(heaters[j] - houses[i]) <NEW_LINE> diff_2 = abs(heaters[j + 1] - houses[i]) <NEW_LINE> if diff_1 >= diff_2: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> ret = max(ret, abs(heaters[j] - houses[i])) <NEW_LINE> <DEDENT> return ret | @param houses: positions of houses
@param heaters: positions of heaters
@return: the minimum radius standard of heaters | 6259904e435de62698e9d254 |
class Solution: <NEW_LINE> <INDENT> def generatePossibleNextMoves(self, s): <NEW_LINE> <INDENT> if "++" in s: <NEW_LINE> <INDENT> next_moves = [] <NEW_LINE> for i in range(len(s)-1): <NEW_LINE> <INDENT> if s[i] == "+" and s[i+1] == "+": <NEW_LINE> <INDENT> next_moves.append(s[:i] + "--" + s[i+2:]) <NEW_LINE> <DEDENT> <DEDENT> return next_moves <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] | @param s: the given string
@return: all the possible states of the string after one valid move | 6259904e50485f2cf55dc3d7 |
class API(Thread): <NEW_LINE> <INDENT> def __init__(self,func,**param): <NEW_LINE> <INDENT> super(API,self).__init__() <NEW_LINE> self.func = func <NEW_LINE> self.param = param <NEW_LINE> self.result = [] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if callable(getattr(self ,self.func)): <NEW_LINE> <INDENT> if isinstance(self.param,dict) and self.param !={}: <NEW_LINE> <INDENT> self.result = getattr(self, self.func)(**self.param) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.result = getattr(self, self.func)() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_hosts(self,**idc_dict): <NEW_LINE> <INDENT> idc = idc_dict['prefix'] <NEW_LINE> try: <NEW_LINE> <INDENT> hosts = get_amazon_regions(region=idc).get_only_instances() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if hosts == None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> for i in hosts: <NEW_LINE> <INDENT> param={} <NEW_LINE> param['outer_ip'] = i.ip_address <NEW_LINE> param['hostname'] = i.tags['Name'] <NEW_LINE> param['wxsn'] =i.id <NEW_LINE> param['inner_ip'] = i.private_ip_address <NEW_LINE> param['purchase_date'] =i.launch_time.replace('T',' ').replace('Z','') <NEW_LINE> param['is_del'] = 0 if i.state=='running' else 1 <NEW_LINE> self.result.append(param) <NEW_LINE> <DEDENT> return self.result <NEW_LINE> <DEDENT> def get_idcs(self): <NEW_LINE> <INDENT> regions = get_amazon_regions() <NEW_LINE> for i in regions: <NEW_LINE> <INDENT> param ={} <NEW_LINE> param['name'] = u'amazon' + '['+i.name+']' <NEW_LINE> param['prefix']= i.name <NEW_LINE> self.result.append(param) <NEW_LINE> <DEDENT> return self.result <NEW_LINE> <DEDENT> def get_balancers(self,**idc_dict): <NEW_LINE> <INDENT> idc = idc_dict['prefix'] <NEW_LINE> balances = get_amazon_regions(region=idc,type='ebl').get_all_load_balancers() <NEW_LINE> for i in balances: <NEW_LINE> <INDENT> children = [] <NEW_LINE> for instance_info in i.instances: <NEW_LINE> <INDENT> children.append(instance_info.id) <NEW_LINE> <DEDENT> myaddr = socket.getaddrinfo(i.dns_name,'http')[0][4][0] <NEW_LINE> public_ip = socket.gethostbyaddr(myaddr)[2][0] <NEW_LINE> param={} <NEW_LINE> param['outer_ip'] = public_ip <NEW_LINE> param['hostname'] = i.name <NEW_LINE> param['wxsn'] = i.canonical_hosted_zone_name <NEW_LINE> param['children'] = ','.join(children) <NEW_LINE> self.result.append(param) <NEW_LINE> <DEDENT> return self.result <NEW_LINE> <DEDENT> def get_result(self): <NEW_LINE> <INDENT> return self.result | 6259904eb57a9660fecd2ec8 |
|
class GroupAtom(GroupRSS): <NEW_LINE> <INDENT> feed_type = Atom1Feed <NEW_LINE> subtitle = GroupRSS.description | Atom feed for a group's releases. | 6259904e1f037a2d8b9e5292 |
class ReflexAgent(Agent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [self.evaluationFunction(gameState, action) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> "Add more of your code here if you want to" <NEW_LINE> return legalMoves[chosenIndex] <NEW_LINE> <DEDENT> def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> def sum_food_proximity(cur_pos, food_positions, norm=False): <NEW_LINE> <INDENT> food_distances = [] <NEW_LINE> for food in food_positions: <NEW_LINE> <INDENT> food_distances.append(util.manhattanDistance(food, cur_pos)) <NEW_LINE> <DEDENT> if norm: <NEW_LINE> <INDENT> return normalize(sum(food_distances) if sum(food_distances) > 0 else 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sum(food_distances) if sum(food_distances) > 0 else 1 <NEW_LINE> <DEDENT> <DEDENT> score = successorGameState.getScore() <NEW_LINE> def ghost_stuff(cur_pos, ghost_states, radius, scores): <NEW_LINE> <INDENT> num_ghosts = 0 <NEW_LINE> for ghost in ghost_states: <NEW_LINE> <INDENT> if util.manhattanDistance(ghost.getPosition(), cur_pos) <= radius: <NEW_LINE> <INDENT> scores -= 30 <NEW_LINE> num_ghosts += 1 <NEW_LINE> <DEDENT> <DEDENT> return scores <NEW_LINE> <DEDENT> def food_stuff(cur_pos, food_pos, cur_score): <NEW_LINE> <INDENT> new_food = sum_food_proximity(cur_pos, food_pos) <NEW_LINE> cur_food = sum_food_proximity(currentGameState.getPacmanPosition(), currentGameState.getFood().asList()) <NEW_LINE> new_food = 1/new_food <NEW_LINE> cur_food = 1/cur_food <NEW_LINE> if new_food > cur_food: <NEW_LINE> <INDENT> cur_score += (new_food - cur_food) * 3 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur_score -= 20 <NEW_LINE> <DEDENT> next_food_dist = closest_dot(cur_pos, food_pos) <NEW_LINE> cur_food_dist = closest_dot(currentGameState.getPacmanPosition(), currentGameState.getFood().asList()) <NEW_LINE> if next_food_dist < cur_food_dist: <NEW_LINE> <INDENT> cur_score += (next_food_dist - cur_food_dist) * 3 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur_score -= 20 <NEW_LINE> <DEDENT> return cur_score <NEW_LINE> <DEDENT> def closest_dot(cur_pos, food_pos): <NEW_LINE> <INDENT> food_distances = [] <NEW_LINE> for food in food_pos: <NEW_LINE> <INDENT> food_distances.append(util.manhattanDistance(food, cur_pos)) <NEW_LINE> <DEDENT> return min(food_distances) if len(food_distances) > 0 else 1 <NEW_LINE> <DEDENT> def normalize(distance, layout): <NEW_LINE> <INDENT> return distance <NEW_LINE> <DEDENT> return food_stuff(newPos, newFood.asList(), ghost_stuff(newPos, newGhostStates, 2, score)) | A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers. | 6259904e7cff6e4e811b6e87 |
class Tipo_telefono(models.Model): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Tipo_telefono, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> tipo_telefono = models.CharField(max_length=50, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.tipo_telefono <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Tipo de telefono" <NEW_LINE> verbose_name_plural = "Tipos de telefono" <NEW_LINE> ordering = ['tipo_telefono'] | docstring for Tipo_telefono | 6259904e3539df3088ecd6f0 |
class RandomOrderAug(Augmenter): <NEW_LINE> <INDENT> def __init__(self, ts): <NEW_LINE> <INDENT> super(RandomOrderAug, self).__init__() <NEW_LINE> self.ts = ts <NEW_LINE> <DEDENT> def dumps(self): <NEW_LINE> <INDENT> return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] <NEW_LINE> <DEDENT> def __call__(self, src): <NEW_LINE> <INDENT> src = [src] <NEW_LINE> random.shuffle(self.ts) <NEW_LINE> for t in self.ts: <NEW_LINE> <INDENT> src = [j for i in src for j in t(i)] <NEW_LINE> <DEDENT> return src | Apply list of augmenters in random order
Parameters
----------
ts : list of augmenters
A series of augmenters to be applied in random order | 6259904e3c8af77a43b68964 |
class MovingAverage(object): <NEW_LINE> <INDENT> def __init__(self, window): <NEW_LINE> <INDENT> self.window = window <NEW_LINE> <DEDENT> def simple_moving_average(self, series): <NEW_LINE> <INDENT> return series.ix[-self.window:].mean() <NEW_LINE> <DEDENT> def simple_z_score(self, series): <NEW_LINE> <INDENT> recent = series.ix[-self.window:] <NEW_LINE> return (series.ix[-1] - recent.mean()) / recent.std() <NEW_LINE> <DEDENT> def exponential_moving_average(self, series, alpha): <NEW_LINE> <INDENT> weights = np.array([(1 - alpha) ** i for i in range(self.window)]) <NEW_LINE> return (series.ix[-self.window:] * weights).sum() | Moving Average Class
Provides support for both simple moving averages and exponential moving
averages | 6259904e63d6d428bbee3c18 |
class NamedStyle(Serialisable): <NEW_LINE> <INDENT> font = Typed(expected_type=Font) <NEW_LINE> fill = Typed(expected_type=Fill) <NEW_LINE> border = Typed(expected_type=Border) <NEW_LINE> alignment = Typed(expected_type=Alignment) <NEW_LINE> number_format = NumberFormatDescriptor() <NEW_LINE> protection = Typed(expected_type=Protection) <NEW_LINE> builtinId = Integer(allow_none=True) <NEW_LINE> hidden = Bool(allow_none=True) <NEW_LINE> xfId = Integer(allow_none=True) <NEW_LINE> name = String() <NEW_LINE> def __init__(self, name="Normal", font=Font(), fill=PatternFill(), border=Border(), alignment=Alignment(), number_format=None, protection=Protection(), builtinId=None, hidden=False, xfId=None, ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.font = font <NEW_LINE> self.fill = fill <NEW_LINE> self.border = border <NEW_LINE> self.alignment = alignment <NEW_LINE> self.number_format = number_format <NEW_LINE> self.protection = protection <NEW_LINE> self.builtinId = builtinId <NEW_LINE> self.hidden = hidden <NEW_LINE> self._wb = None <NEW_LINE> self._style = StyleArray() <NEW_LINE> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> super(NamedStyle, self).__setattr__(attr, value) <NEW_LINE> if getattr(self, '_wb', None) and attr in ( 'font', 'fill', 'border', 'alignment', 'number_format', 'protection', ): <NEW_LINE> <INDENT> self._recalculate() <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for key in ('name', 'builtinId', 'hidden', 'xfId'): <NEW_LINE> <INDENT> value = getattr(self, key, None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> yield key, safe_string(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def xfId(self): <NEW_LINE> <INDENT> return self._style.xfId <NEW_LINE> <DEDENT> def _set_index(self, idx): <NEW_LINE> <INDENT> self._style.xfId = idx <NEW_LINE> <DEDENT> def bind(self, wb): <NEW_LINE> <INDENT> self._wb = wb <NEW_LINE> self._recalculate() <NEW_LINE> <DEDENT> def _recalculate(self): <NEW_LINE> <INDENT> self._style.fontId = self._wb._fonts.add(self.font) <NEW_LINE> self._style.borderId = self._wb._borders.add(self.border) <NEW_LINE> self._style.fillId = self._wb._fills.add(self.fill) <NEW_LINE> self._style.protectionId = self._wb._protections.add(self.protection) <NEW_LINE> self._style.alignmentId = self._wb._alignments.add(self.alignment) <NEW_LINE> fmt = self.number_format <NEW_LINE> if fmt in BUILTIN_FORMATS_REVERSE: <NEW_LINE> <INDENT> fmt = BUILTIN_FORMATS_REVERSE[fmt] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fmt = self._wb._number_formats.add(self.number_format) + 164 <NEW_LINE> <DEDENT> self._style.numFmtId = fmt <NEW_LINE> <DEDENT> def as_tuple(self): <NEW_LINE> <INDENT> return self._style <NEW_LINE> <DEDENT> def as_xf(self): <NEW_LINE> <INDENT> xf = CellStyle.from_array(self._style) <NEW_LINE> xf.xfId = None <NEW_LINE> xf.pivotButton = None <NEW_LINE> xf.quotePrefix = None <NEW_LINE> return xf <NEW_LINE> <DEDENT> def as_name(self): <NEW_LINE> <INDENT> named = _NamedCellStyle( name=self.name, builtinId=self.builtinId, hidden=self.hidden, xfId=self.xfId ) <NEW_LINE> return named | Named and editable styles | 6259904ed6c5a102081e356a |
class DeltaField(Field): <NEW_LINE> <INDENT> def __init__(self, doc, **kwargs): <NEW_LINE> <INDENT> super(DeltaField, self).__init__(doc, datetime.timedelta, **kwargs) <NEW_LINE> <DEDENT> def convert(self, value): <NEW_LINE> <INDENT> if isinstance(value, (int, long)): <NEW_LINE> <INDENT> value = datetime.timedelta(seconds=value) <NEW_LINE> <DEDENT> return value | A field which accepts only :class:`datetime.timedelta` type. | 6259904e26068e7796d4dd91 |
class RabiResult: <NEW_LINE> <INDENT> def __init__(self, rabi_angles: Sequence[float], excited_state_probabilities: Sequence[float]): <NEW_LINE> <INDENT> self._rabi_angles = rabi_angles <NEW_LINE> self._excited_state_probs = excited_state_probabilities <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self) -> Sequence[Tuple[float, float]]: <NEW_LINE> <INDENT> return [(angle, prob) for angle, prob in zip(self._rabi_angles, self._excited_state_probs)] <NEW_LINE> <DEDENT> def plot(self, ax: Optional[plt.Axes] = None, **plot_kwargs: Any) -> plt.Axes: <NEW_LINE> <INDENT> show_plot = not ax <NEW_LINE> if not ax: <NEW_LINE> <INDENT> fig, ax = plt.subplots(1, 1, figsize=(8, 8)) <NEW_LINE> <DEDENT> ax.set_ylim([0, 1]) <NEW_LINE> ax.plot(self._rabi_angles, self._excited_state_probs, 'ro-', **plot_kwargs) <NEW_LINE> ax.set_xlabel(r"Rabi Angle (Radian)") <NEW_LINE> ax.set_ylabel('Excited State Probability') <NEW_LINE> if show_plot: <NEW_LINE> <INDENT> fig.show() <NEW_LINE> <DEDENT> return ax | Results from a Rabi oscillation experiment. | 6259904e3cc13d1c6d466b86 |
class DOS(HelperFunctions): <NEW_LINE> <INDENT> cal_dts = { 'matterial': 'Si', 'temp': 300., 'author': None, } <NEW_LINE> author_list = 'DOS.models' <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> temp = locals().copy() <NEW_LINE> del temp['self'] <NEW_LINE> self._update_dts(**temp) <NEW_LINE> author_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), self.cal_dts['matterial'], self.author_list) <NEW_LINE> self._int_model(author_file) <NEW_LINE> self.change_model(self.cal_dts['author']) <NEW_LINE> <DEDENT> def update(self, **kwargs): <NEW_LINE> <INDENT> self._update_dts(**kwargs) <NEW_LINE> if 'author' in kwargs.keys(): <NEW_LINE> <INDENT> self.change_model(self.cal_dts['author']) <NEW_LINE> <DEDENT> if 'egi_author' in self.vals.keys(): <NEW_LINE> <INDENT> Eg0 = Egi(matterial=self.cal_dts['matterial']).update( temp=0, author=self.vals['egi_author']) <NEW_LINE> Egratio = Eg0 / Egi(matterial=self.cal_dts['matterial']).update( temp=self.cal_dts['temp'], author=self.vals['egi_author']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Egratio = None <NEW_LINE> <DEDENT> self.Nc, self.Nv = getattr(dos_models, self.model)( self.vals, temp=self.cal_dts['temp'], Egratio=Egratio) <NEW_LINE> return self.Nc, self.Nv <NEW_LINE> <DEDENT> def check_models(self): <NEW_LINE> <INDENT> temp = np.logspace(0, np.log10(600)) <NEW_LINE> num = len(self.available_models()) <NEW_LINE> fig, ax = plt.subplots(1) <NEW_LINE> self.plotting_colours(num, fig, ax, repeats=2) <NEW_LINE> for author in self.available_models(): <NEW_LINE> <INDENT> Nc, Nv = self.update(temp, author) <NEW_LINE> ax.plot(temp, Nc, '--') <NEW_LINE> ax.plot(temp, Nv, '.', label=author) <NEW_LINE> <DEDENT> ax.loglog() <NEW_LINE> leg1 = ax.legend(loc=0, title='colour legend') <NEW_LINE> Nc, = ax.plot(np.inf, np.inf, 'k--', label='Nc') <NEW_LINE> Nv, = ax.plot(np.inf, np.inf, 'k.', label='Nv') <NEW_LINE> plt.legend([Nc, Nv], ['Nc', 'Nv'], loc=4, title='Line legend') <NEW_LINE> plt.gca().add_artist(leg1) <NEW_LINE> ax.set_xlabel('Temperature (K)') <NEW_LINE> ax.set_ylabel('Density of states (cm$^{-3}$)') <NEW_LINE> plt.show() | The density of states is a value that determines the
number of free states for electrons and holes in the conduction
and valance band | 6259904e0a366e3fb87dde33 |
class TGrant(TElem): <NEW_LINE> <INDENT> type = T_GRANT <NEW_LINE> SQL = "SELECT relacl FROM pg_class where oid = %(oid)s" <NEW_LINE> acl_map = { 'a': 'INSERT', 'r': 'SELECT', 'w': 'UPDATE', 'd': 'DELETE', 'D': 'TRUNCATE', 'x': 'REFERENCES', 't': 'TRIGGER', 'X': 'EXECUTE', 'U': 'USAGE', 'C': 'CREATE', 'T': 'TEMPORARY', 'c': 'CONNECT', 'R': 'RULE', } <NEW_LINE> def acl_to_grants(self, acl): <NEW_LINE> <INDENT> if acl == "arwdRxt": <NEW_LINE> <INDENT> return "ALL" <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> lst1 = [] <NEW_LINE> lst2 = [] <NEW_LINE> while i < len(acl): <NEW_LINE> <INDENT> a = self.acl_map[acl[i]] <NEW_LINE> if i+1 < len(acl) and acl[i+1] == '*': <NEW_LINE> <INDENT> lst2.append(a) <NEW_LINE> i += 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lst1.append(a) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> return ", ".join(lst1), ", ".join(lst2) <NEW_LINE> <DEDENT> def parse_relacl(self, relacl): <NEW_LINE> <INDENT> if relacl is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> tup_list = [] <NEW_LINE> for sacl in skytools.parse_pgarray(relacl): <NEW_LINE> <INDENT> acl = skytools.parse_acl(sacl) <NEW_LINE> if not acl: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tup_list.append(acl) <NEW_LINE> <DEDENT> return tup_list <NEW_LINE> <DEDENT> def __init__(self, table_name, row, new_name = None): <NEW_LINE> <INDENT> self.name = table_name <NEW_LINE> self.acl_list = self.parse_relacl(row['relacl']) <NEW_LINE> <DEDENT> def get_create_sql(self, curs, new_name = None): <NEW_LINE> <INDENT> if not new_name: <NEW_LINE> <INDENT> new_name = self.name <NEW_LINE> <DEDENT> qtarget = quote_fqident(new_name) <NEW_LINE> sql_list = [] <NEW_LINE> for role, acl, who in self.acl_list: <NEW_LINE> <INDENT> qrole = quote_ident(role) <NEW_LINE> astr1, astr2 = self.acl_to_grants(acl) <NEW_LINE> if astr1: <NEW_LINE> <INDENT> sql = "GRANT %s ON %s\n TO %s;" % (astr1, qtarget, qrole) <NEW_LINE> sql_list.append(sql) <NEW_LINE> <DEDENT> if astr2: <NEW_LINE> <INDENT> sql = "GRANT %s ON %s\n TO %s WITH GRANT OPTION;" % (astr2, qtarget, qrole) <NEW_LINE> sql_list.append(sql) <NEW_LINE> <DEDENT> <DEDENT> return "\n".join(sql_list) <NEW_LINE> <DEDENT> def get_drop_sql(self, curs): <NEW_LINE> <INDENT> sql_list = [] <NEW_LINE> for user, acl, who in self.acl_list: <NEW_LINE> <INDENT> sql = "REVOKE ALL FROM %s ON %s;" % (quote_ident(user), quote_fqident(self.name)) <NEW_LINE> sql_list.append(sql) <NEW_LINE> <DEDENT> return "\n".join(sql_list) | Info about permissions. | 6259904e29b78933be26aae9 |
class LRUCache(Cache): <NEW_LINE> <INDENT> def __init__(self, maxsize, getsizeof=None): <NEW_LINE> <INDENT> if getsizeof is not None: <NEW_LINE> <INDENT> Cache.__init__(self, maxsize, lambda e: getsizeof(e[0])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Cache.__init__(self, maxsize) <NEW_LINE> <DEDENT> root = Node() <NEW_LINE> root.prev = root.next = root <NEW_LINE> self.__root = root <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> value, link = super(LRUCache, self).__getitem__(key) <NEW_LINE> root = self.__root <NEW_LINE> link.prev.next = link.next <NEW_LINE> link.next.prev = link.prev <NEW_LINE> link.prev = tail = root.prev <NEW_LINE> link.next = root <NEW_LINE> tail.next = root.prev = link <NEW_LINE> return value <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, link = super(LRUCache, self).__getitem__(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> link = Node() <NEW_LINE> <DEDENT> super(LRUCache, self).__setitem__(key, (value, link)) <NEW_LINE> try: <NEW_LINE> <INDENT> link.prev.next = link.next <NEW_LINE> link.next.prev = link.prev <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> link.data = key <NEW_LINE> <DEDENT> root = self.__root <NEW_LINE> link.prev = tail = root.prev <NEW_LINE> link.next = root <NEW_LINE> tail.next = root.prev = link <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> _, link = super(LRUCache, self).__getitem__(key) <NEW_LINE> super(LRUCache, self).__delitem__(key) <NEW_LINE> link.prev.next = link.next <NEW_LINE> link.next.prev = link.prev <NEW_LINE> del link.next <NEW_LINE> del link.prev <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s(%r, maxsize=%d, currsize=%d)' % ( self.__class__.__name__, [(key, super(LRUCache, self).__getitem__(key)[0]) for key in self], self.maxsize, self.currsize, ) <NEW_LINE> <DEDENT> def popitem(self): <NEW_LINE> <INDENT> root = self.__root <NEW_LINE> link = root.next <NEW_LINE> if link is root: <NEW_LINE> <INDENT> raise KeyError('cache is empty') <NEW_LINE> <DEDENT> key = link.data <NEW_LINE> return (key, self.pop(key)) | Least Recently Used (LRU) cache implementation.
This class discards the least recently used items first to make
space when necessary. | 6259904e07d97122c42180f1 |
class Element(metaclass=ABCMeta): <NEW_LINE> <INDENT> __attrs_attrs__ = [] <NEW_LINE> @staticmethod <NEW_LINE> def element(wrapped_cls): <NEW_LINE> <INDENT> return attr.s(wrapped_cls, frozen=True) <NEW_LINE> <DEDENT> def unzip_to_tuple(self): <NEW_LINE> <INDENT> return tuple((getattr(self, attribute.name) for attribute in self.__attrs_attrs__)) <NEW_LINE> <DEDENT> def unzip_to_dict(self): <NEW_LINE> <INDENT> return {attribute.name: getattr(self, attribute.name) for attribute in self.__attrs_attrs__} <NEW_LINE> <DEDENT> def deep_copy(self): <NEW_LINE> <INDENT> return self.make_element_from_dict(self.unzip_to_dict()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def make_element_from_dict(cls, dictionary): <NEW_LINE> <INDENT> return cls.make_element(**dictionary) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def make_element_zero(cls, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @abstractmethod <NEW_LINE> def make_element(cls, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() | Represents a type to be placed in a Replay buffer (however, they can be used
for other purposes as well, and do not require a buffer)
There purpose is to serve as keepers of steps taken by the agent
and the associated changes in the environment. | 6259904e55399d3f05627968 |
class HallazgoForm(EmergenciaBaseForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Hallazgo <NEW_LINE> fields = '__all__' <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(HallazgoForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper.layout = Fieldset(u'Agregar Hallazgo', *self.field_names) | Formulario para agregar :class:`RemisionExterna`s | 6259904ed53ae8145f9198b0 |
class C2DEnv(object): <NEW_LINE> <INDENT> def __init__(self, env, n_bins=30): <NEW_LINE> <INDENT> assert isinstance(env.action_space, gym.spaces.Box) <NEW_LINE> assert len(env.action_space.shape) == 1 <NEW_LINE> self.env = env <NEW_LINE> self.n_bins = n_bins <NEW_LINE> self.action_space = gym.spaces.MultiDiscrete( env.action_space.shape[0] * [n_bins]) <NEW_LINE> self.observation_space = self.env.observation_space <NEW_LINE> if hasattr(env, 'original_env'): <NEW_LINE> <INDENT> self.original_env = env.original_env <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.original_env = env <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def horizon(self): <NEW_LINE> <INDENT> if hasattr(self.env, 'horizon'): <NEW_LINE> <INDENT> return self.env._horizon <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return self.env.reset() <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> continuous_action = [] <NEW_LINE> for a, low, high in zip(action, self.env.action_space.low, self.env.action_space.high): <NEW_LINE> <INDENT> continuous_action.append(np.linspace(low, high, self.n_bins)[a]) <NEW_LINE> <DEDENT> action = np.array(continuous_action) <NEW_LINE> next_obs, reward, done, info = self.env.step(action) <NEW_LINE> return next_obs, reward, done, info <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> self.env.render() <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> self.env.terminate() | Wrapper environment for converting continuous action space to multi discrete action space.
Parameters
----------
env : gym.Env
n_bins : int
Number of bins for converting continuous to discrete.
e.g. continuous action space is 0 ~ 1 and n_bins=5,
action space is converted to [0, 0.25, 0.5, 0.75, 1] | 6259904ed7e4931a7ef3d4c6 |
class CometResponse(StreamingIframeResponse): <NEW_LINE> <INDENT> pass | Class used for Comet handler functions,
instead of the :class:`sijax.response.BaseResponse` class.
This class extends :class:`sijax.response.BaseResponse` and
every available method from it works here too. | 6259904e07f4c71912bb0882 |
class BaseProtocol(event_emitter.EventEmitter): <NEW_LINE> <INDENT> def __init__(self, host, port, secure=True): <NEW_LINE> <INDENT> super(BaseProtocol, self).__init__() <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.secure = secure <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def fileno(self): <NEW_LINE> <INDENT> raise NotImplementedError("fileno not implemented.") <NEW_LINE> <DEDENT> def fd_set(self, readable, writeable, errorable): <NEW_LINE> <INDENT> raise NotImplementedError("fd_set not implemented.") <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> raise NotImplementedError("clean up not implemented.") <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> raise NotImplementedError("write not implemented.") <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> raise NotImplementedError("read not implemented.") <NEW_LINE> <DEDENT> def error(self): <NEW_LINE> <INDENT> raise NotImplementedError("error not implemented.") <NEW_LINE> <DEDENT> def reconnect(self): <NEW_LINE> <INDENT> raise NotImplementedError("reconnect not implemented.") <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.cleanup() <NEW_LINE> <DEDENT> def connect(self, conn=None): <NEW_LINE> <INDENT> self.emit("connect", conn) | Base FD Interface | 6259904eb57a9660fecd2eca |
class Signer(Recipient): <NEW_LINE> <INDENT> attributes = ['clientUserId', 'email', 'emailBody', 'emailSubject', 'name', 'recipientId', 'routingOrder', 'supportedLanguage', 'tabs', 'accessCode', 'userId'] <NEW_LINE> attribute_defaults = { 'name': '', 'routingOrder': 0 } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Signer, self).__init__(**kwargs) <NEW_LINE> if self.tabs is None: <NEW_LINE> <INDENT> self.tabs = [] <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> data = { 'clientUserId': self.clientUserId, 'email': self.email, 'emailNotification': None, 'name': self.name, 'recipientId': self.recipientId, 'routingOrder': self.routingOrder, 'tabs': {}, 'accessCode': self.accessCode, } <NEW_LINE> if self.emailBody or self.emailSubject or self.supportedLanguage: <NEW_LINE> <INDENT> data['emailNotification'] = { 'emailBody': self.emailBody, 'emailSubject': self.emailSubject, 'supportedLanguage': self.supportedLanguage, } <NEW_LINE> <DEDENT> for tab in self.tabs: <NEW_LINE> <INDENT> data['tabs'].setdefault(tab.tabs_name, []) <NEW_LINE> data['tabs'][tab.tabs_name].append(tab.to_dict()) <NEW_LINE> <DEDENT> return data | A recipient who must sign, initial, date or add data to form fields on
the documents in the envelope.
DocuSign reference lives at
https://docs.docusign.com/esign/restapi/Envelopes/EnvelopeRecipients/#signers-recipient | 6259904e07d97122c42180f2 |
class Indexer(object): <NEW_LINE> <INDENT> def __init__(self, index_path=None): <NEW_LINE> <INDENT> self.index_path = index_path <NEW_LINE> self.inverted_index = {} <NEW_LINE> self.docs_index = [] <NEW_LINE> self.term_id = 0 <NEW_LINE> self.doc_id = 0 <NEW_LINE> self.preprocessor = Preprocessor() <NEW_LINE> <DEDENT> def indexing_doc(self, doc): <NEW_LINE> <INDENT> tokens = self.preprocessor.preprocessing(doc) <NEW_LINE> token_dict = self.preprocessor.tokens2dict(tokens) <NEW_LINE> self.docs_index.append([len(tokens), token_dict]) <NEW_LINE> for token, tf in token_dict.iteritems(): <NEW_LINE> <INDENT> if token not in self.inverted_index: <NEW_LINE> <INDENT> self.inverted_index[token] = [self.term_id, 0, 0, []] <NEW_LINE> self.term_id += 1 <NEW_LINE> <DEDENT> self.inverted_index[token][1] += tf[0] <NEW_LINE> self.inverted_index[token][2] += 1 <NEW_LINE> self.inverted_index[token][3].append([self.doc_id, tf[0], tf[1]]) <NEW_LINE> <DEDENT> doc_path = path.join(self.index_path, '%d.doc' % self.doc_id) <NEW_LINE> with open(doc_path, 'wb') as doc_file: <NEW_LINE> <INDENT> doc_file.write(doc) <NEW_LINE> <DEDENT> self.doc_id += 1 <NEW_LINE> <DEDENT> def indexing_docs(self, docs): <NEW_LINE> <INDENT> for doc in docs: <NEW_LINE> <INDENT> self.indexing_doc(doc) <NEW_LINE> <DEDENT> <DEDENT> def avdl(self): <NEW_LINE> <INDENT> total_dl = sum([doc[0] for doc in self.docs_index]) <NEW_LINE> return (1.0 * total_dl) / self.doc_id <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> index_data_path = path.join(self.index_path, 'index') <NEW_LINE> with open(index_data_path, 'wb') as index_file: <NEW_LINE> <INDENT> json_data = {} <NEW_LINE> json_data['index_path'] = self.index_path <NEW_LINE> json_data['inverted_index'] = self.inverted_index <NEW_LINE> json_data['docs_index'] = self.docs_index <NEW_LINE> json_data['term_id'] = self.term_id <NEW_LINE> json_data['doc_id'] = self.doc_id <NEW_LINE> index_file.write(json.dumps(json_data)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def load(cls, index_data_path): <NEW_LINE> <INDENT> indexer = Indexer() <NEW_LINE> json_data = json.load(open(index_data_path, 'rb')) <NEW_LINE> indexer.index_path = json_data['index_path'] <NEW_LINE> indexer.inverted_index = json_data['inverted_index'] <NEW_LINE> indexer.docs_index = json_data['docs_index'] <NEW_LINE> indexer.term_id = json_data['term_id'] <NEW_LINE> indexer.doc_id = json_data['doc_id'] <NEW_LINE> return indexer | search engine indexing class | 6259904e94891a1f408ba11c |
class DEPTh(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "DEPTh" <NEW_LINE> args = ["1"] | SOURce:ILS:GSLope:COMid:DEPTh
Arguments: 1 | 6259904e73bcbd0ca4bcb6d7 |
class FeatLabelPadCollator(PadCollator): <NEW_LINE> <INDENT> @overrides <NEW_LINE> def __call__(self, features, labels, apply_pad_labels=(), apply_pad_values=()): <NEW_LINE> <INDENT> self.collate(features) <NEW_LINE> self.collate(labels, apply_pad=False, apply_pad_labels=apply_pad_labels, apply_pad_values=apply_pad_values) <NEW_LINE> return utils.make_batch(features, labels) <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def collate(self, datas, apply_pad=True, apply_pad_labels=(), apply_pad_values=()): <NEW_LINE> <INDENT> for data_name, data in datas.items(): <NEW_LINE> <INDENT> if not apply_pad and data_name in apply_pad_labels: <NEW_LINE> <INDENT> _apply_pad = True <NEW_LINE> pad_value = apply_pad_values[apply_pad_labels.index(data_name)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _apply_pad = apply_pad <NEW_LINE> pad_value = 0 <NEW_LINE> <DEDENT> if isinstance(data, dict): <NEW_LINE> <INDENT> for key, value in data.items(): <NEW_LINE> <INDENT> data[key] = self._collate( value, apply_pad=_apply_pad, token_name=key, pad_value=pad_value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> datas[data_name] = self._collate(data, apply_pad=_apply_pad, pad_value=pad_value) | Collator apply pad and make tensor
Minimizes amount of padding needed while producing mini-batch.
FeatLabelPadCollator allows applying pad to not only features, but also labels.
* Kwargs:
cuda_device_id: tensor assign to cuda device id
Default is None (CPU)
skip_keys: skip to make tensor | 6259904e8e71fb1e983bcf14 |
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_token(cls, user): <NEW_LINE> <INDENT> token = super(CustomTokenObtainPairSerializer, cls).get_token(user) <NEW_LINE> token['username'] = user.username <NEW_LINE> token['email'] = user.email <NEW_LINE> return token | Subclassing the TokenObtainPairSerializer to add more claims
in the payload section of the JWT | 6259904ee76e3b2f99fd9e4f |
class ChangeRequest(Base): <NEW_LINE> <INDENT> __tablename__ = 'change_request' <NEW_LINE> summary = db.Column(db.String(255)) <NEW_LINE> requestor = db.Column(db.String(255)) <NEW_LINE> application = db.Column(db.String(255)) <NEW_LINE> source_location = db.Column(db.String(255)) <NEW_LINE> destination_location = db.Column(db.String(255)) <NEW_LINE> action = db.Column(db.String(255)) <NEW_LINE> status = db.Column(db.String(20), default='open') <NEW_LINE> sources = db.relationship('Address', backref='change_request_sources', lazy='dynamic', cascade="all,delete", foreign_keys='Address.change_request_source_id') <NEW_LINE> destinations = db.relationship('Address', lazy='dynamic', backref='change_request_destinations', cascade="all,delete", foreign_keys='Address.change_request_destination_id') <NEW_LINE> services = db.relationship('Service', backref='change_request', lazy='dynamic', cascade="all,delete") <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> data = super(ChangeRequest, self).serialize() <NEW_LINE> data.update({ 'sources': [v.serialize() for v in self.sources], 'destinations': [v.serialize() for v in self.destinations], 'services': [v.serialize() for v in self.services], }) <NEW_LINE> return data | Change Request model
Represents firewall policy change requests. I.e. in the human form,
"This server needs to talk to this other sever over this port."
The implementation of a change request is what we are actually trying
to automate here... | 6259904edc8b845886d54a0c |
class CensysCommentNotFoundException(CensysAsmException): <NEW_LINE> <INDENT> pass | Exception raised when the requested comment is not found. | 6259904e16aa5153ce40193d |
class Solution: <NEW_LINE> <INDENT> def wordBreak(self, s: str, wordDict: List[str]) -> bool: <NEW_LINE> <INDENT> t = Trie() <NEW_LINE> for w in wordDict: <NEW_LINE> <INDENT> t.addWord(w) <NEW_LINE> <DEDENT> L = len(s) <NEW_LINE> dp = [True] <NEW_LINE> for i in range(1, (L+1)): <NEW_LINE> <INDENT> dp += any(dp[j] and t.checkWord(s[j:i]) for j in range(i)), <NEW_LINE> <DEDENT> return dp[-1] | https://leetcode.com/problems/word-break/discuss/274536/python-trie-%2B-bfs-solution.-O(N)-on-english-dictionary | 6259904e76e4537e8c3f09d5 |
class Milestone: <NEW_LINE> <INDENT> def __init__(self, project_data): <NEW_LINE> <INDENT> for k in iter(project_data): <NEW_LINE> <INDENT> setattr(self, k, project_data[k]) | Create a Milestone object from the JSON data
retrieved from the API | 6259904e6e29344779b01a92 |
class Trough8x1(Plate): <NEW_LINE> <INDENT> num_rows = 8 <NEW_LINE> num_columns = 1 <NEW_LINE> def __init__(self, name, data=None): <NEW_LINE> <INDENT> Plate.__init__(self, name=name, data=data) <NEW_LINE> for well in self: <NEW_LINE> <INDENT> well.content = self["A1"].content | Eight positions share the same content | 6259904ed53ae8145f9198b1 |
class TextUtils(object): <NEW_LINE> <INDENT> def find_matches(self, word, collection, fuzzy): <NEW_LINE> <INDENT> word = self._last_token(word).lower() <NEW_LINE> matches = [] <NEW_LINE> for suggestion in self._find_collection_matches(word, collection, fuzzy): <NEW_LINE> <INDENT> matches.append(suggestion) <NEW_LINE> <DEDENT> return matches <NEW_LINE> <DEDENT> def get_tokens(self, text): <NEW_LINE> <INDENT> if text is not None: <NEW_LINE> <INDENT> text = text.strip() <NEW_LINE> words = self._safe_split(text) <NEW_LINE> return words <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def _last_token(self, text): <NEW_LINE> <INDENT> if text is not None: <NEW_LINE> <INDENT> text = text.strip() <NEW_LINE> if len(text) > 0: <NEW_LINE> <INDENT> word = self._safe_split(text)[-1] <NEW_LINE> word = word.strip() <NEW_LINE> return word <NEW_LINE> <DEDENT> <DEDENT> return '' <NEW_LINE> <DEDENT> def _fuzzy_finder(self, text, collection, case_sensitive=True): <NEW_LINE> <INDENT> suggestions = [] <NEW_LINE> if case_sensitive: <NEW_LINE> <INDENT> pat = '.*?'.join(map(re.escape, text)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pat = '.*?'.join(map(re.escape, text.lower())) <NEW_LINE> <DEDENT> regex = re.compile(pat) <NEW_LINE> for item in collection: <NEW_LINE> <INDENT> if case_sensitive: <NEW_LINE> <INDENT> r = regex.search(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = regex.search(item.lower()) <NEW_LINE> <DEDENT> if r: <NEW_LINE> <INDENT> suggestions.append((len(r.group()), r.start(), item)) <NEW_LINE> <DEDENT> <DEDENT> return (z for _, _, z in sorted(suggestions)) <NEW_LINE> <DEDENT> def _find_collection_matches(self, word, collection, fuzzy): <NEW_LINE> <INDENT> word = word.lower() <NEW_LINE> if fuzzy: <NEW_LINE> <INDENT> for suggestion in self._fuzzy_finder(word, collection, case_sensitive=False): <NEW_LINE> <INDENT> yield Completion(suggestion, -len(word), display_meta='display_meta') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for name in sorted(collection): <NEW_LINE> <INDENT> if name.lower().startswith(word) or not word: <NEW_LINE> <INDENT> display = None <NEW_LINE> display_meta = None <NEW_LINE> if name in META_LOOKUP_GH: <NEW_LINE> <INDENT> display_meta = META_LOOKUP_GH[name] <NEW_LINE> <DEDENT> yield Completion(name, -len(word), display=display, display_meta=display_meta) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _shlex_split(self, text): <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> text = text.encode('utf-8') <NEW_LINE> <DEDENT> return shlex.split(text) <NEW_LINE> <DEDENT> def _safe_split(self, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> words = self._shlex_split(text) <NEW_LINE> return words <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return text | Utilities for parsing and matching text. | 6259904e0fa83653e46f632e |
class Platform(Element): <NEW_LINE> <INDENT> TYPE = 'Platform' <NEW_LINE> TYPE_C = 'Platform' <NEW_LINE> def reload(self): <NEW_LINE> <INDENT> if XMLClient().request('POST', self.url['self'] + '/reload'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def delete(self): <NEW_LINE> <INDENT> raise appngizer.errors.ElementError("Method not available for {0}({1})".format(self.__class__.__name__, self.name)) | Class to manage the platform | 6259904e55399d3f0562796a |
class ClientList(object): <NEW_LINE> <INDENT> __metaclass__ = Singleton <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> result = toggl("%s/clients" % TOGGL_URL, 'get') <NEW_LINE> self.client_list = json.loads(result) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self.iter_index = 0 <NEW_LINE> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self.iter_index >= len(self.client_list): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.iter_index += 1 <NEW_LINE> return self.client_list[self.iter_index-1] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = "" <NEW_LINE> for client in self.client_list: <NEW_LINE> <INDENT> s = s + "%s\n" % client['name'] <NEW_LINE> <DEDENT> return s.rstrip() | A singleton list of clients. A "client object" is a set of properties
as documented at
https://github.com/toggl/toggl_api_docs/blob/master/chapters/clients.md | 6259904e07f4c71912bb0884 |
class SectionMatchClass: <NEW_LINE> <INDENT> def __init__(self, start, end, start_token_number, start_token, end_token_number, end_token, title, EBI_title): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.start_token_number = start_token_number <NEW_LINE> self.start_token = start_token <NEW_LINE> self.end_token_number = end_token_number <NEW_LINE> self.end_token = end_token <NEW_LINE> self.title = title <NEW_LINE> self.EBI_title = EBI_title | Class for handling source section matches | 6259904e8a43f66fc4bf35e7 |
class Template(object): <NEW_LINE> <INDENT> def __init__(self, name, app = None, encoding = 'utf-8', indent = False): <NEW_LINE> <INDENT> super(Template, self).__init__() <NEW_LINE> self.app = app <NEW_LINE> self.name = name <NEW_LINE> self.encoding = encoding <NEW_LINE> self.encoding_errors = 'replace' <NEW_LINE> self.indent = indent <NEW_LINE> self.params = None <NEW_LINE> self.template = None <NEW_LINE> <DEDENT> def load(self, text = None): <NEW_LINE> <INDENT> raise hlib.error.UnimplementedError(obj = Template) <NEW_LINE> <DEDENT> def do_render(self): <NEW_LINE> <INDENT> raise hlib.error.UnimplementedError(obj = Template) <NEW_LINE> <DEDENT> def render(self, params = None): <NEW_LINE> <INDENT> self.params = params or {} <NEW_LINE> data = self.do_render() <NEW_LINE> return data <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def render_error(): <NEW_LINE> <INDENT> return '' | Generic template class | 6259904e94891a1f408ba11d |
class ThemeManager(BaseObject): <NEW_LINE> <INDENT> def __init__(self, user_theme=u"current"): <NEW_LINE> <INDENT> super(ThemeManager, self).__init__() <NEW_LINE> self.exceptions = ThemeExceptions(self) <NEW_LINE> self.user_theme = user_theme <NEW_LINE> <DEDENT> def get_theme(self, name='default'): <NEW_LINE> <INDENT> if (name == 'current') and (self.user_theme != 'current'): <NEW_LINE> <INDENT> return self.get_theme(self.user_theme) <NEW_LINE> <DEDENT> elif (name == 'current'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Theme.objects.get(current=True) <NEW_LINE> <DEDENT> except Theme.DoesNotExist: <NEW_LINE> <INDENT> self.exception(u"No theme selected as 'current'.") <NEW_LINE> return self.get_theme('default') <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return Theme.objects.get(name=name) <NEW_LINE> <DEDENT> except Theme.DoesNotExist: <NEW_LINE> <INDENT> self.exception( u"Selected theme '{theme:s}' does not exist.".format(theme=name), 0 ) <NEW_LINE> if name == 'default': <NEW_LINE> <INDENT> raise ThemeError("There is no default theme supplied.") <NEW_LINE> <DEDENT> return self.get_theme(name='current') <NEW_LINE> <DEDENT> <DEDENT> def exception(self, *args, **kwargs): <NEW_LINE> <INDENT> self.exceptions.exception(*args, **kwargs) <NEW_LINE> <DEDENT> def __getattribute__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(ThemeManager, self).__getattribute__(key) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> if key not in self.cache: <NEW_LINE> <INDENT> self.use_cache(key, ThemeObject(self, self.get_theme(name=key))) <NEW_LINE> <DEDENT> return self.use_cache(key) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for theme in Theme.objects.all(): <NEW_LINE> <INDENT> yield self.use_cache(theme.name, ThemeObject(self, theme)) | Root theme manager. This is the object contained in the 'theme' name
in a `RequestContext`. Supports the following:
exception:
Any exceptions that occur in the theming process and feel like they
can't be handled should be handled by calling `ThemeManager.exception`.
exceptions:
An attribute containing a `ThemeExceptions` class.
get_theme:
Returns a Theme model instance of the requested theme.
Defaults to 'default'
The `ThemeManager` class is iterable and will return a generator
that returns all themes in the database. | 6259904e462c4b4f79dbce50 |
class ApplicationGatewayRewriteRuleSet(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'rewrite_rules': {'key': 'properties.rewriteRules', 'type': '[ApplicationGatewayRewriteRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayRewriteRuleSet, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.etag = None <NEW_LINE> self.rewrite_rules = kwargs.get('rewrite_rules', None) <NEW_LINE> self.provisioning_state = None | Rewrite rule set of an application gateway.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: Name of the rewrite rule set that is unique within an Application Gateway.
:type name: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param rewrite_rules: Rewrite rules in the rewrite rule set.
:type rewrite_rules: list[~azure.mgmt.network.v2021_02_01.models.ApplicationGatewayRewriteRule]
:ivar provisioning_state: The provisioning state of the rewrite rule set resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2021_02_01.models.ProvisioningState | 6259904e097d151d1a2c24c0 |
class Operation(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, name, main, func, widgets=[]): <NEW_LINE> <INDENT> super(Operation, self).__init__(None) <NEW_LINE> layout = QtGui.QGridLayout(self) <NEW_LINE> self.name = name <NEW_LINE> self.main = main <NEW_LINE> self.func = func <NEW_LINE> self.items = {} <NEW_LINE> self.types = {} <NEW_LINE> height = 1 <NEW_LINE> for widget in widgets: <NEW_LINE> <INDENT> w_name, data = widget <NEW_LINE> if type(data) == bool: <NEW_LINE> <INDENT> checkbox = QtGui.QCheckBox(w_name) <NEW_LINE> checkbox.setChecked(data) <NEW_LINE> checkbox.stateChanged.connect(self.main.on_data_change) <NEW_LINE> layout.addWidget(checkbox, height, 2) <NEW_LINE> self.items[w_name] = checkbox <NEW_LINE> <DEDENT> elif type(data) == int or type(data) == float: <NEW_LINE> <INDENT> lineedit = QtGui.QLineEdit(str(data)) <NEW_LINE> lineedit.setValidator(QtGui.QDoubleValidator()) <NEW_LINE> layout.addWidget(QtGui.QLabel(w_name), height, 1) <NEW_LINE> layout.addWidget(lineedit, height, 2) <NEW_LINE> self.items[w_name] = lineedit <NEW_LINE> <DEDENT> elif type(data) == list: <NEW_LINE> <INDENT> layout.addWidget(QtGui.QLabel(w_name), height, 1) <NEW_LINE> combobox = QtGui.QComboBox() <NEW_LINE> combobox.activated.connect(self.main.on_data_change) <NEW_LINE> combobox.addItems(data) <NEW_LINE> layout.addWidget(combobox, height, 2) <NEW_LINE> self.items[w_name] = combobox <NEW_LINE> <DEDENT> self.types[w_name] = type(data) <NEW_LINE> height += 1 <NEW_LINE> <DEDENT> if name == 'sub linecut' or name == 'sub linecut avg': <NEW_LINE> <INDENT> b_current = QtGui.QPushButton('Current linecut') <NEW_LINE> b_current.clicked.connect(self.on_current_linecut) <NEW_LINE> layout.addWidget(b_current, height, 2) <NEW_LINE> <DEDENT> <DEDENT> def on_current_linecut(self): <NEW_LINE> <INDENT> index = self.items['type'].findText(self.main.canvas.line_type) <NEW_LINE> self.items['type'].setCurrentIndex(index) <NEW_LINE> self.items['position'].setText(str(self.main.canvas.line_coord)) <NEW_LINE> <DEDENT> def get_parameter(self, name): <NEW_LINE> <INDENT> if name in self.items: <NEW_LINE> <INDENT> widget = self.items[name] <NEW_LINE> cast = self.types[name] <NEW_LINE> if type(widget) is QtGui.QCheckBox: <NEW_LINE> <INDENT> return cast(widget.isChecked()) <NEW_LINE> <DEDENT> elif type(widget) is QtGui.QLineEdit: <NEW_LINE> <INDENT> return cast(str(widget.text())) <NEW_LINE> <DEDENT> elif type(widget) is QtGui.QComboBox: <NEW_LINE> <INDENT> return str(widget.currentText()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_parameter(self, name, value): <NEW_LINE> <INDENT> if name in self.items: <NEW_LINE> <INDENT> widget = self.items[name] <NEW_LINE> if type(widget) is QtGui.QCheckBox: <NEW_LINE> <INDENT> widget.setChecked(bool(value)) <NEW_LINE> <DEDENT> elif type(widget) is QtGui.QLineEdit: <NEW_LINE> <INDENT> widget.setText(str(value)) <NEW_LINE> <DEDENT> elif type(widget) is QtGui.QComboBox: <NEW_LINE> <INDENT> index = widget.findText(value) <NEW_LINE> widget.setCurrentIndex(index) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_parameters(self): <NEW_LINE> <INDENT> params = {name: self.get_parameter(name) for name in self.items} <NEW_LINE> return self.name, params <NEW_LINE> <DEDENT> def set_parameters(self, params): <NEW_LINE> <INDENT> for name, value in params.items(): <NEW_LINE> <INDENT> self.set_parameter(name, value) | Contains the name and GUI widgets for the parameters of an operation. | 6259904e15baa723494633dd |
class V1beta1HorizontalPodAutoscaler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'kind': 'str', 'api_version': 'str', 'metadata': 'V1ObjectMeta', 'spec': 'V1beta1HorizontalPodAutoscalerSpec', 'status': 'V1beta1HorizontalPodAutoscalerStatus' } <NEW_LINE> self.attribute_map = { 'kind': 'kind', 'api_version': 'apiVersion', 'metadata': 'metadata', 'spec': 'spec', 'status': 'status' } <NEW_LINE> self._kind = None <NEW_LINE> self._api_version = None <NEW_LINE> self._metadata = None <NEW_LINE> self._spec = None <NEW_LINE> self._status = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def kind(self): <NEW_LINE> <INDENT> return self._kind <NEW_LINE> <DEDENT> @kind.setter <NEW_LINE> def kind(self, kind): <NEW_LINE> <INDENT> self._kind = kind <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_version(self): <NEW_LINE> <INDENT> return self._api_version <NEW_LINE> <DEDENT> @api_version.setter <NEW_LINE> def api_version(self, api_version): <NEW_LINE> <INDENT> self._api_version = api_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> return self._metadata <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, metadata): <NEW_LINE> <INDENT> self._metadata = metadata <NEW_LINE> <DEDENT> @property <NEW_LINE> def spec(self): <NEW_LINE> <INDENT> return self._spec <NEW_LINE> <DEDENT> @spec.setter <NEW_LINE> def spec(self, spec): <NEW_LINE> <INDENT> self._spec = spec <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._status <NEW_LINE> <DEDENT> @status.setter <NEW_LINE> def status(self, status): <NEW_LINE> <INDENT> self._status = status <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259904eac7a0e7691f7392c |
class Ball(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, board, square_model, square_view): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.board = board <NEW_LINE> self.square_model = square_model <NEW_LINE> self.image = load_image('red_ball.png') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.bottom = square_view.rect.bottom - BALL_OFFSET_BOTTOM <NEW_LINE> self.rect.left = square_view.rect.left + BALL_OFFSET_LEFT <NEW_LINE> dispatcher.connect(self.handle_board_changed, signal='BOARD CHANGED') <NEW_LINE> dispatcher.connect(self.handle_score_changed, signal='SCORE CHANGED') <NEW_LINE> <DEDENT> def handle_board_changed(self): <NEW_LINE> <INDENT> if self.square_model.value == BLANK and self.alive(): <NEW_LINE> <INDENT> self.remove(self.board) <NEW_LINE> <DEDENT> elif self.square_model.value != BLANK and not self.alive(): <NEW_LINE> <INDENT> self.add(self.board) <NEW_LINE> self.fix_color() <NEW_LINE> <DEDENT> <DEDENT> def handle_score_changed(self, xyzs_included=[]): <NEW_LINE> <INDENT> if self.square_model.xyz in xyzs_included: <NEW_LINE> <INDENT> self.image = load_image('green_ball.png') <NEW_LINE> scheduler.set_timer(ANIMATED_PAUSE, self.fix_color) <NEW_LINE> <DEDENT> <DEDENT> def fix_color(self): <NEW_LINE> <INDENT> for color in ('RED', 'BLUE'): <NEW_LINE> <INDENT> if self.square_model.value == globals()[color]: <NEW_LINE> <INDENT> self.image = load_image('%s_ball.png' % color.lower()) | This represense a ball on a square.
The following attributes are used:
board
This is the rendering group. This ball adds itself to the board
in order to be rendered on an as needed basis.
square_model
This is the associated instance of model.Square. | 6259904e7d847024c075d824 |
class animateTransform(BaseShape, CoreAttrib, ConditionalAttrib, ExternalAttrib, AnimationEventsAttrib, AnimationAttrib, AnimationAttributeAttrib, AnimationTimingAttrib, AnimationValueAttrib, AnimationAdditionAttrib): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> BaseElement.__init__(self, 'animateTransform') <NEW_LINE> self.setKWARGS(**kwargs) <NEW_LINE> <DEDENT> def set_type(self, type): <NEW_LINE> <INDENT> self._attributes['type'] = type <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return self._attributes.get('type') | Class representing the animateTransform element of an svg doc. | 6259904ed6c5a102081e356f |
class AzureDataLakeStorageRESTAPIConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, url: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> if url is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'url' must not be None.") <NEW_LINE> <DEDENT> super(AzureDataLakeStorageRESTAPIConfiguration, self).__init__(**kwargs) <NEW_LINE> self.url = url <NEW_LINE> self.resource = "filesystem" <NEW_LINE> self.version = "2020-02-10" <NEW_LINE> kwargs.setdefault('sdk_moniker', 'azuredatalakestoragerestapi/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') | Configuration for AzureDataLakeStorageRESTAPI.
Note that all parameters used to create this instance are saved as instance
attributes.
:param url: The URL of the service account, container, or blob that is the targe of the desired operation.
:type url: str | 6259904e6e29344779b01a94 |
class SpaceGroup(object): <NEW_LINE> <INDENT> def __init__(self, number, symbol, transformations): <NEW_LINE> <INDENT> self.number = number <NEW_LINE> self.symbol = symbol <NEW_LINE> self.transformations = transformations <NEW_LINE> self.transposed_rotations = N.array([N.transpose(t[0]) for t in transformations]) <NEW_LINE> self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2] for t in transformations])) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.transformations) <NEW_LINE> <DEDENT> def symmetryEquivalentMillerIndices(self, hkl): <NEW_LINE> <INDENT> hkls = N.dot(self.transposed_rotations, hkl) <NEW_LINE> p = N.multiply.reduce(self.phase_factors**hkl, -1) <NEW_LINE> return hkls, p | Space group
All possible space group objects are created in this module. Other
modules should access these objects through the dictionary
space_groups rather than create their own space group objects. | 6259904ed53ae8145f9198b4 |
class FixedGraphEditDistanceDataset(GraphEditDistanceDataset): <NEW_LINE> <INDENT> def __init__( self, n_nodes_range, p_edge_range, n_changes_positive, n_changes_negative, dataset_size, permute=True, seed=1234, ): <NEW_LINE> <INDENT> super(FixedGraphEditDistanceDataset, self).__init__( n_nodes_range, p_edge_range, n_changes_positive, n_changes_negative, permute=permute, ) <NEW_LINE> self._dataset_size = dataset_size <NEW_LINE> self._seed = seed <NEW_LINE> <DEDENT> def triplets(self, batch_size): <NEW_LINE> <INDENT> if hasattr(self, "_triplets"): <NEW_LINE> <INDENT> triplets = self._triplets <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with reset_random_state(self._seed): <NEW_LINE> <INDENT> triplets = [] <NEW_LINE> for _ in range(self._dataset_size): <NEW_LINE> <INDENT> g1, g2, g3 = self._get_triplet() <NEW_LINE> triplets.append((g1, g2, g1, g3)) <NEW_LINE> <DEDENT> <DEDENT> self._triplets = triplets <NEW_LINE> <DEDENT> ptr = 0 <NEW_LINE> while ptr + batch_size <= len(triplets): <NEW_LINE> <INDENT> batch_graphs = triplets[ptr: ptr + batch_size] <NEW_LINE> yield self._pack_batch(batch_graphs) <NEW_LINE> ptr += batch_size <NEW_LINE> <DEDENT> <DEDENT> def pairs(self, batch_size): <NEW_LINE> <INDENT> if hasattr(self, "_pairs") and hasattr(self, "_labels"): <NEW_LINE> <INDENT> pairs = self._pairs <NEW_LINE> labels = self._labels <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with reset_random_state(self._seed): <NEW_LINE> <INDENT> pairs = [] <NEW_LINE> labels = [] <NEW_LINE> positive = True <NEW_LINE> for _ in range(self._dataset_size): <NEW_LINE> <INDENT> pairs.append(self._get_pair(positive)) <NEW_LINE> labels.append(1 if positive else -1) <NEW_LINE> positive = not positive <NEW_LINE> <DEDENT> <DEDENT> labels = np.array(labels, dtype=np.int32) <NEW_LINE> self._pairs = pairs <NEW_LINE> self._labels = labels <NEW_LINE> <DEDENT> ptr = 0 <NEW_LINE> while ptr + batch_size <= len(pairs): <NEW_LINE> <INDENT> batch_graphs = pairs[ptr: ptr + batch_size] <NEW_LINE> packed_batch = self._pack_batch(batch_graphs) <NEW_LINE> yield packed_batch, labels[ptr: ptr + batch_size] <NEW_LINE> ptr += batch_size | A fixed dataset of pairs or triplets for the graph edit distance task.
This dataset can be used for evaluation. | 6259904e55399d3f0562796c |
class EventManipulator(ManipulatorBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def getCacheKeysAndControllers(cls, affected_refs): <NEW_LINE> <INDENT> return CacheClearer.get_event_cache_keys_and_controllers(affected_refs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def postUpdateHook(cls, events, updated_attr_list, is_new_list): <NEW_LINE> <INDENT> for (event, updated_attrs) in zip(events, updated_attr_list): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> event.timezone_id = EventHelper.get_timezone_id(event.location, event.key.id()) <NEW_LINE> cls.createOrUpdate(event, run_post_update_hook=False) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logging.warning("Timezone update for event {} failed!".format(event.key_name)) <NEW_LINE> <DEDENT> <DEDENT> for event in events: <NEW_LINE> <INDENT> taskqueue.add( url='/tasks/math/do/district_points_calc/{}'.format(event.key.id()), method='GET') <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def updateMerge(self, new_event, old_event, auto_union=True): <NEW_LINE> <INDENT> attrs = [ "end_date", "event_short", "event_type_enum", "event_district_enum", "custom_hashtag", "facebook_eid", "first_eid", "city", "state_prov", "country", "timezone_id", "name", "official", "short_name", "start_date", "venue", "venue_address", "webcast_json", "website", "year" ] <NEW_LINE> list_attrs = [] <NEW_LINE> old_event._updated_attrs = [] <NEW_LINE> for attr in attrs: <NEW_LINE> <INDENT> if getattr(new_event, attr) is not None: <NEW_LINE> <INDENT> if getattr(new_event, attr) != getattr(old_event, attr): <NEW_LINE> <INDENT> setattr(old_event, attr, getattr(new_event, attr)) <NEW_LINE> old_event._updated_attrs.append(attr) <NEW_LINE> old_event.dirty = True <NEW_LINE> <DEDENT> <DEDENT> if getattr(new_event, attr) == "None": <NEW_LINE> <INDENT> if getattr(old_event, attr, None) is not None: <NEW_LINE> <INDENT> setattr(old_event, attr, None) <NEW_LINE> old_event._updated_attrs.append(attr) <NEW_LINE> old_event.dirty = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for attr in list_attrs: <NEW_LINE> <INDENT> if len(getattr(new_event, attr)) > 0: <NEW_LINE> <INDENT> if getattr(new_event, attr) != getattr(old_event, attr): <NEW_LINE> <INDENT> setattr(old_event, attr, getattr(new_event, attr)) <NEW_LINE> old_event._updated_attrs.append(attr) <NEW_LINE> old_event.dirty = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return old_event | Handle Event database writes. | 6259904ed7e4931a7ef3d4ca |
class SoundPlayer : <NEW_LINE> <INDENT> PLAYER = "/usr/bin/aplay" <NEW_LINE> def __init__(self) : <NEW_LINE> <INDENT> self.curpath = None <NEW_LINE> self.current = None <NEW_LINE> <DEDENT> def __del__(self) : <NEW_LINE> <INDENT> print("__del__ : Waiting for last play") <NEW_LINE> self.wait() <NEW_LINE> <DEDENT> def play(self, path) : <NEW_LINE> <INDENT> if self.current : <NEW_LINE> <INDENT> if self.current.poll() == None : <NEW_LINE> <INDENT> if path == self.curpath : <NEW_LINE> <INDENT> print(path, "is still playing. Not playing again") <NEW_LINE> return <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> print("Different sound; first waiting for", self.curpath) <NEW_LINE> self.wait() <NEW_LINE> <DEDENT> <DEDENT> self.current = None <NEW_LINE> self.curpath = None <NEW_LINE> <DEDENT> print("Trying to play", path) <NEW_LINE> self.curpath = path <NEW_LINE> self.current = subprocess.Popen([ SoundPlayer.PLAYER, '-q', path ] ) <NEW_LINE> <DEDENT> def wait(self) : <NEW_LINE> <INDENT> if self.current and self.current.poll() == None : <NEW_LINE> <INDENT> self.current.wait() | Play sounds that don't overlap in time. | 6259904e07f4c71912bb0886 |
class NewComment(LoginRequiredMixin, FormView): <NEW_LINE> <INDENT> http_method_names = ['post'] <NEW_LINE> template_name = 'blog/post.html' <NEW_LINE> form_class = CommentForm <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> form.save() <NEW_LINE> return super().form_valid(form) <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> post = self.request.POST.get('post') <NEW_LINE> post_slug = Post.objects.get(id=post).slug <NEW_LINE> return reverse_lazy('blog:detail_view', kwargs={'slug': post_slug}) | A post only view for new comments. for logged in users | 6259904eb57a9660fecd2ece |
class ControllerProcessWrapper(object): <NEW_LINE> <INDENT> def __init__(self, rpc, cmd, verbose=False, detached=False, cwd=None, key=None): <NEW_LINE> <INDENT> logging.info('Creating a process with cmd=%s', cmd) <NEW_LINE> self._rpc = rpc <NEW_LINE> self._key = rpc.subprocess.Process(cmd, key) <NEW_LINE> logging.info('Process created with key=%s', self._key) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> self._rpc.subprocess.SetVerbose(self._key) <NEW_LINE> <DEDENT> if detached: <NEW_LINE> <INDENT> self._rpc.subprocess.SetDetached(self._key) <NEW_LINE> <DEDENT> if cwd: <NEW_LINE> <INDENT> self._rpc.subprocess.SetCwd(self._rpc, cwd) <NEW_LINE> <DEDENT> self._rpc.subprocess.Start(self._key) <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self): <NEW_LINE> <INDENT> return self._key <NEW_LINE> <DEDENT> def Terminate(self): <NEW_LINE> <INDENT> logging.debug('Terminating process %s', self._key) <NEW_LINE> return self._rpc.subprocess.Terminate(self._key) <NEW_LINE> <DEDENT> def Kill(self): <NEW_LINE> <INDENT> logging.debug('Killing process %s', self._key) <NEW_LINE> self._rpc.subprocess.Kill(self._key) <NEW_LINE> <DEDENT> def Delete(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.Delete(self._key) <NEW_LINE> <DEDENT> def GetReturncode(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.GetReturncode(self._key) <NEW_LINE> <DEDENT> def ReadStdout(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.ReadStdout(self._key) <NEW_LINE> <DEDENT> def ReadStderr(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.ReadStderr(self._key) <NEW_LINE> <DEDENT> def ReadOutput(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.ReadOutput(self._key) <NEW_LINE> <DEDENT> def Wait(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.Wait(self._key) <NEW_LINE> <DEDENT> def Poll(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.Poll(self._key) <NEW_LINE> <DEDENT> def GetPid(self): <NEW_LINE> <INDENT> return self._rpc.subprocess.GetPid(self._key) | Controller-side process wrapper class.
This class provides a more intuitive interface to task-side processes
than calling the methods directly using the RPC object. | 6259904e76d4e153a661dca1 |
class IMetaCompetence(Interface): <NEW_LINE> <INDENT> pass | A meta competence | 6259904e73bcbd0ca4bcb6db |
class Dashboard: <NEW_LINE> <INDENT> url = None <NEW_LINE> token = None <NEW_LINE> api_endpoint = '/api/dashboard' <NEW_LINE> def __init__(self, url, token): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.token = token <NEW_LINE> <DEDENT> def get(self, id=None): <NEW_LINE> <INDENT> headers = { "Content-Type": "application/json", "X-Metabase-Session": self.token } <NEW_LINE> if id != None: <NEW_LINE> <INDENT> dashboard = requests.get(self.url + self.api_endpoint + '/' + str(id), headers=headers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dashboard = requests.get(self.url + self.api_endpoint, headers=headers) <NEW_LINE> <DEDENT> return loads(dashboard.text) | Card Class is core class which provides metabase
dashboards.
Attributes:
url (str) : metabase host. default value None
token (str) : metabase session token. default value None
api_endpoint (str) : metabase api endpoint
Return:
class object | 6259904e6fece00bbaccce0c |
class RandomNodeTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_set_cpd(self): <NEW_LINE> <INDENT> n = nodes.RandomNode("test") <NEW_LINE> with self.assertRaises(NotImplementedError) as cm: <NEW_LINE> <INDENT> n.set_cpd(None) <NEW_LINE> <DEDENT> self.assertEqual(str(cm.exception), "Called unimplemented method.") <NEW_LINE> <DEDENT> def test_eq(self): <NEW_LINE> <INDENT> n1 = nodes.RandomNode("test") <NEW_LINE> n2 = nodes.RandomNode("test2") <NEW_LINE> n3 = nodes.RandomNode("test") <NEW_LINE> self.assertEqual(n1, n3) <NEW_LINE> self.assertNotEqual(n1,n2) <NEW_LINE> self.assertEqual(n2, "test2") <NEW_LINE> self.assertNotEqual(n3, "somethingElse") <NEW_LINE> <DEDENT> def test_hash(self): <NEW_LINE> <INDENT> n = nodes.RandomNode("test") <NEW_LINE> self.assertEqual(hash(n), hash("test")) <NEW_LINE> testDict = {n: n} <NEW_LINE> self.assertEqual(testDict[n], testDict["test"]) | This is the baseclass for all nodes. Only subclasses should be used. | 6259904e1f037a2d8b9e5295 |
class JobLogSummaryWorkspaceJob(): <NEW_LINE> <INDENT> def __init__(self, *, resources_add: float = None, resources_modify: float = None, resources_destroy: float = None) -> None: <NEW_LINE> <INDENT> self.resources_add = resources_add <NEW_LINE> self.resources_modify = resources_modify <NEW_LINE> self.resources_destroy = resources_destroy <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, _dict: Dict) -> 'JobLogSummaryWorkspaceJob': <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'resources_add' in _dict: <NEW_LINE> <INDENT> args['resources_add'] = _dict.get('resources_add') <NEW_LINE> <DEDENT> if 'resources_modify' in _dict: <NEW_LINE> <INDENT> args['resources_modify'] = _dict.get('resources_modify') <NEW_LINE> <DEDENT> if 'resources_destroy' in _dict: <NEW_LINE> <INDENT> args['resources_destroy'] = _dict.get('resources_destroy') <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> return cls.from_dict(_dict) <NEW_LINE> <DEDENT> def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'resources_add') and getattr(self, 'resources_add') is not None: <NEW_LINE> <INDENT> _dict['resources_add'] = getattr(self, 'resources_add') <NEW_LINE> <DEDENT> if hasattr(self, 'resources_modify') and getattr(self, 'resources_modify') is not None: <NEW_LINE> <INDENT> _dict['resources_modify'] = getattr(self, 'resources_modify') <NEW_LINE> <DEDENT> if hasattr(self, 'resources_destroy') and getattr(self, 'resources_destroy') is not None: <NEW_LINE> <INDENT> _dict['resources_destroy'] = getattr(self, 'resources_destroy') <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return self.to_dict() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other: 'JobLogSummaryWorkspaceJob') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other: 'JobLogSummaryWorkspaceJob') -> bool: <NEW_LINE> <INDENT> return not self == other | Workspace Job log summary.
:attr float resources_add: (optional) Number of resources add.
:attr float resources_modify: (optional) Number of resources modify.
:attr float resources_destroy: (optional) Number of resources destroy. | 6259904e462c4b4f79dbce52 |
class TrainHillClimb(Train): <NEW_LINE> <INDENT> def __init__(self, goal_minimize=True): <NEW_LINE> <INDENT> Train.__init__(self, goal_minimize) <NEW_LINE> <DEDENT> def train(self, x0, funct, acceleration=1.2, step_size=1.0): <NEW_LINE> <INDENT> iteration_number = 1 <NEW_LINE> self.position = list(x0) <NEW_LINE> self.best_score = funct(self.position) <NEW_LINE> step_size = [step_size] * len(x0) <NEW_LINE> candidate = [0] * 5 <NEW_LINE> candidate[0] = -acceleration <NEW_LINE> candidate[1] = -1 / acceleration <NEW_LINE> candidate[2] = 0 <NEW_LINE> candidate[3] = 1 / acceleration <NEW_LINE> candidate[4] = acceleration <NEW_LINE> while not self.should_stop(iteration_number, self.best_score): <NEW_LINE> <INDENT> if self.goal_minimize: <NEW_LINE> <INDENT> best_step_score = sys.float_info.max <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> best_step_score = sys.float_info.min <NEW_LINE> <DEDENT> for dimension in xrange(0, len(self.position)): <NEW_LINE> <INDENT> best = -1 <NEW_LINE> for i in xrange(0, len(candidate)): <NEW_LINE> <INDENT> self.position[dimension] += candidate[i] * step_size[dimension] <NEW_LINE> trial_score = funct(self.position) <NEW_LINE> self.position[dimension] -= candidate[i] * step_size[dimension] <NEW_LINE> if self.better_than(trial_score, best_step_score): <NEW_LINE> <INDENT> best_step_score = trial_score <NEW_LINE> best = i <NEW_LINE> <DEDENT> <DEDENT> if best != -1: <NEW_LINE> <INDENT> self.best_score = best_step_score <NEW_LINE> self.position[dimension] += candidate[best] * step_size[dimension] <NEW_LINE> step_size[dimension] += candidate[best] <NEW_LINE> <DEDENT> <DEDENT> if self.display_iteration: <NEW_LINE> <INDENT> print("Iteration #" + str(iteration_number) + ", Score: " + str(self.best_score)) <NEW_LINE> <DEDENT> iteration_number += 1 <NEW_LINE> <DEDENT> if self.display_final: <NEW_LINE> <INDENT> print("Finished after " + str(iteration_number) + " iterations, final score is " + str(self.best_score)) <NEW_LINE> <DEDENT> return self.position | Train using hill climbing. Hill climbing can be used to optimize the long term memory of a Machine Learning
Algorithm. This is done by moving the current long term memory values to a new location if that new location
gives a better score from the scoring function.
http://en.wikipedia.org/wiki/Hill_climbing | 6259904eb57a9660fecd2ecf |
class itrs(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def rotation_at(t): <NEW_LINE> <INDENT> R = mxm(rot_z(-t.gast * tau / 24.0), t.M) <NEW_LINE> if t.ts.polar_motion_table is not None: <NEW_LINE> <INDENT> R = mxm(t.polar_motion_matrix(), R) <NEW_LINE> <DEDENT> return R <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _dRdt_times_RT_at(t): <NEW_LINE> <INDENT> return _itrs_angvel_matrix | The International Terrestrial Reference System (ITRS).
This is the IAU standard for an Earth-centered Earth-fixed (ECEF)
coordinate system, anchored to the Earth’s crust and continents.
This reference frame combines three other reference frames: the
Earth’s true equator and equinox of date, the Earth’s rotation with
respect to the stars, and (if your ``Timescale`` has polar offsets
loaded) the polar wobble of the crust with respect to the Earth’s
pole of rotation.
.. versionadded:: 1.34 | 6259904e4428ac0f6e659985 |
class MockMatplotlibMethods(MockBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> plt_attrs = {'subplots': Mock(return_value=(MagicMock(), MagicMock()))} <NEW_LINE> self.patcher_pyplot = patch('model_analyzer.plots.simple_plot.plt', Mock(**plt_attrs)) <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.pyplot_mock = self.patcher_pyplot.start() <NEW_LINE> <DEDENT> def _fill_patchers(self): <NEW_LINE> <INDENT> self._patchers.append(self.patcher_pyplot) <NEW_LINE> <DEDENT> def assert_called_subplots(self): <NEW_LINE> <INDENT> self.pyplot_mock.subplots.assert_called() <NEW_LINE> <DEDENT> def assert_called_plot_with_args(self, x_data, y_data, marker, label): <NEW_LINE> <INDENT> self.pyplot_mock.subplots.return_value[1].plot.assert_called_with( x_data, y_data, marker=marker, label=label) <NEW_LINE> <DEDENT> def assert_called_save_with_args(self, filepath): <NEW_LINE> <INDENT> self.pyplot_mock.subplots.return_value[0].savefig.assert_called_with( filepath) | Mock class that mocks
matplotlib | 6259904e0c0af96317c5778a |
class PositionList(generics.ListAPIView, viewsets.GenericViewSet): <NEW_LINE> <INDENT> serializer_class = PositionsSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> imo = self.kwargs['imo'] <NEW_LINE> return Position.objects.filter(ship__imo_number=imo).distinct() | API endpoint that allows listing positions for a ship provided the imo. | 6259904ea79ad1619776b4d3 |
class Operator: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> pass | Used as a wildcards and operators when matching message arguments
(see assertMessageMatch and match_list) | 6259904eac7a0e7691f7392e |
class Meta: <NEW_LINE> <INDENT> model = Task <NEW_LINE> exclude = [] | This class contains the serializer metadata. | 6259904e82261d6c527308f0 |
class GroupByDateEditForm(EditForm): <NEW_LINE> <INDENT> form_fields = form.FormFields(IGroupByDateAction) <NEW_LINE> form_fields['base_folder'].custom_widget = UberSelectionWidget <NEW_LINE> label = _(u"Edit group by date action") <NEW_LINE> description = _(u"A content rules action to move an item to a folder" u" structure.") | An edit form for the group by date action | 6259904e24f1403a926862f7 |
class MissingVersionHandled(CloudInitPickleMixin, metaclass=_Collector): <NEW_LINE> <INDENT> def __getstate__(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def _unpickle(self, ci_pkl_version: int) -> None: <NEW_LINE> <INDENT> assert 0 == ci_pkl_version | Test that pickles without ``_ci_pkl_version`` are handled gracefully.
This is tested by overriding ``__getstate__`` so the dumped pickle of this
class will not have ``_ci_pkl_version`` included. | 6259904e0fa83653e46f6332 |
class PasteWindow(QtWidgets.QDialog): <NEW_LINE> <INDENT> _mw = None <NEW_LINE> def __init__(self, main): <NEW_LINE> <INDENT> super(PasteWindow, self).__init__() <NEW_LINE> self._mw = main <NEW_LINE> self.gridLayout = QtWidgets.QGridLayout(self) <NEW_LINE> self.pasteButton = QtWidgets.QPushButton( QtGui.QIcon.fromTheme("edit-paste"), "&Paste", self) <NEW_LINE> self.clearButton = QtWidgets.QPushButton( QtGui.QIcon.fromTheme("edit-clear"), "&Clear", self) <NEW_LINE> self.textBox = QtWidgets.QPlainTextEdit(self) <NEW_LINE> self.label = QtWidgets.QLabel( "Every line below will be added to the list.\n" "GitHub Flavored Markdown is supported for basic markup " "(done status, <b>**bold**</b>, <i>*italic*</i>, " "<u><u>underline</u></u>, <s>~~strikeout~~</s>).", self) <NEW_LINE> self.label.setTextFormat(QtCore.Qt.RichText) <NEW_LINE> self.label.setWordWrap(True) <NEW_LINE> self.buttonBox = QtWidgets.QDialogButtonBox(self) <NEW_LINE> self.buttonBox.setOrientation(QtCore.Qt.Horizontal) <NEW_LINE> self.buttonBox.setStandardButtons( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) <NEW_LINE> self.pasteButton.clicked.connect(self.paste) <NEW_LINE> self.clearButton.clicked.connect(self.clear) <NEW_LINE> self.gridLayout.addWidget(self.label, 0, 0, 2, 3) <NEW_LINE> self.gridLayout.addWidget(self.pasteButton, 0, 3, 1, 1) <NEW_LINE> self.gridLayout.addWidget(self.clearButton, 1, 3, 1, 1) <NEW_LINE> self.gridLayout.addWidget(self.textBox, 2, 0, 1, 4) <NEW_LINE> self.gridLayout.addWidget(self.buttonBox, 3, 0, 1, 4) <NEW_LINE> self.setWindowTitle("Paste into Cheqlist") <NEW_LINE> self.setWindowIcon(QtGui.QIcon.fromTheme("edit-paste")) <NEW_LINE> self.setModal(True) <NEW_LINE> self.resize(400, 400) <NEW_LINE> self.buttonBox.accepted.connect(self.accept) <NEW_LINE> self.buttonBox.rejected.connect(self.reject) <NEW_LINE> QtCore.QMetaObject.connectSlotsByName(self) <NEW_LINE> self.paste() <NEW_LINE> <DEDENT> def paste(self, event=None): <NEW_LINE> <INDENT> self.textBox.clear() <NEW_LINE> self.textBox.paste() <NEW_LINE> <DEDENT> def clear(self, event=None): <NEW_LINE> <INDENT> self.textBox.clear() | A simple window to paste items. | 6259904e71ff763f4b5e8bfb |
class CIFARFractalNet(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, channels, num_columns, dropout_probs, loc_drop_prob, glob_drop_ratio, in_channels=3, in_size=(32, 32), classes=10, **kwargs): <NEW_LINE> <INDENT> super(CIFARFractalNet, self).__init__(**kwargs) <NEW_LINE> self.in_size = in_size <NEW_LINE> self.classes = classes <NEW_LINE> self.glob_drop_ratio = glob_drop_ratio <NEW_LINE> self.num_columns = num_columns <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.features = ParametricSequential(prefix="") <NEW_LINE> for i, out_channels in enumerate(channels): <NEW_LINE> <INDENT> dropout_prob = dropout_probs[i] <NEW_LINE> self.features.add(FractalUnit( in_channels=in_channels, out_channels=out_channels, num_columns=num_columns, loc_drop_prob=loc_drop_prob, dropout_prob=dropout_prob)) <NEW_LINE> in_channels = out_channels <NEW_LINE> <DEDENT> self.output = nn.Dense( units=classes, in_units=in_channels) <NEW_LINE> <DEDENT> <DEDENT> def hybrid_forward(self, F, x): <NEW_LINE> <INDENT> glob_batch_size = int(x.shape[0] * self.glob_drop_ratio) <NEW_LINE> glob_num_columns = np.random.randint(0, self.num_columns, size=(glob_batch_size,)) <NEW_LINE> x = self.features(x, glob_num_columns) <NEW_LINE> x = self.output(x) <NEW_LINE> return x | FractalNet model for CIFAR from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
channels : list of int
Number of output channels for each unit.
num_columns : int
Number of columns in each block.
dropout_probs : list of float
Probability of dropout in each block.
loc_drop_prob : float
Local drop path probability.
glob_drop_ratio : float
Global drop part fraction.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes. | 6259904e50485f2cf55dc3dc |
class UserBest(BaseModel): <NEW_LINE> <INDENT> def __init__(self, *, api : 'OsuApi' = None, **data): <NEW_LINE> <INDENT> super().__init__(api) <NEW_LINE> self.rank = data.get('rank' , "") <NEW_LINE> self.user_id = int(data.get('user_id' , 0)) <NEW_LINE> self.count50 = int(data.get('count50' , 0)) <NEW_LINE> self.count100 = int(data.get('count100' , 0)) <NEW_LINE> self.count300 = int(data.get('count300' , 0)) <NEW_LINE> self.maxcombo = int(data.get('maxcombo' , 0)) <NEW_LINE> self.countmiss = int(data.get('countmiss' , 0)) <NEW_LINE> self.countkatu = int(data.get('countkatu' , 0)) <NEW_LINE> self.countgeki = int(data.get('countgeki' , 0)) <NEW_LINE> self.beatmap_id = int(data.get('beatmap_id' , 0)) <NEW_LINE> self.enabled_mods = int(data.get('enabled_mods', 0)) <NEW_LINE> self.perfect = bool(data.get('perfect' , False)) <NEW_LINE> self.pp = float(data.get('pp' , 0.0)) <NEW_LINE> self.score = float(data.get('score' , 0.0)) <NEW_LINE> self.date = datetime.datetime.strptime(data.get('date', "1970-01-01 00:00:00"), "%Y-%m-%d %H:%M:%S") <NEW_LINE> self._beatmap = None <NEW_LINE> self._user = None <NEW_LINE> <DEDENT> async def get_user(self): <NEW_LINE> <INDENT> if self._user is None: <NEW_LINE> <INDENT> self._user = await self.api.get_user(user = self.user_id, type_str = 'id') <NEW_LINE> <DEDENT> return self._user <NEW_LINE> <DEDENT> async def get_beatmap(self): <NEW_LINE> <INDENT> if self._beatmap is None: <NEW_LINE> <INDENT> self._beatmap = await self.api.get_beatmap(beatmap_id = self.beatmap_id) <NEW_LINE> <DEDENT> return self._beatmap | User best model | 6259904ee76e3b2f99fd9e54 |
class StraightHTML(Base.WebElement): <NEW_LINE> <INDENT> __slots__ = ('html') <NEW_LINE> properties = Base.WebElement.properties.copy() <NEW_LINE> properties['html'] = {'action':'classAttribute'} <NEW_LINE> def _create(self, name=None, id=None, parent=None, html=""): <NEW_LINE> <INDENT> Base.WebElement._create(self, None, None, parent) <NEW_LINE> self.html = html <NEW_LINE> <DEDENT> def toHTML(self, formatted=False, *args, **kwargs): <NEW_LINE> <INDENT> return self.html | Simply displays the html as it is given | 6259904ed4950a0f3b11186d |
class HttpClient(object): <NEW_LINE> <INDENT> def __init__(self, host, port, user, password, verify): <NEW_LINE> <INDENT> self.base_url = 'https://%s:%s/api/rest/' % (host, port) <NEW_LINE> self.session = requests.Session() <NEW_LINE> self.session.auth = (user, password) <NEW_LINE> self.header = {} <NEW_LINE> self.header['Content-Type'] = 'application/json; charset=utf-8' <NEW_LINE> self.header['x-dell-api-version'] = '2.0' <NEW_LINE> self.verify = verify <NEW_LINE> if not verify: <NEW_LINE> <INDENT> requests.packages.urllib3.disable_warnings() <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, tipe, value, traceback): <NEW_LINE> <INDENT> self.session.close() <NEW_LINE> <DEDENT> def _format_url(self, url): <NEW_LINE> <INDENT> return '%s%s' % (self.base_url, url if url[0] != '/' else url[1:]) <NEW_LINE> <DEDENT> def get(self, url): <NEW_LINE> <INDENT> return self.session.get( self._format_url(url), headers=self.header, verify=self.verify) <NEW_LINE> <DEDENT> def post(self, url, payload): <NEW_LINE> <INDENT> return self.session.post( self._format_url(url), data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), headers=self.header, verify=self.verify) <NEW_LINE> <DEDENT> def put(self, url, payload): <NEW_LINE> <INDENT> return self.session.put( self._format_url(url), data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), headers=self.header, verify=self.verify) <NEW_LINE> <DEDENT> def delete(self, url): <NEW_LINE> <INDENT> return self.session.delete( self._format_url(url), headers=self.header, verify=self.verify) | Wrapper class for making Storage Center API calls. | 6259904ebaa26c4b54d506fe |
class BinaryExpr(Expr): <NEW_LINE> <INDENT> def __init__(self, left_expr, right_expr): <NEW_LINE> <INDENT> Expr.__init__(self) <NEW_LINE> self._left_expr = left_expr <NEW_LINE> self._right_expr = right_expr <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _op_symbol(cls): <NEW_LINE> <INDENT> raise FatalError('UnaryExpr._op_symbol called') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _binary_func(cls, x, y): <NEW_LINE> <INDENT> raise FatalError('BinaryExpr._binary_func called') <NEW_LINE> <DEDENT> def contains_operator(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def eval(self): <NEW_LINE> <INDENT> left_value = self._left_expr.eval() <NEW_LINE> right_value = self._right_expr.eval() <NEW_LINE> if not (is_finite(left_value) and is_finite(right_value)): <NEW_LINE> <INDENT> raise EvalError('%f %s %f [invalid values]' % (left_value, self._op_symbol(), right_value)) <NEW_LINE> <DEDENT> value = self._binary_func(left_value, right_value) <NEW_LINE> if not is_finite(value): <NEW_LINE> <INDENT> raise EvalError('%f %s %f = %f [overflow or NaN]' % (left_value, self._op_symbol(), right_value, value)) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def build_test_expr(self): <NEW_LINE> <INDENT> if (isinstance(self._left_expr, Number) or isinstance(self._left_expr, UnaryExpr) or isinstance(self._left_expr, Group)): <NEW_LINE> <INDENT> left_format = '%s' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> left_format = '(%s)' <NEW_LINE> <DEDENT> if (isinstance(self._right_expr, Number) or isinstance(self._right_expr, UnaryExpr) or isinstance(self._right_expr, Group)): <NEW_LINE> <INDENT> right_format = '%s' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> right_format = '(%s)' <NEW_LINE> <DEDENT> format = left_format + '%s' + right_format <NEW_LINE> return format % (self._left_expr.build_test_expr(), self._op_symbol(), self._right_expr.build_test_expr()) <NEW_LINE> <DEDENT> def build_python_expr(self): <NEW_LINE> <INDENT> return '(%s) %s (%s)' % (self._left_expr.build_python_expr(), self._op_symbol(), self._right_expr.build_python_expr()) <NEW_LINE> <DEDENT> def build_cc_expr(self): <NEW_LINE> <INDENT> return '(%s) %s (%s)' % (self._left_expr.build_cc_expr(), self._op_symbol(), self._right_expr.build_cc_expr()) | Base class for binary operators.
This is an abstract class: two functions, _op_symbol and _binary_func must
be implemented in each subclass.
Attributes:
_left_expr: an expression (Expr object) on left side.
_right_expr: an expression (Expr object) on right side. | 6259904e23849d37ff852512 |
class Worker(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, fn, channel, data): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.fn = fn <NEW_LINE> self.channel = channel <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"<{self.__class__.__name__} for {self.data} on {self.channel}>" <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logger.debug("%s dispatched with data %r on channel %r", self.__class__.__name__, self.data, self.channel) <NEW_LINE> try: <NEW_LINE> <INDENT> self.fn(self.channel, self.data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.exception('Exception in %s', self) | Thread subclass to for handling pubsub events | 6259904e8da39b475be0463e |
class ProductFileInline(admin.StackedInline): <NEW_LINE> <INDENT> model = ProductFile | Inline view of ProductFile admin | 6259904e96565a6dacd2d9b3 |
class Input(Node): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Input, self).__init__() <NEW_LINE> <DEDENT> def store(self, inp): <NEW_LINE> <INDENT> self._output = inp <NEW_LINE> <DEDENT> def get_output(self): <NEW_LINE> <INDENT> return self._output <NEW_LINE> <DEDENT> def fit(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | A Node to be used as a placeholder for the graph's input. | 6259904e596a897236128fd9 |
class JSONBool(int, _JSONTypeBase): <NEW_LINE> <INDENT> def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) == 0: <NEW_LINE> <INDENT> b = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> b = 1 if args[0] >= 1 else 0 <NEW_LINE> <DEDENT> return int.__new__(JSONBool, b) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> int.__init__(self) <NEW_LINE> _JSONTypeBase.__init__(self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ['False', 'True'][self] <NEW_LINE> <DEDENT> def _to_map_value(self): <NEW_LINE> <INDENT> return [False, True][self] <NEW_LINE> <DEDENT> def true(self): <NEW_LINE> <INDENT> return self == 1 <NEW_LINE> <DEDENT> def false(self): <NEW_LINE> <INDENT> return self == 0 <NEW_LINE> <DEDENT> def equals(self, other): <NEW_LINE> <INDENT> return self == other | 注意,不要将JSONBool实例通过 is 关键字和 True 比较,这样的结果永远是 False。例:
jbool = JSONBool(True)
print(jbool is True) # False
print(jbool == True) # True
print(jbool.true()) # True
print(jbool.true() is True) # True | 6259904e8e7ae83300eea4e9 |
@attr.s <NEW_LINE> class TrialRecord(object): <NEW_LINE> <INDENT> trial_name = attr.ib() <NEW_LINE> principal_investigator = attr.ib() <NEW_LINE> start_date = attr.ib() <NEW_LINE> samples = attr.ib(factory=list) <NEW_LINE> assays = attr.ib(factory=list) <NEW_LINE> collaborators = attr.ib(factory=list) | Class representing a mongo record for a trial.
Arguments:
object {[type]} -- [description] | 6259904e63d6d428bbee3c20 |
class TestPlayer_0opponents: <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.payoffs = [0, 1, -1] <NEW_LINE> self.player = Player(self.payoffs) <NEW_LINE> self.best_response_action = 1 <NEW_LINE> self.dominated_actions = [0, 2] <NEW_LINE> <DEDENT> def test_delete_action(self): <NEW_LINE> <INDENT> N = self.player.num_opponents + 1 <NEW_LINE> actions_to_delete = [0, 2] <NEW_LINE> actions_to_remain = np.setdiff1d(np.arange(self.player.num_actions), actions_to_delete) <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> player_new = self.player.delete_action(actions_to_delete, i) <NEW_LINE> assert_array_equal( player_new.payoff_array, self.player.payoff_array.take(actions_to_remain, axis=i) ) <NEW_LINE> <DEDENT> <DEDENT> def test_payoff_vector(self): <NEW_LINE> <INDENT> assert_array_equal(self.player.payoff_vector(None), self.payoffs) <NEW_LINE> <DEDENT> def test_is_best_response(self): <NEW_LINE> <INDENT> ok_(self.player.is_best_response(self.best_response_action, None)) <NEW_LINE> <DEDENT> def test_best_response(self): <NEW_LINE> <INDENT> eq_(self.player.best_response(None), self.best_response_action) <NEW_LINE> <DEDENT> def test_is_dominated(self): <NEW_LINE> <INDENT> for action in range(self.player.num_actions): <NEW_LINE> <INDENT> eq_(self.player.is_dominated(action), (action in self.dominated_actions)) <NEW_LINE> <DEDENT> <DEDENT> def test_dominated_actions(self): <NEW_LINE> <INDENT> eq_(self.player.dominated_actions(), self.dominated_actions) | Test for trivial Player with no opponent player | 6259904e3cc13d1c6d466b8e |
class Custom20Pagination(PageNumberPagination): <NEW_LINE> <INDENT> page_size = 20 <NEW_LINE> page_size_query_param = 'page_size' <NEW_LINE> max_page_size = 20 <NEW_LINE> def get_paginated_response(self, data): <NEW_LINE> <INDENT> return Response({ 'links': {'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data } ) | A pagination class that paginates every 20 objects. | 6259904e82261d6c527308f1 |
class NeoModelBase(type(dj_models.Model)): <NEW_LINE> <INDENT> meta_additions = ['has_own_index'] <NEW_LINE> def __init__(cls, name, bases, dct): <NEW_LINE> <INDENT> super(NeoModelBase, cls).__init__(name, bases, dct) <NEW_LINE> cls._creation_counter = 0 <NEW_LINE> <DEDENT> def __new__(cls, name, bases, attrs): <NEW_LINE> <INDENT> super_new = super(NeoModelBase, cls).__new__ <NEW_LINE> attr_meta = attrs.get('Meta', None) <NEW_LINE> extra_options = {} <NEW_LINE> if attr_meta: <NEW_LINE> <INDENT> for key in set(NeoModelBase.meta_additions + cls.meta_additions): <NEW_LINE> <INDENT> if hasattr(attr_meta, key): <NEW_LINE> <INDENT> extra_options[key] = getattr(attr_meta, key) <NEW_LINE> delattr(attr_meta, key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> flagged_methods = [i for i in attrs.items() if getattr(i[1], 'transactional', False) and inspect.isfunction(i[1])] <NEW_LINE> @decorator <NEW_LINE> def trans_method(func, *args, **kw): <NEW_LINE> <INDENT> if len(args) > 0 and isinstance(args[0], NodeModel) and len(connections[args[0].using]._transactions) < 1: <NEW_LINE> <INDENT> ret = func(*args, **kw) <NEW_LINE> return ret <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func(*args, **kw) <NEW_LINE> <DEDENT> <DEDENT> for i in flagged_methods: <NEW_LINE> <INDENT> attrs[i[0]] = trans_method(i[1]) <NEW_LINE> <DEDENT> new_cls = super_new(cls, name, bases, attrs) <NEW_LINE> if not new_cls._meta.abstract: <NEW_LINE> <INDENT> new_cls._meta.pk = new_cls.id <NEW_LINE> <DEDENT> for k in extra_options: <NEW_LINE> <INDENT> setattr(new_cls._meta, k, extra_options[k]) <NEW_LINE> <DEDENT> return new_cls | Model metaclass that adds creation counters to models, a hook for adding
custom "class Meta" style options to NeoModels beyond those supported by
Django, and method transactionality. | 6259904e26068e7796d4dd99 |
class Team(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'team_info' <NEW_LINE> team_id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> team_name = db.Column(db.String(5), nullable=False) <NEW_LINE> team_city = db.Column(db.String(20)) <NEW_LINE> team_year = db.Column(db.Integer) <NEW_LINE> player_data = db.relationship('Player_Data', backref='team', lazy='dynamic') <NEW_LINE> player_contract = db.relationship('Player_Contract', backref='team', lazy='dynamic') <NEW_LINE> team_data = db.relationship('Team_Data', backref='team', lazy='dynamic') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return { 'team_id': self.team_id, 'team_name': self.team_name, 'team_city': self.team_city, 'team_year': self.team_year } | 球队类 | 6259904ebe383301e0254c70 |
class TagDefineShape3(TagDefineShape2): <NEW_LINE> <INDENT> TYPE = 32 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(TagDefineShape3, self).__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "DefineShape3" <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return TagDefineShape3.TYPE <NEW_LINE> <DEDENT> @property <NEW_LINE> def level(self): <NEW_LINE> <INDENT> return 3 <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return 3 | DefineShape3 extends the capabilities of DefineShape2 by extending
all of the RGB color fields to support RGBA with opacity information.
The minimum file format version is SWF 3. | 6259904e287bf620b627303f |
class GriddedField4(GriddedField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(GriddedField4, self).__init__(4, *args, **kwargs) | GriddedField with 4 dimensions. | 6259904e3eb6a72ae038bab1 |
class MsearchDevice(Msearch): <NEW_LINE> <INDENT> _timestamp_first_request = 0 <NEW_LINE> _devicelist = [] <NEW_LINE> _count = -1 <NEW_LINE> _retry = 0 <NEW_LINE> _verbose = False <NEW_LINE> def __init__(self, verbose=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._verbose = verbose <NEW_LINE> <DEDENT> def request(self, retries=3): <NEW_LINE> <INDENT> if retries > 0: <NEW_LINE> <INDENT> self._timestamp_first_request = time() <NEW_LINE> self._devicelist = [] <NEW_LINE> self._count = retries <NEW_LINE> super().request() <NEW_LINE> self._retry = 1 <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> if self._count < 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> _o_datagram = super().get() <NEW_LINE> if _o_datagram is None: <NEW_LINE> <INDENT> self._count -= 1 <NEW_LINE> _o_dummy_datagram = SSDPdatagram() <NEW_LINE> if self._count > 0: <NEW_LINE> <INDENT> super().request() <NEW_LINE> self._retry += 1 <NEW_LINE> _o_dummy_datagram.request = self._retry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._count = -1 <NEW_LINE> _o_dummy_datagram.request = 0 <NEW_LINE> <DEDENT> return _o_dummy_datagram.fdevice( base_time=self._timestamp_first_request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _device = _o_datagram.ipaddr + ' ' +_o_datagram.uuid <NEW_LINE> if _device not in self._devicelist: <NEW_LINE> <INDENT> self._devicelist.append(_device) <NEW_LINE> _o_datagram.request = self._retry <NEW_LINE> return _o_datagram.fdevice( base_time=self._timestamp_first_request, verbose=self._verbose) | Search for the next device on the network.
Because of stateless communication of multicast it may be possible that
requests are lost. To improve reliability requests are send more than one
time. Most devices will response on every request but we make the responses
unique. Only the first response is reported. | 6259904ed53ae8145f9198b8 |
class GrapesJsField(forms.CharField): <NEW_LINE> <INDENT> widget = GrapesJsWidget <NEW_LINE> def __init__(self, default_html=GRAPESJS_DEFAULT_HTML, html_name_init_conf=REDACTOR_CONFIG[BASE], apply_django_tag=False, validate_tags=False, template_choices=None, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.widget.default_html = default_html <NEW_LINE> self.widget.html_name_init_conf = html_name_init_conf <NEW_LINE> self.widget.apply_django_tag = apply_django_tag <NEW_LINE> self.widget.template_choices = template_choices <NEW_LINE> self.validate_tags = validate_tags <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> super().validate(value) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> value = apply_string_handling(value, 'apply_tag_save') <NEW_LINE> return super().clean(value) | Form field with support grapesjs. | 6259904e45492302aabfd929 |
class WinkDevice(Entity): <NEW_LINE> <INDENT> def __init__(self, wink): <NEW_LINE> <INDENT> from pubnub import Pubnub <NEW_LINE> self.wink = wink <NEW_LINE> self._battery = self.wink.battery_level <NEW_LINE> if self.wink.pubnub_channel in CHANNELS: <NEW_LINE> <INDENT> pubnub = Pubnub("N/A", self.wink.pubnub_key, ssl_on=True) <NEW_LINE> pubnub.set_heartbeat(120) <NEW_LINE> pubnub.subscribe(self.wink.pubnub_channel, self._pubnub_update, error=self._pubnub_error) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> CHANNELS.append(self.wink.pubnub_channel) <NEW_LINE> SUBSCRIPTION_HANDLER.subscribe(self.wink.pubnub_channel, self._pubnub_update, error=self._pubnub_error) <NEW_LINE> <DEDENT> <DEDENT> def _pubnub_update(self, message, channel): <NEW_LINE> <INDENT> self.wink.pubnub_update(json.loads(message)) <NEW_LINE> self.update_ha_state() <NEW_LINE> <DEDENT> def _pubnub_error(self, message): <NEW_LINE> <INDENT> logging.getLogger(__name__).error( "Error on pubnub update for " + self.wink.name()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return "{}.{}".format(self.__class__, self.wink.device_id()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.wink.name() <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self.wink.available <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.wink.update_state() <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return self.wink.pubnub_channel is None <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> if self._battery: <NEW_LINE> <INDENT> return { ATTR_BATTERY_LEVEL: self._battery_level, } <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _battery_level(self): <NEW_LINE> <INDENT> return self.wink.battery_level * 100 | Represents a base Wink device. | 6259904e29b78933be26aaed |
class TBTAFFilterType(object): <NEW_LINE> <INDENT> IN="Inclusion" <NEW_LINE> OUT="Exclusion" | Simple enumeration to describe a logical operator for filtering a given query | 6259904e71ff763f4b5e8bfd |
class ResourceNotFound(Exception): <NEW_LINE> <INDENT> pass | If target resource is not found, it is raised.
| 6259904eb57a9660fecd2ed3 |
class Gre(Resource): <NEW_LINE> <INDENT> def __init__(self, gres): <NEW_LINE> <INDENT> super(Gre, self).__init__(gres) <NEW_LINE> self._meta_data['required_creation_parameters'].update(('partition',)) <NEW_LINE> self._meta_data['required_json_kind'] = 'tm:net:tunnels:gre:grestate' | BIG-IP® tunnels GRE sub-collection resource | 6259904e1f037a2d8b9e5297 |
class AssignmentError(Error): <NEW_LINE> <INDENT> pass | Raised when assignment fails. | 6259904e21a7993f00c673bf |
class PptFile(anydoc.AnyDoc): <NEW_LINE> <INDENT> def __init__(self, isPPS, fp, isBin=None, **kwargs): <NEW_LINE> <INDENT> anydoc.AnyDoc.__init__(self, fp, isBin, **kwargs) <NEW_LINE> self.pps = isPPS | power point document | 6259904e3c8af77a43b68969 |
@pytest.mark.django_db <NEW_LINE> class BasePostsApiV1(object): <NEW_LINE> <INDENT> @pytest.fixture <NEW_LINE> def setup_test(self, request): <NEW_LINE> <INDENT> self.user = User.objects.create() <NEW_LINE> self.profile = Profile.objects.create( website='http://127.0.0.1:8000', user=self.user, ) <NEW_LINE> self.post = Post.objects.create( title='Test', post='Lorem ipsum', user=self.user, ) <NEW_LINE> self.list_posts_url = reverse('list_posts_api_v1') <NEW_LINE> self.create_post_url = reverse('create_post_api_v1') <NEW_LINE> self.get_post_url = reverse('get_post_api_v1', kwargs={'pk': self.post.pk}) <NEW_LINE> self.get_post_url_invalid = reverse('get_post_api_v1', kwargs={'pk': self.post.pk + 9999}) | Base Test module for posts API | 6259904edc8b845886d54a14 |
class AbstractAlgorithm: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_owner( cls ): <NEW_LINE> <INDENT> raise NotImplementedError( "abstract" ) <NEW_LINE> <DEDENT> def __init__( self, function: Callable, argskwargs: ArgsKwargs = ArgsKwargs.EMPTY, name: str = None, ): <NEW_LINE> <INDENT> assert inspect.isfunction( function ), repr( function ) <NEW_LINE> self.function = function <NEW_LINE> self.argskwargs = argskwargs <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def __call__( self, *args, **kwargs ) -> object: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.function( *args, *self.argskwargs.args, **kwargs, **self.argskwargs.kwargs ) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> raise ValueError( "The algorithm «{}» failed to execute correctly, see causing exception for details.".format( repr( self ) ) ) from ex <NEW_LINE> <DEDENT> <DEDENT> def __str__( self ): <NEW_LINE> <INDENT> name = self.name or self.function <NEW_LINE> args = "({})".format( self.argskwargs ) if self.argskwargs else "" <NEW_LINE> return "{}{}".format( name, args ) <NEW_LINE> <DEDENT> def __repr__( self ): <NEW_LINE> <INDENT> return "{}(function = {}, argskwargs = {})".format( type( self ).__name__, repr( self.function ), repr( self.argskwargs ) ) | The concrete varieties of this class serve as function annotations denoting which type of algorithm a command accepts.
Other than that, such annotations may be considered synonymous with `Callable`.
These concrete versions are defined in `AlgorithmCollection.__init__`.
Instances of this class simply wrap a function. | 6259904ed6c5a102081e3574 |
class PlainTextField(Field): <NEW_LINE> <INDENT> widget = PlainTextWidget() <NEW_LINE> def validate(self, form, extra_validators=()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def process(self, formdata, data=None): <NEW_LINE> <INDENT> self.data = self.default <NEW_LINE> return self.default | A field for displaying plain text. This field's value
cannot be changed and always uses the default. | 6259904e82261d6c527308f2 |
class Comparitor(): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def describe(): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def order(): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def make_view(self, parent, inline=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def config(self): <NEW_LINE> <INDENT> return dict() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def settings_string(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def pprint(self): <NEW_LINE> <INDENT> settings = self.settings_string <NEW_LINE> if settings is not None: <NEW_LINE> <INDENT> return self.name + " : " + settings <NEW_LINE> <DEDENT> return self.name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def from_dict(self, data): <NEW_LINE> <INDENT> raise NotImplementedError() | Still a work in progress as I think about what we need to support:
currently the business end of how to get "output" is not specified in this
base class.
:param model: An instance of :class:`analysis.Model` from which we can
obtain data and settings. | 6259904e379a373c97d9a482 |
class TestIndependentLearnersManyAgents(BaseTestMultiAgentModel): <NEW_LINE> <INDENT> nb_agents = _HIGH_NB_AGENTS <NEW_LINE> multiagent_model_class = IndependentLearners <NEW_LINE> expected_state = MultiAgentTestEnv._DEFAULT_STATE | Test independent learners, many agents. | 6259904ed6c5a102081e3575 |
class others_keyword(parser.keyword): <NEW_LINE> <INDENT> def __init__(self, sString): <NEW_LINE> <INDENT> parser.keyword.__init__(self, sString) | unique_id = entity_name_list : others_keyword | 6259904ed53ae8145f9198ba |
class Owner(ndb.Model): <NEW_LINE> <INDENT> id = ndb.StringProperty() <NEW_LINE> email = ndb.StringProperty() <NEW_LINE> nickname = ndb.StringProperty() <NEW_LINE> @classmethod <NEW_LINE> def exists(cls, user=None, email=None): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> <DEDENT> return Owner.query(Owner.id == user.user_id()).count(limit=1) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_key(cls, user=None): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> user = users.get_current_user() <NEW_LINE> <DEDENT> return Owner.query(Owner.id == user.user_id()).get(keys_only=True) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, user=None): <NEW_LINE> <INDENT> return Owner.get_key(user).get() | Represents an owner of a vessel. | 6259904e8a43f66fc4bf35ef |
class Household: <NEW_LINE> <INDENT> def __init__(self, home_id): <NEW_LINE> <INDENT> self.id = home_id <NEW_LINE> self.module_use_flgas = RecommendModulesUseFlags() <NEW_LINE> <DEDENT> def get_smart_meter(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_ac_log(self, start_time=None, end_time=None): <NEW_LINE> <INDENT> return ACLogDataRows( home_id=self.id, start_time=start_time, end_time=end_time ) <NEW_LINE> <DEDENT> def get_web_view_log(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_is_done(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_home_meta(self): <NEW_LINE> <INDENT> return MetaDataRow(home_id=self.id).get_row() | 家庭はデータの固まりをいくつか持つ
DataFormat型のモデルをいくつか保持するものが家庭
DataFormat型のモデルというのがつまりDBの各テーブルにあたる
データ形式
時系列データ TimeSeriesDataFormat -> SmartMeterDataFormat
操作ログデータ LogDataFormat -> ApplianceLogDataFormat -> ACLogDataFormat
内容実行二択データ TwoSelectionsDataFormat -> IsDoneDataFormat
MetaDataFormat
# 家族構成情報
# 住まい地域情報
2016-10-06 現状、以下のPractical DataFormatのみを持つようにする
1. SmartMeterDataFormat
2. ACLogDataFormat
3. WebViewLogDataFormat
4. IsDoneDataFormat
5. HomeMeta <= New! 2016-11-17 | 6259904ee76e3b2f99fd9e58 |
class LearningAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, env, learning=False, epsilon=1, Gamma=1,alpha=0.7,action=None): <NEW_LINE> <INDENT> super(LearningAgent, self).__init__(env) <NEW_LINE> self.planner = RoutePlanner(self.env, self) <NEW_LINE> self.valid_actions = self.env.valid_actions <NEW_LINE> self.learning = learning <NEW_LINE> self.Q = dict() <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.alpha = alpha <NEW_LINE> self.action=action <NEW_LINE> self.Gamma=Gamma <NEW_LINE> self.trial=0 <NEW_LINE> <DEDENT> def reset(self, destination=None, testing=False): <NEW_LINE> <INDENT> self.planner.route_to(destination) <NEW_LINE> self.trial=self.trial+1 <NEW_LINE> if testing: <NEW_LINE> <INDENT> self.epsilon=0 <NEW_LINE> self.alpha=0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a=0.02 <NEW_LINE> self.epsilon=self.epsilon*math.exp(-a) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def build_state(self): <NEW_LINE> <INDENT> waypoint = self.planner.next_waypoint() <NEW_LINE> inputs = self.env.sense(self) <NEW_LINE> deadline = self.env.get_deadline(self) <NEW_LINE> if self.learning is True: <NEW_LINE> <INDENT> state = (waypoint,inputs['light'], inputs['oncoming'], inputs['left']) <NEW_LINE> <DEDENT> return state <NEW_LINE> <DEDENT> def get_maxQ(self, state): <NEW_LINE> <INDENT> maxQ = max(self.Q[state], key=(lambda x: self.Q[state][x])) <NEW_LINE> return self.Q[state][maxQ] <NEW_LINE> <DEDENT> def createQ(self, state): <NEW_LINE> <INDENT> if self.learning is True: <NEW_LINE> <INDENT> if state not in self.Q.keys(): <NEW_LINE> <INDENT> self.Q[state]= {None:0,'left':0, 'right':0, 'forward':0} <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> action = None <NEW_LINE> if self.learning!=True: <NEW_LINE> <INDENT> action_opt=[None, 'forward', 'left', 'right'] <NEW_LINE> action=random.choice(action_opt) <NEW_LINE> <DEDENT> elif random.uniform(0, 1)<self.epsilon: <NEW_LINE> <INDENT> action_opt=[None, 'forward', 'left', 'right'] <NEW_LINE> action=random.choice(action_opt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Q_max = self.get_maxQ(state) <NEW_LINE> action_opt=[None, 'forward', 'left', 'right'] <NEW_LINE> action_Q=map(lambda x: self.Q[state][x],action_opt) <NEW_LINE> action_opt2=[] <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> if action_Q[i]==Q_max: <NEW_LINE> <INDENT> action_opt2.append(action_opt[i]) <NEW_LINE> <DEDENT> <DEDENT> action=random.choice(action_opt2) <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def learn(self, state, action, reward): <NEW_LINE> <INDENT> if self.learning is True: <NEW_LINE> <INDENT> self.Q[state][action] = (1-self.alpha)*self.Q[state][action] + self.alpha*(reward) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> state = self.build_state() <NEW_LINE> self.createQ(state) <NEW_LINE> action = self.choose_action(state) <NEW_LINE> reward = self.env.act(self, action) <NEW_LINE> self.learn(state, action, reward) <NEW_LINE> return | An agent that learns to drive in the Smartcab world.
This is the object you will be modifying. | 6259904eb57a9660fecd2ed4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.