Search is not available for this dataset
text
stringlengths
75
104k
def save_game(self): """ save_game() asks the underlying game object (_g) to dump the contents of itself as JSON and then returns the JSON to :return: A JSON representation of the game object """ logging.debug("save_game called.") logging.debug("Validating game ...
def guess(self, *args): """ guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches)...
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._get_text_answer() return "{0} The correct answer was {1}. Please start a ne...
def _validate_game_object(self, op="unknown"): """ A helper method to provide validation of the game object (_g). If the game object does not exist or if (for any reason) the object is not a GameObject, then an exception will be raised. :param op: A string describing the operati...
def extra_context(request): """Adds useful global items to the context for use in templates. * *request*: the request object * *HOST*: host name of server * *IN_ADMIN*: True if you are in the django admin area """ host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \ or reque...
def fft(values, freq=None, timestamps=None, fill_missing=False): """ Adds options to :func:`scipy.fftpack.rfft`: * *freq* is the frequency the samples were taken at * *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true """ # ==========...
def create(self, server): """Create the challenge on the server""" return server.post( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def update(self, server): """Update existing challenge on the server""" return server.put( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def exists(self, server): """Check if a challenge exists on the server""" try: server.get( 'challenge', replacements={'slug': self.slug}) except Exception: return False return True
def from_server(cls, server, slug): """Retrieve a challenge from the MapRoulette server :type server """ challenge = server.get( 'challenge', replacements={'slug': slug}) return cls( **challenge)
def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'): """Extends :func:`logthing.utils.default_logging_dict` with django specific values. """ d = default_logging_dict(log_dir, handlers, filename) d['handlers'].update({ 'mail_admins':{ 'level':'ERROR', ...
def get_position(self, position_id): """ Returns position data. http://dev.wheniwork.com/#get-existing-position """ url = "/2/positions/%s" % position_id return self.position_from_json(self._get_resource(url)["position"])
def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "/2/positions" data = self._get_resource(url) positions = [] for entry in data['positions']: positions.append(self.position_from_j...
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
def print2elog(author='', title='', text='', link=None, file=None, now=None): """ Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : s...
def fopen(name, mode='r', buffering=-1): """Similar to Python's built-in `open()` function.""" f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
def sloccount(): '''Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ ....
def pyflakes(): '''passive check of python programs by pyflakes. requirements: - pyflakes_ should be installed. ``easy_install pyflakes`` options.paved.pycheck.pyflakes.param .. _pyflakes: http://pypi.python.org/pypi/pyflakes ''' # filter out subpackages packages = [x for x in opti...
def gaussian(x, mu, sigma): """ Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma...
def http_exception_error_handler( exception): """ Handle HTTP exception :param werkzeug.exceptions.HTTPException exception: Raised exception A response is returned, as formatted by the :py:func:`response` function. """ assert issubclass(type(exception), HTTPException), type(exception)...
def is_colour(value): """Returns True if the value given is a valid CSS colour, i.e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser. """ global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH value = value.strip() ...
def format_time(seconds): """Formats time as the string "HH:MM:SS".""" timedelta = datetime.timedelta(seconds=int(seconds)) mm, ss = divmod(timedelta.seconds, 60) if mm < 60: return "%02d:%02d" % (mm, ss) hh, mm = divmod(mm, 60) if hh < 24: retur...
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could...
def reynolds_number(length, speed, temperature=25): """ Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally, it can also take account of temperature effect of sea water. Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawat...
def froude_number(speed, length): """ Froude number utility function that return Froude number for vehicle at specific length and speed. :param speed: m/s speed of the vehicle :param length: metres length of the vehicle :return: Froude number of the vehicle (dimensionless) """ g = 9.80665 ...
def residual_resistance_coef(slenderness, prismatic_coef, froude_number): """ Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number. :param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displace...
def dimension(self, length, draught, beam, speed, slenderness_coefficient, prismatic_coefficient): """ Assign values for the main dimension of a ship. :param length: metres length of the vehicle :param draught: metres draught of the vehicle :param beam: metres b...
def resistance(self): """ Return resistance of the vehicle. :return: newton the resistance of the ship """ self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \ residual_resistance_coef(self.slenderness_coefficient, ...
def maximum_deck_area(self, water_plane_coef=0.88): """ Return the maximum deck area of the ship :param water_plane_coef: optional water plane coefficient :return: Area of the deck """ AD = self.beam * self.length * water_plane_coef return AD
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2): """ Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion pow...
def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. """ items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()) for item in items: item.set_fontsize(fontsize)
def less_labels(ax, x_fraction=0.5, y_fraction=0.5): """ Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively. """ nbins = _np.size(ax.get_xticklabels()) ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='x') nbins = _np.size(ax.get_yticklabels()) ...
def configure(self, url=None, token=None, test=False): """ Configure the api to use given url and token or to get them from the Config. """ if url is None: url = Config.get_value("url") if token is None: token = Config.get_value("token") ...
def send_zip(self, exercise, file, params): """ Send zipfile to TMC for given exercise """ resp = self.post( exercise.return_url, params=params, files={ "submission[file]": ('submission.zip', file) }, data={ ...
def _make_url(self, slug): """ Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted, sometimes we need to form our own. """ if slug.startswith("http"): return slug return "{0}{1}".format(self.server_...
def _do_request(self, method, slug, **kwargs): """ Does HTTP request sending / response validation. Prevents RequestExceptions from propagating """ # ensure we are configured if not self.configured: self.configure() url = self._make_url(slug) ...
def _to_json(self, resp): """ Extract json from a response. Assumes response is valid otherwise. Internal use only. """ try: json = resp.json() except ValueError as e: reason = "TMC Server did not send valid JSON: {0}" ...
def _normalize_instancemethod(instance_method): """ wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick """ if not hasattr(instance_method, 'im_self'): return instance_met...
def safe_joinall(greenlets, timeout=None, raise_error=False): """ Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it joins for. """ greenlets = list(greenlets) try: gevent.joinall(greenlets, timeout=timeout, raise_error=raise_erro...
def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(16, 12), rows=2, columns=2, cmap=None, **kwargs): """ Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*. * *cmap*: Specifies color map * *cbar*: Add color bars * *show*: If false, dismisses eac...
def error(code: int, *args, **kwargs) -> HedgehogCommandError: """ Creates an error from the given code, and args and kwargs. :param code: The acknowledgement code :param args: Exception args :param kwargs: Exception kwargs :return: the error for the given acknowledgement code """ # TOD...
def to_message(self): """ Creates an error Acknowledgement message. The message's code and message are taken from this exception. :return: the message representing this exception """ from .messages import ack return ack.Acknowledgement(self.code, self.args[0] if ...
def clean(options, info): """Clean up extra files littering the source tree. options.paved.clean.dirs: directories to search recursively options.paved.clean.patterns: patterns to search for and remove """ info("Cleaning patterns %s", options.paved.clean.patterns) for wd in options.paved.clean.d...
def printoptions(): '''print paver options. Prettified by json. `long_description` is removed ''' x = json.dumps(environment.options, indent=4, sort_keys=True, skipkeys=True, cls=MyEncoder) print(x)
def parse(self, data: RawMessage) -> Message: """\ Parses a binary protobuf message into a Message object. """ try: return self.receiver.parse(data) except KeyError as err: raise UnknownCommandError from err except DecodeError as err: r...
def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): """ Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters --------...
def factory(cls, data_class, **kwargs): """Creates a ``DCCGraph``, a root :class:`Node`: and the node's associated data class instance. This factory is used to get around the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within it having pointers to each other. :par...
def factory_from_graph(cls, data_class, root_args, children): """Creates a ``DCCGraph`` and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a :class:`Node` and its corresponding :class:`BaseNodeData` subclass from the data_class specified. ...
def find_nodes(self, **kwargs): """Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a :class:`django.db.models.query.QuerySet`` of the attached :class:`Node` objects. :param kwargs: filter arguments app...
def add_child(self, **kwargs): """Creates a new ``Node`` based on the extending class and adds it as a child to this ``Node``. :param kwargs: arguments for constructing the data object associated with this ``Node`` :returns: extender of the ``Node``...
def connect_child(self, node): """Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect """ if node.graph != self.graph: raise AttributeError('cannot connect nod...
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(...
def ancestors_root(self): """Returns a list of the ancestors of this node but does not pass the root node, even if the root has parents due to cycles.""" if self.is_root(): return [] ancestors = set([]) self._depth_ascend(self, ancestors, True) try: ...
def descendents(self): """Returns a list of descendents of this node.""" visited = set([]) self._depth_descend(self, visited) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(vis...
def descendents_root(self): """Returns a list of descendents of this node, if the root node is in the list (due to a cycle) it will be included but will not pass through it. """ visited = set([]) self._depth_descend(self, visited, True) try: visited....
def can_remove(self): """Returns True if it is legal to remove this node and still leave the graph as a single connected entity, not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted. """ if self.children.count() == 0: r...
def remove(self): """Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises Attri...
def prune(self): """Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. :returns: list of :class:`BaseDataNode` subclassers associated with the removed ``Node`` objects. """ targ...
def prune_list(self): """Returns a list of nodes that would be removed if prune were called on this element. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem ...
def _child_allowed(self, child_rule): """Called to verify that the given rule can become a child of the current node. :raises AttributeError: if the child is not allowed """ num_kids = self.node.children.count() num_kids_allowed = len(self.rule.children) ...
def add_child_rule(self, child_rule): """Add a child path in the :class:`Flow` graph using the given :class:`Rule` subclass. This will create a new child :class:`Node` in the associated :class:`Flow` object's state graph with a new :class:`FlowNodeData` instance attached. ...
def connect_child(self, child_node): """Adds a connection to an existing rule in the :class`Flow` graph. The given :class`Rule` subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. :param child_node: ``FlowNodeData`` to att...
def in_use(self): """Returns True if there is a :class:`State` object that uses this ``Flow``""" state = State.objects.filter(flow=self).first() return bool(state)
def start(self, flow): """Factory method for a running state based on a flow. Creates and returns a ``State`` object and calls the associated :func:`Rule.on_enter` method. :param flow: :class:`Flow` which defines this state machine :returns: newly crea...
def next_state(self, rule=None): """Proceeds to the next step in the flow. Calls the associated :func:`Rule.on_leave` method for the for the current rule and the :func:`Rule.on_enter` for the rule being entered. If the current step in the flow is multipath then a valid :class:`Rule` su...
def get_location(self, location_id): """ Returns location data. http://dev.wheniwork.com/#get-existing-location """ url = "/2/locations/%s" % location_id return self.location_from_json(self._get_resource(url)["location"])
def get_locations(self): """ Returns a list of locations. http://dev.wheniwork.com/#listing-locations """ url = "/2/locations" data = self._get_resource(url) locations = [] for entry in data['locations']: locations.append(self.location_from_j...
def X(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._X is None: X = _copy.deepcopy(self.X_unweighted) # print 'X shape is {}'.format(X.shape) for i, el in enumerate(X): X[i, :] = el/self.y_error[i] ...
def y(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._y is None: self._y = self.y_unweighted/self.y_error return self._y
def y_fit(self): """ Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i` """ if self._y_fit is None: self._y_fit = _np.dot(self.X_unweighted, self.beta) return self._y_fit
def beta(self): """ The result :math:`\\beta` of the linear least squares """ if self._beta is None: # This is the linear least squares matrix formalism self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y) return self._beta
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
def chisq_red(self): """ The reduced chi-square of the linear least squares """ if self._chisq_red is None: self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False) return self._chisq_red
def create(self, server): """Create the task on the server""" if len(self.geometries) == 0: raise Exception('no geometries') return server.post( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, ...
def update(self, server): """Update existing task on the server""" return server.put( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
def from_server(cls, server, slug, identifier): """Retrieve a task from the server""" task = server.get( 'task', replacements={ 'slug': slug, 'identifier': identifier}) return cls(**task)
def formatter(color, s): """ Formats a string with color """ if no_coloring: return s return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET)
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versio...
def pdf2png(file_in, file_out): """ Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.) Parameters ---------- file_in : str The path to the pdf file to be converted. file_out : str The path to t...
def get_user(self, user_id): """ Returns user profile data. http://dev.wheniwork.com/#get-existing-user """ url = "/2/users/%s" % user_id return self.user_from_json(self._get_resource(url)["user"])
def get_users(self, params={}): """ Returns a list of users. http://dev.wheniwork.com/#listing-users """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/users/?%s" % urlencode(param_list) data = self._get_resource(url) users = [] ...
def _setVirtualEnv(): """Attempt to set the virtualenv activate command, if it hasn't been specified. """ try: activate = options.virtualenv.activate_cmd except AttributeError: activate = None if activate is None: virtualenv = path(os.environ.get('VIRTUAL_ENV', '')) ...
def shv(command, capture=False, ignore_error=False, cwd=None): """Run the given command inside the virtual environment, if available: """ _setVirtualEnv() try: command = "%s; %s" % (options.virtualenv.activate_cmd, command) except AttributeError: pass return bash(command, capture...
def update(dst, src): """Recursively update the destination dict-like object with the source dict-like object. Useful for merging options and Bunches together! Based on: http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1 """ stack = [(dst, src)] ...
def pip_install(*args): """Send the given arguments to `pip install`. """ download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else '' shv('pip install %s%s' % (download_cache, ' '.join(args)))
def _get_resource(self, url, data_key=None): """ When I Work GET method. Return representation of the requested resource. """ headers = {"Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().getU...
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, hea...
def _post_resource(self, url, body): """ When I Work POST method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().postURL(url, ...
def _delete_resource(self, url): """ When I Work DELETE method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().deleteURL(url, ...
def get_shifts(self, params={}): """ List shifts http://dev.wheniwork.com/#listing-shifts """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/shifts/?%s" % urlencode(param_list) data = self._get_resource(url) shifts = [] locations...
def create_shift(self, params={}): """ Creates a shift http://dev.wheniwork.com/#create/update-shift """ url = "/2/shifts/" body = params data = self._post_resource(url, body) shift = self.shift_from_json(data["shift"]) return shift
def delete_shifts(self, shifts): """ Delete existing shifts. http://dev.wheniwork.com/#delete-shift """ url = "/2/shifts/?%s" % urlencode( {'ids': ",".join(str(s) for s in shifts)}) data = self._delete_resource(url) return data
def delete_past_events(self): """ Removes old events. This is provided largely as a convenience for maintenance purposes (daily_cleanup). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name...
def recently_ended(self): """ Determines if event ended recently (within 5 days). Useful for attending list. """ if self.ended(): end_date = self.end_date if self.end_date else self.start_date if end_date >= offset.date(): return True
def all_comments(self): """ Returns combined list of event and update comments. """ ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event') update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update') update_ids...
def get_all_images(self): """ Returns chained list of event and update images. """ self_imgs = self.image_set.all() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids) return list(chain(self_i...
def get_all_images_count(self): """ Gets count of all images from both event and updates. """ self_imgs = self.image_set.count() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids).count() coun...
def get_top_assets(self): """ Gets images and videos to populate top assets. Map is built separately. """ images = self.get_all_images()[0:14] video = [] if supports_video: video = self.eventvideo_set.all()[0:10] return list(chain(images, vid...
def plot_featured(*args, **kwargs): """ Wrapper for matplotlib.pyplot.plot() / errorbar(). Takes options: * 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here. * 'fig': figure to use. * 'figlabel': f...
def decorate(msg="", waitmsg="Please wait"): """ Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): ...