_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q268800
Property.validate_value
test
def validate_value(self, value): """ Validate new property value before setting it. value -- New value """ if 'readOnly' in self.metadata and self.metadata['readOnly']: raise PropertyError('Read-only property') try: validate(value, self.metadata)...
python
{ "resource": "" }
q268801
Property.as_property_description
test
def as_property_description(self): """ Get the property description. Returns a dictionary describing the property. """ description = deepcopy(self.metadata) if 'links' not in description: description['links'] = [] description['links'].append( ...
python
{ "resource": "" }
q268802
Property.set_value
test
def set_value(self, value): """ Set the current value of the property. value -- the value to set """ self.validate_value(value) self.value.set(value)
python
{ "resource": "" }
q268803
MultipleThings.get_thing
test
def get_thing(self, idx): """ Get the thing at the given index. idx -- the index """ try: idx = int(idx) except ValueError: return None if idx < 0 or idx >= len(self.things): return None return self.things[idx]
python
{ "resource": "" }
q268804
BaseHandler.initialize
test
def initialize(self, things, hosts): """ Initialize the handler. things -- list of Things managed by this server hosts -- list of allowed hostnames """ self.things = things self.hosts = hosts
python
{ "resource": "" }
q268805
BaseHandler.set_default_headers
test
def set_default_headers(self, *args, **kwargs): """Set the default headers for all requests.""" self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') self.set_header('A...
python
{ "resource": "" }
q268806
ThingHandler.prepare
test
def prepare(self): """Validate Host header.""" host = self.request.headers.get('Host', None) if host is not None and host in self.hosts: return raise tornado.web.HTTPError(403)
python
{ "resource": "" }
q268807
ThingHandler.get
test
def get(self, thing_id='0'): """ Handle a GET request, including websocket requests. thing_id -- ID of the thing this request is for """ self.thing = self.get_thing(thing_id) if self.thing is None: self.set_status(404) self.finish() re...
python
{ "resource": "" }
q268808
ThingHandler.on_message
test
def on_message(self, message): """ Handle an incoming message. message -- message to handle """ try: message = json.loads(message) except ValueError: try: self.write_message(json.dumps({ 'messageType': 'error', ...
python
{ "resource": "" }
q268809
ActionsHandler.post
test
def post(self, thing_id='0'): """ Handle a POST request. thing_id -- ID of the thing this request is for """ thing = self.get_thing(thing_id) if thing is None: self.set_status(404) return try: message = json.loads(self.request...
python
{ "resource": "" }
q268810
ActionIDHandler.delete
test
def delete(self, thing_id='0', action_name=None, action_id=None): """ Handle a DELETE request. thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL path """ thing = self.get_th...
python
{ "resource": "" }
q268811
WebThingServer.start
test
def start(self): """Start listening for incoming connections.""" self.service_info = ServiceInfo( '_webthing._tcp.local.', '{}._webthing._tcp.local.'.format(self.name), address=socket.inet_aton(get_ip()), port=self.port, properties={ ...
python
{ "resource": "" }
q268812
Action.as_action_description
test
def as_action_description(self): """ Get the action description. Returns a dictionary describing the action. """ description = { self.name: { 'href': self.href_prefix + self.href, 'timeRequested': self.time_requested, '...
python
{ "resource": "" }
q268813
Action.start
test
def start(self): """Start performing the action.""" self.status = 'pending' self.thing.action_notify(self) self.perform_action() self.finish()
python
{ "resource": "" }
q268814
Action.finish
test
def finish(self): """Finish performing the action.""" self.status = 'completed' self.time_completed = timestamp() self.thing.action_notify(self)
python
{ "resource": "" }
q268815
Event.as_event_description
test
def as_event_description(self): """ Get the event description. Returns a dictionary describing the event. """ description = { self.name: { 'timestamp': self.time, }, } if self.data is not None: description[self...
python
{ "resource": "" }
q268816
get_ip
test
def get_ip(): """ Get the default local IP address. From: https://stackoverflow.com/a/28950776 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except (socket.error, IndexError): ip = '127.0.0.1' ...
python
{ "resource": "" }
q268817
get_addresses
test
def get_addresses(): """ Get all IP addresses. Returns list of addresses. """ addresses = set() for iface in ifaddr.get_adapters(): for addr in iface.ips: # Filter out link-local addresses. if addr.is_IPv4: ip = addr.ip if not ip...
python
{ "resource": "" }
q268818
Value.set
test
def set(self, value): """ Set a new value for this thing. value -- value to set """ if self.value_forwarder is not None: self.value_forwarder(value) self.notify_of_external_update(value)
python
{ "resource": "" }
q268819
Value.notify_of_external_update
test
def notify_of_external_update(self, value): """ Notify observers of a new value. value -- new value """ if value is not None and value != self.last_value: self.last_value = value self.emit('update', value)
python
{ "resource": "" }
q268820
Thing.as_thing_description
test
def as_thing_description(self): """ Return the thing state as a Thing Description. Returns the state as a dictionary. """ thing = { 'name': self.name, 'href': self.href_prefix if self.href_prefix else '/', '@context': self.context, ...
python
{ "resource": "" }
q268821
Thing.set_href_prefix
test
def set_href_prefix(self, prefix): """ Set the prefix of any hrefs associated with this thing. prefix -- the prefix """ self.href_prefix = prefix for property_ in self.properties.values(): property_.set_href_prefix(prefix) for action_name in self.ac...
python
{ "resource": "" }
q268822
Thing.get_property_descriptions
test
def get_property_descriptions(self): """ Get the thing's properties as a dictionary. Returns the properties as a dictionary, i.e. name -> description. """ return {k: v.as_property_description() for k, v in self.properties.items()}
python
{ "resource": "" }
q268823
Thing.get_action_descriptions
test
def get_action_descriptions(self, action_name=None): """ Get the thing's actions as an array. action_name -- Optional action name to get descriptions for Returns the action descriptions. """ descriptions = [] if action_name is None: for name in self...
python
{ "resource": "" }
q268824
Thing.get_event_descriptions
test
def get_event_descriptions(self, event_name=None): """ Get the thing's events as an array. event_name -- Optional event name to get descriptions for Returns the event descriptions. """ if event_name is None: return [e.as_event_description() for e in self.eve...
python
{ "resource": "" }
q268825
Thing.add_property
test
def add_property(self, property_): """ Add a property to this thing. property_ -- property to add """ property_.set_href_prefix(self.href_prefix) self.properties[property_.name] = property_
python
{ "resource": "" }
q268826
Thing.remove_property
test
def remove_property(self, property_): """ Remove a property from this thing. property_ -- property to remove """ if property_.name in self.properties: del self.properties[property_.name]
python
{ "resource": "" }
q268827
Thing.get_property
test
def get_property(self, property_name): """ Get a property's value. property_name -- the property to get the value of Returns the properties value, if found, else None. """ prop = self.find_property(property_name) if prop: return prop.get_value() ...
python
{ "resource": "" }
q268828
Thing.get_properties
test
def get_properties(self): """ Get a mapping of all properties and their values. Returns a dictionary of property_name -> value. """ return {prop.get_name(): prop.get_value() for prop in self.properties.values()}
python
{ "resource": "" }
q268829
Thing.set_property
test
def set_property(self, property_name, value): """ Set a property value. property_name -- name of the property to set value -- value to set """ prop = self.find_property(property_name) if not prop: return prop.set_value(value)
python
{ "resource": "" }
q268830
Thing.get_action
test
def get_action(self, action_name, action_id): """ Get an action. action_name -- name of the action action_id -- ID of the action Returns the requested action if found, else None. """ if action_name not in self.actions: return None for action...
python
{ "resource": "" }
q268831
Thing.add_event
test
def add_event(self, event): """ Add a new event and notify subscribers. event -- the event that occurred """ self.events.append(event) self.event_notify(event)
python
{ "resource": "" }
q268832
Thing.add_available_event
test
def add_available_event(self, name, metadata): """ Add an available event. name -- name of the event metadata -- event metadata, i.e. type, description, etc., as a dict """ if metadata is None: metadata = {} self.available_events[name] = { ...
python
{ "resource": "" }
q268833
Thing.perform_action
test
def perform_action(self, action_name, input_=None): """ Perform an action on the thing. action_name -- name of the action input_ -- any action inputs Returns the action that was created. """ if action_name not in self.available_actions: return None ...
python
{ "resource": "" }
q268834
Thing.remove_action
test
def remove_action(self, action_name, action_id): """ Remove an existing action. action_name -- name of the action action_id -- ID of the action Returns a boolean indicating the presence of the action. """ action = self.get_action(action_name, action_id) ...
python
{ "resource": "" }
q268835
Thing.add_available_action
test
def add_available_action(self, name, metadata, cls): """ Add an available action. name -- name of the action metadata -- action metadata, i.e. type, description, etc., as a dict cls -- class to instantiate for this action """ if metadata is None: meta...
python
{ "resource": "" }
q268836
Thing.remove_subscriber
test
def remove_subscriber(self, ws): """ Remove a websocket subscriber. ws -- the websocket """ if ws in self.subscribers: self.subscribers.remove(ws) for name in self.available_events: self.remove_event_subscriber(name, ws)
python
{ "resource": "" }
q268837
Thing.add_event_subscriber
test
def add_event_subscriber(self, name, ws): """ Add a new websocket subscriber to an event. name -- name of the event ws -- the websocket """ if name in self.available_events: self.available_events[name]['subscribers'].add(ws)
python
{ "resource": "" }
q268838
Thing.remove_event_subscriber
test
def remove_event_subscriber(self, name, ws): """ Remove a websocket subscriber from an event. name -- name of the event ws -- the websocket """ if name in self.available_events and \ ws in self.available_events[name]['subscribers']: self.avail...
python
{ "resource": "" }
q268839
Thing.property_notify
test
def property_notify(self, property_): """ Notify all subscribers of a property change. property_ -- the property that changed """ message = json.dumps({ 'messageType': 'propertyStatus', 'data': { property_.name: property_.get_value(), ...
python
{ "resource": "" }
q268840
Thing.action_notify
test
def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action whose status changed """ message = json.dumps({ 'messageType': 'actionStatus', 'data': action.as_action_description(), }) for sub...
python
{ "resource": "" }
q268841
Thing.event_notify
test
def event_notify(self, event): """ Notify all subscribers of an event. event -- the event that occurred """ if event.name not in self.available_events: return message = json.dumps({ 'messageType': 'event', 'data': event.as_event_descr...
python
{ "resource": "" }
q268842
PostgresQuerySet.annotate
test
def annotate(self, **annotations): """Custom version of the standard annotate function that allows using field names as annotated fields. Normally, the annotate function doesn't allow you to use the name of an existing field on the model as the alias name. This version of the fu...
python
{ "resource": "" }
q268843
PostgresQuerySet.update
test
def update(self, **fields): """Updates all rows that match the filter.""" # build up the query to execute self._for_write = True if django.VERSION >= (2, 0): query = self.query.chain(UpdateQuery) else: query = self.query.clone(UpdateQuery) query._...
python
{ "resource": "" }
q268844
PostgresQuerySet.bulk_insert
test
def bulk_insert(self, rows, return_model=False): """Creates multiple new records in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: rows: ...
python
{ "resource": "" }
q268845
PostgresQuerySet.insert
test
def insert(self, **fields): """Creates a new record in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fields: The fields of the row t...
python
{ "resource": "" }
q268846
PostgresQuerySet.insert_and_get
test
def insert_and_get(self, **fields): """Creates a new record in the database and then gets the entire row. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fi...
python
{ "resource": "" }
q268847
PostgresQuerySet._build_insert_compiler
test
def _build_insert_compiler(self, rows: List[Dict]): """Builds the SQL compiler for a insert query. Arguments: rows: A list of dictionaries, where each entry describes a record to insert. Returns: The SQL compiler for the insert. "...
python
{ "resource": "" }
q268848
PostgresQuerySet._is_magical_field
test
def _is_magical_field(self, model_instance, field, is_insert: bool): """Verifies whether this field is gonna modify something on its own. "Magical" means that a field modifies the field value during the pre_save. Arguments: model_instance: The model ...
python
{ "resource": "" }
q268849
PostgresQuerySet._get_upsert_fields
test
def _get_upsert_fields(self, kwargs): """Gets the fields to use in an upsert. This some nice magic. We'll split the fields into a group of "insert fields" and "update fields": INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1 ^^^^...
python
{ "resource": "" }
q268850
PostgresManager._on_model_save
test
def _on_model_save(sender, **kwargs): """When a model gets created or updated.""" created, instance = kwargs['created'], kwargs['instance'] if created: signals.create.send(sender, pk=instance.pk) else: signals.update.send(sender, pk=instance.pk)
python
{ "resource": "" }
q268851
PostgresManager._on_model_delete
test
def _on_model_delete(sender, **kwargs): """When a model gets deleted.""" instance = kwargs['instance'] signals.delete.send(sender, pk=instance.pk)
python
{ "resource": "" }
q268852
IsNotNone
test
def IsNotNone(*fields, default=None): """Selects whichever field is not None, in the specified order. Arguments: fields: The fields to attempt to get a value from, in order. default: The value to return in case all values are None. Returns: A Ca...
python
{ "resource": "" }
q268853
HStoreValue.resolve_expression
test
def resolve_expression(self, *args, **kwargs): """Resolves expressions inside the dictionary.""" result = dict() for key, value in self.value.items(): if hasattr(value, 'resolve_expression'): result[key] = value.resolve_expression( *args, **kwargs...
python
{ "resource": "" }
q268854
HStoreValue.as_sql
test
def as_sql(self, compiler, connection): """Compiles the HStore value into SQL. Compiles expressions contained in the values of HStore entries as well. Given a dictionary like: dict(key1='val1', key2='val2') The resulting SQL will be: hstore(hstore('ke...
python
{ "resource": "" }
q268855
HStoreColumn.relabeled_clone
test
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
python
{ "resource": "" }
q268856
PostgresQuery.add_join_conditions
test
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query...
python
{ "resource": "" }
q268857
PostgresQuery._is_hstore_field
test
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]: """Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the ...
python
{ "resource": "" }
q268858
PostgresInsertQuery.values
test
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. ...
python
{ "resource": "" }
q268859
HStoreRequiredSchemaEditorMixin._create_hstore_required
test
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), ...
python
{ "resource": "" }
q268860
HStoreRequiredSchemaEditorMixin._rename_hstore_required
test
def _rename_hstore_required(self, old_table_name, new_table_name, old_field, new_field, key): """Renames an existing REQUIRED CONSTRAINT for the specified hstore key.""" old_name = self._required_constraint_name( old_table_name, old_field, key) ...
python
{ "resource": "" }
q268861
HStoreRequiredSchemaEditorMixin._drop_hstore_required
test
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), ...
python
{ "resource": "" }
q268862
HStoreRequiredSchemaEditorMixin._required_constraint_name
test
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to creat...
python
{ "resource": "" }
q268863
ConditionalUniqueIndex.create_sql
test
def create_sql(self, model, schema_editor, using=''): """Creates the actual SQL used when applying the migration.""" if django.VERSION >= (2, 0): statement = super().create_sql(model, schema_editor, using) statement.template = self.sql_create_index statement.parts['co...
python
{ "resource": "" }
q268864
create_command
test
def create_command(text, commands): """Creates a custom setup.py command.""" class CustomCommand(BaseCommand): description = text def run(self): for cmd in commands: subprocess.check_call(cmd) return CustomCommand
python
{ "resource": "" }
q268865
_get_backend_base
test
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base ...
python
{ "resource": "" }
q268866
DatabaseWrapper.prepare_database
test
def prepare_database(self): """Ran to prepare the configured database. This is where we enable the `hstore` extension if it wasn't enabled yet.""" super().prepare_database() with self.cursor() as cursor: try: cursor.execute('CREATE EXTENSION IF NOT E...
python
{ "resource": "" }
q268867
HStoreField.get_prep_value
test
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.""" value = Field.get_prep_value(self, value) if isinstance(value, dict...
python
{ "resource": "" }
q268868
PostgresReturningUpdateCompiler._form_returning
test
def _form_returning(self): """Builds the RETURNING part of the query.""" qn = self.connection.ops.quote_name return ' RETURNING %s' % qn(self.query.model._meta.pk.attname)
python
{ "resource": "" }
q268869
PostgresInsertCompiler.as_sql
test
def as_sql(self, return_id=False): """Builds the SQL INSERT statement.""" queries = [ self._rewrite_insert(sql, params, return_id) for sql, params in super().as_sql() ] return queries
python
{ "resource": "" }
q268870
PostgresInsertCompiler._rewrite_insert
test
def _rewrite_insert(self, sql, params, return_id=False): """Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. re...
python
{ "resource": "" }
q268871
PostgresInsertCompiler._rewrite_insert_update
test
def _rewrite_insert_update(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.""" update_columns = ', '.join([ '{0} = EXCLUDED.{0}'.format(self.qn(field.column)) for field in self.query.update_fields ]...
python
{ "resource": "" }
q268872
PostgresInsertCompiler._rewrite_insert_nothing
test
def _rewrite_insert_nothing(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.""" # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() where_clau...
python
{ "resource": "" }
q268873
PostgresInsertCompiler._build_conflict_target
test
def _build_conflict_target(self): """Builds the `conflict_target` for the ON CONFLICT clause.""" conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' ...
python
{ "resource": "" }
q268874
PostgresInsertCompiler._get_model_field
test
def _get_model_field(self, name: str): """Gets the field on a model with the specified name. Arguments: name: The name of the field to look for. This can be both the actual field name, or the name of the column, both will work :) Ret...
python
{ "resource": "" }
q268875
PostgresInsertCompiler._format_field_name
test
def _format_field_name(self, field_name) -> str: """Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL. """ field = self._get...
python
{ "resource": "" }
q268876
PostgresInsertCompiler._format_field_value
test
def _format_field_value(self, field_name) -> str: """Formats a field's value for usage in SQL. Arguments: field_name: The name of the field to format the value of. Returns: The field's value formatted for usage in SQL. ...
python
{ "resource": "" }
q268877
HStoreUniqueSchemaEditorMixin._create_hstore_unique
test
def _create_hstore_unique(self, model, field, keys): """Creates a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) columns = [ '(%s->\'%s\')' % (field.column, key) for key in keys ...
python
{ "resource": "" }
q268878
HStoreUniqueSchemaEditorMixin._rename_hstore_unique
test
def _rename_hstore_unique(self, old_table_name, new_table_name, old_field, new_field, keys): """Renames an existing UNIQUE constraint for the specified hstore keys.""" old_name = self._unique_constraint_name( old_table_name, old_field, keys) new...
python
{ "resource": "" }
q268879
HStoreUniqueSchemaEditorMixin._drop_hstore_unique
test
def _drop_hstore_unique(self, model, field, keys): """Drops a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) sql = self.sql_hstore_unique_drop.format(name=self.quote_name(name)) self.execute(sql)
python
{ "resource": "" }
q268880
HStoreUniqueSchemaEditorMixin._unique_constraint_name
test
def _unique_constraint_name(table: str, field, keys): """Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field. Arguments: table: The name of the table the field is a part of. field: The hstor...
python
{ "resource": "" }
q268881
HStoreUniqueSchemaEditorMixin._iterate_uniqueness_keys
test
def _iterate_uniqueness_keys(self, field): """Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over. """ uniqueness = getattr(field, 'uniqueness', None) if...
python
{ "resource": "" }
q268882
ConditionalJoin.add_condition
test
def add_condition(self, field, value: Any) -> None: """Adds an extra condition to this join. Arguments: field: The field that the condition will apply to. value: The value to compare. """ self.extra_conditions.append((field, valu...
python
{ "resource": "" }
q268883
ConditionalJoin.as_sql
test
def as_sql(self, compiler, connection) -> Tuple[str, List[Any]]: """Compiles this JOIN into a SQL string.""" sql, params = super().as_sql(compiler, connection) qn = compiler.quote_name_unless_alias # generate the extra conditions extra_conditions = ' AND '.join([ '{...
python
{ "resource": "" }
q268884
tdist95conf_level
test
def tdist95conf_level(df): """Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: ...
python
{ "resource": "" }
q268885
pooled_sample_variance
test
def pooled_sample_variance(sample1, sample2): """Find the pooled sample variance for two samples. Args: sample1: one sample. sample2: the other sample. Returns: Pooled sample variance, as a float. """ deg_freedom = len(sample1) + len(sample2) - 2 mean1 = statistics.mean...
python
{ "resource": "" }
q268886
tscore
test
def tscore(sample1, sample2): """Calculate a t-test score for the difference between two samples. Args: sample1: one sample. sample2: the other sample. Returns: The t-test score, as a float. """ if len(sample1) != len(sample2): raise ValueError("different number of ...
python
{ "resource": "" }
q268887
is_significant
test
def is_significant(sample1, sample2): """Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool i...
python
{ "resource": "" }
q268888
topoSort
test
def topoSort(roots, getParents): """Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node """ results = [] visited = set() # Use iterative version to avoid stack limits for large datasets...
python
{ "resource": "" }
q268889
n_queens
test
def n_queens(queen_count): """N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the ...
python
{ "resource": "" }
q268890
UCTNode.play
test
def play(self, board): """ uct tree search """ color = board.color node = self path = [node] while True: pos = node.select(board) if pos == PASS: break board.move(pos) child = node.pos_child[pos] if not c...
python
{ "resource": "" }
q268891
UCTNode.select
test
def select(self, board): """ select move; unexplored children first, then according to uct value """ if self.unexplored: i = random.randrange(len(self.unexplored)) pos = self.unexplored[i] self.unexplored[i] = self.unexplored[len(self.unexplored) - 1] self...
python
{ "resource": "" }
q268892
UCTNode.random_playout
test
def random_playout(self, board): """ random play until both players pass """ for x in range(MAXMOVES): # XXX while not self.finished? if board.finished: break board.move(board.random_move())
python
{ "resource": "" }
q268893
filter_benchmarks
test
def filter_benchmarks(benchmarks, bench_funcs, base_ver): """Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The f...
python
{ "resource": "" }
q268894
expand_benchmark_name
test
def expand_benchmark_name(bm_name, bench_groups): """Recursively expand name benchmark names. Args: bm_name: string naming a benchmark or benchmark group. Yields: Names of actual benchmarks, with all group names fully expanded. """ expansion = bench_groups.get(bm_name) if expan...
python
{ "resource": "" }
q268895
gen_string_table
test
def gen_string_table(n): """Generates the list of strings that will be used in the benchmarks. All strings have repeated prefixes and suffices, and n specifies the number of repetitions. """ strings = [] def append(s): if USE_BYTES_IN_PY3K: strings.append(s.encode('latin1')...
python
{ "resource": "" }
q268896
init_benchmarks
test
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benc...
python
{ "resource": "" }
q268897
Spline.GetDomain
test
def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree])
python
{ "resource": "" }
q268898
Mattermost.fetch_items
test
def fetch_items(self, category, **kwargs): """Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Fetching messages of '%s' - '%s' c...
python
{ "resource": "" }
q268899
Mattermost._parse_posts
test
def _parse_posts(self, raw_posts): """Parse posts and returns in order.""" parsed_posts = self.parse_json(raw_posts) # Posts are not sorted. The order is provided by # 'order' key. for post_id in parsed_posts['order']: yield parsed_posts['posts'][post_id]
python
{ "resource": "" }