Search is not available for this dataset
text
stringlengths
75
104k
def dict_to_env(d, pathsep=os.pathsep): ''' Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep) ''' out_env = {} for k, v in d.iteritems(): if isinstance(v, list): out_env[k] = pathsep.join(v) elif isinstance(v, string_types): out_env[k] = v else: raise TypeError('{} not a valid env var type'.format(type(v))) return out_env
def expand_envvars(env): ''' Expand all environment variables in an environment dict :param env: Environment dict ''' out_env = {} for k, v in env.iteritems(): out_env[k] = Template(v).safe_substitute(env) # Expand twice to make sure we expand everything we possibly can for k, v in out_env.items(): out_env[k] = Template(v).safe_substitute(out_env) return out_env
def get_store_env_tmp(): '''Returns an unused random filepath.''' tempdir = tempfile.gettempdir() temp_name = 'envstore{0:0>3d}' temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9))) if not os.path.exists(temp_path): return temp_path else: return get_store_env_tmp()
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.write(env_dict) return path
def restore_env(env_dict): '''Set environment variables in the current python process from a dict containing envvars and values.''' if hasattr(sys, 'real_prefix'): sys.prefix = sys.real_prefix del(sys.real_prefix) replace_osenviron(expand_envvars(dict_to_env(env_dict)))
def restore_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) restore_env(env_dict)
def set_env(*env_dicts): '''Set environment variables in the current python process from a dict containing envvars and values.''' old_env_dict = env_to_dict(os.environ.data) new_env_dict = join_dicts(old_env_dict, *env_dicts) new_env = dict_to_env(new_env_dict) replace_osenviron(expand_envvars(new_env))
def set_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) if 'environment' in env_dict: env_dict = env_dict['environment'] set_env(env_dict)
def upstream_url(self, uri): "Returns the URL to the upstream data source for the given URI based on configuration" return self.application.options.upstream + self.request.uri
def cache_get(self): "Returns (headers, body) from the cache or raise KeyError" key = self.cache_key() (headers, body, expires_ts) = self.application._cache[key] if expires_ts < time.now(): # asset has expired, delete it del self.application._cache[key] raise KeyError(key) return (headers, body)
def make_upstream_request(self): "Return request object for calling the upstream" url = self.upstream_url(self.request.uri) return tornado.httpclient.HTTPRequest(url, method=self.request.method, headers=self.request.headers, body=self.request.body if self.request.body else None)
def ttl(self, response): """Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public no-cache no-store max-age: seconds s-maxage: seconds must-revalidate proxy-revalidate - expires: Thu, 01 Dec 1983 20:00:00 GMT - pragma: no-cache (=cache-control: no-cache) See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/ TODO: tests """ if response.code != 200: return 0 if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0 try: pragma = self.request.headers['pragma'] if pragma == 'no-cache': return 0 except KeyError: pass try: cache_control = self.request.headers['cache-control'] # no caching options for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']: if cache_control.find(option): return 0 # further parsing to get a ttl options = parse_cache_control(cache_control) try: return int(options['s-maxage']) except KeyError: pass try: return int(options['max-age']) except KeyError: pass if 's-maxage' in options: max_age = options['s-maxage'] if max_age < ttl: ttl = max_age if 'max-age' in options: max_age = options['max-age'] if max_age < ttl: ttl = max_age return ttl except KeyError: pass try: expires = self.request.headers['expires'] return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time() except KeyError: pass
def hist2d(x, y, bins=10, labels=None, aspect="auto", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs): """ Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of *fig*, then the last axis, to use an already-created window. Plotting (*plot*) is on by default, setting false doesn't attempt to create a figure. *interpolation* sets the interpolation type of :meth:`matplotlib.axis.imshow`. Returns a handle and extent as :code:`h, extent` """ h_range = kwargs.pop('range', None) h_normed = kwargs.pop('normed', None) h_weights = kwargs.pop('weights', None) h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights) extent = [xe[0], xe[-1], ye[0], ye[-1]] # fig = plt.figure() if plot: if ax is None: if fig is None: fig = _figure('hist2d') ax = fig.gca() ax.clear() img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs) if cbar: _colorbar(ax=ax, im=img) if labels is not None: _addlabel(labels[0], labels[1], labels[2]) # _showfig(fig, aspect) return h, extent
def w_p(self): """ Plasma frequency :math:`\\omega_p` for given plasma density """ return _np.sqrt(self.n_p * _np.power(_spc.e, 2) / (_spc.m_e * _spc.epsilon_0))
def k_ion(self, E): """ Geometric focusing force due to ion column for given plasma density as a function of *E* """ return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)
def manifest(): """Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive. `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive. `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft` `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune` """ prune = options.paved.dist.manifest.prune graft = set() if options.paved.dist.manifest.include_sphinx_docroot: docroot = options.get('docroot', 'docs') graft.update([docroot]) if options.paved.dist.manifest.exclude_sphinx_builddir: builddir = docroot + '/' + options.get("builddir", ".build") prune.update([builddir]) with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo: for item in graft: fo.write('graft %s\n' % item) for item in options.paved.dist.manifest.include: fo.write('include %s\n' % item) for item in options.paved.dist.manifest.recursive_include: fo.write('recursive-include %s\n' % item) for item in prune: fo.write('prune %s\n' % item)
def accessor(parser, token): """This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above surrounded in square brackets For each variable or literal parameter given a `getattr` is called on the object, chaining to the next parameter. For any sqaure bracket enclosed items the access is done through a dictionary lookup. Example:: {% accessor car where 'front_seat' [position] ['fabric'] %} The above would result in the following chain of commands: .. code-block:: python ref = getattr(car, where) ref = getattr(ref, 'front_seat') ref = ref[position] return ref['fabric'] This tag also supports "as" syntax, putting the results into a template variable:: {% accessor car 'interior' as foo %} """ contents = token.split_contents() tag = contents[0] if len(contents) < 3: raise template.TemplateSyntaxError(('%s requires at least two ' 'arguments: object and one or more getattr parms') % tag) as_var = None if len(contents) >= 4: # check for "as" syntax if contents[-2] == 'as': as_var = contents[-1] contents = contents[:-2] return AccessorNode(contents[1], contents[2:], as_var)
def get_field_value_from_context(field_name, context_list): """ Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from first item on context. """ field_path = field_name.split('.') if field_path[0] == '<root>': context_index = 0 field_path.pop(0) else: context_index = -1 while field_path[0] == '<context>': context_index -= 1 field_path.pop(0) try: field_value = context_list[context_index] while len(field_path): field = field_path.pop(0) if isinstance(field_value, (list, tuple, ListModel)): if field.isdigit(): field = int(field) field_value = field_value[field] elif isinstance(field_value, dict): try: field_value = field_value[field] except KeyError: if field.isdigit(): field = int(field) field_value = field_value[field] else: field_value = None else: field_value = getattr(field_value, field) return field_value except (IndexError, AttributeError, KeyError, TypeError): return None
def create_threadpool_executed_func(original_func): """ Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function """ def wrapped_func(*args, **kwargs): try: result = original_func(*args, **kwargs) return True, result except: return False, sys.exc_info() def new_func(*args, **kwargs): status, result = gevent.get_hub().threadpool.apply(wrapped_func, args, kwargs) if status: return result else: six.reraise(*result) new_func.__name__ = original_func.__name__ new_func.__doc__ = "(gevent-friendly)" + (" " + original_func.__doc__ if original_func.__doc__ is not None else "") return new_func
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a pathname so it is not longer than *max_length* characters. The resulting pathname is returned. It does so by replacing characters at the start of the *pathname* with three dots, if necessary. The idea is that the end of the *pathname* is the most important part to be able to identify the file. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(pathname) > max_length: pathname = "...{}".format(pathname[-(max_length-3):]) return pathname
def format_time_point( time_point_string): """ :param str time_point_string: String representation of a time point to format :return: Formatted time point :rtype: str :raises ValueError: If *time_point_string* is not formatted by dateutil.parser.parse See :py:meth:`datetime.datetime.isoformat` function for supported formats. """ time_point = dateutil.parser.parse(time_point_string) if not is_aware(time_point): time_point = make_aware(time_point) time_point = local_time_point(time_point) return time_point.strftime("%Y-%m-%dT%H:%M:%S")
def format_uuid( uuid, max_length=10): """ Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function formats a UUID so it is not longer than *max_length* characters. The resulting string is returned. It does so by replacing characters at the end of the *uuid* with three dots, if necessary. The idea is that the start of the *uuid* is the most important part to be able to identify the related entity. The default *max_length* is 10, which will result in a string containing the first 7 characters of the *uuid* passed in. Most of the time, such a string is still unique within a collection of UUIDs. """ if max_length <= 3: raise ValueError("max length must be larger than 3") if len(uuid) > max_length: uuid = "{}...".format(uuid[0:max_length-3]) return uuid
def chisquare(observe, expect, error, ddof, verbose=True): """ Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom. *verbose* flag determines if the reduced chi square is printed to the terminal. """ chisq = 0 error = error.flatten() observe = observe.flatten() expect = expect.flatten() for i, el in enumerate(observe): chisq = chisq + _np.power((el - expect[i]) / error[i], 2) red_chisq = chisq / (len(observe) - ddof) if verbose: # print 'Chi-Squared is {}.'.format(chisq) print('Reduced Chi-Squared is {}.'.format(red_chisq)) return red_chisq
def frexp10(x): """ Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. exponent : float Number :math:`e` such that :math:`x = m 10^e`. """ expon = _np.int(_np.floor(_np.log10(_np.abs(x)))) mant = x/_np.power(10, expon) return (mant, expon)
def get_upcoming_events_count(days=14, featured=False): """ Returns count of upcoming events for a given number of days, either featured or all Usage: {% get_upcoming_events_count DAYS as events_count %} with days being the number of days you want, or 5 by default """ from happenings.models import Event start_period = today - datetime.timedelta(days=2) end_period = today + datetime.timedelta(days=days) if featured: return Event.objects.filter( featured=True, start_date__gte=start_period, start_date__lte=end_period ).count() return Event.objects.filter(start_date__gte=start_period, start_date__lte=end_period).count()
def get_upcoming_events(num, days, featured=False): """ Get upcoming events. Allows slicing to a given number, picking the number of days to hold them after they've started and whether they should be featured or not. Usage: {% get_upcoming_events 5 14 featured as events %} Would return no more than 5 Featured events, holding them for 14 days past their start date. """ from happenings.models import Event start_date = today - datetime.timedelta(days=days) events = Event.objects.filter(start_date__gt=start_date).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:num] return events
def get_events_by_date_range(days_out, days_hold, max_num=5, featured=False): """ Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usage: {% get_events_by_date_range 14 3 3 'featured' as events %} Would return no more than 3 featured events, that fall within the next 14 days or have ended within the past 3. """ from happenings.models import Event range_start = today - datetime.timedelta(days=days_hold) range_end = today + datetime.timedelta(days=days_out) events = Event.objects.filter( start_date__gte=range_start, start_date__lte=range_end ).order_by('start_date') if featured: events = events.filter(featured=True) events = events[:max_num] return events
def paginate_update(update): """ attempts to get next and previous on updates """ from happenings.models import Update time = update.pub_time event = update.event try: next = Update.objects.filter( event=event, pub_time__gt=time ).order_by('pub_time').only('title')[0] except: next = None try: previous = Update.objects.filter( event=event, pub_time__lt=time ).order_by('-pub_time').only('title')[0] except: previous = None return {'next': next, 'previous': previous, 'event': event}
def notify_client( notifier_uri, client_id, status_code, message=None): """ Notify the client of the result of handling a request The payload contains two elements: - client_id - result The *client_id* is the id of the client to notify. It is assumed that the notifier service is able to identify the client by this id and that it can pass the *result* to it. The *result* always contains a *status_code* element. In case the message passed in is not None, it will also contain a *message* element. In case the notifier service does not exist or returns an error, an error message will be logged to *stderr*. """ payload = { "client_id": client_id, "result": { "response": { "status_code": status_code } } } if message is not None: payload["result"]["response"]["message"] = message response = requests.post(notifier_uri, json=payload) if response.status_code != 201: sys.stderr.write("failed to notify client: {}\n".format(payload)) sys.stderr.flush()
def consume_message( method): """ Decorator for methods handling requests from RabbitMQ The goal of this decorator is to perform the tasks common to all methods handling requests: - Log the raw message to *stdout* - Decode the message into a Python dictionary - Log errors to *stderr* - Signal the broker that we're done handling the request The method passed in will be called with the message body as a dictionary. It is assumed here that the message body is a JSON string encoded in UTF8. """ def wrapper( self, channel, method_frame, header_frame, body): # Log the message sys.stdout.write("received message: {}\n".format(body)) sys.stdout.flush() try: # Grab the data and call the method body = body.decode("utf-8") data = json.loads(body) method(self, data) except Exception as exception: # Log the error message sys.stderr.write("{}\n".format(traceback.format_exc())) sys.stderr.flush() # Signal the broker we are done channel.basic_ack(delivery_tag=method_frame.delivery_tag) return wrapper
def consume_message_with_notify( notifier_uri_getter): """ Decorator for methods handling requests from RabbitMQ This decorator builds on the :py:func:`consume_message` decorator. It extents it by logic for notifying a client of the result of handling the request. The *notifier_uri_getter* argument must be a callable which accepts *self* and returns the uri of the notifier service. """ def consume_message_with_notify_decorator( method): @consume_message def wrapper( self, data): notifier_uri = notifier_uri_getter(self) client_id = data["client_id"] # Forward the call to the method and notify the client of the # result try: method(self, data) notify_client(notifier_uri, client_id, 200) except Exception as exception: notify_client(notifier_uri, client_id, 400, str(exception)) raise return wrapper return consume_message_with_notify_decorator
def get(self, key): """ >>> c = LRUCache() >>> c.get('toto') Traceback (most recent call last): ... KeyError: 'toto' >>> c.stats()['misses'] 1 >>> c.put('toto', 'tata') >>> c.get('toto') 'tata' >>> c.stats()['hits'] 1 """ try: value = self._cache[key] self._order.push(key) self._hits += 1 return value except KeyError, e: self._misses += 1 raise
def put(self, key, value): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 """ self._cache[key] = value self._order.push(key) self._size += 1
def delete(self, key): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.delete(1) >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.delete(1) Traceback (most recent call last): ... KeyError: 1 """ del self._cache[key] self._order.delete(key) self._size -= 1
def put(self, key, value): """ >>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() 4 >>> c.put(5, 5) >>> c.size() 4 >>> c.get(2) Traceback (most recent call last): ... KeyError: 2 """ mem = sys.getsizeof(value) if self._mem + mem > self._maxmem: self.delete(self.last()) LRUCache.put(self, key, (value, mem)) self._mem += mem
def delete(self, key): """ >>> c = MemSizeLRUCache() >>> c.put(1, 1) >>> c.mem() 24 >>> c.delete(1) >>> c.mem() 0 """ (_value, mem) = LRUCache.get(self, key) self._mem -= mem LRUCache.delete(self, key)
def put(self, key, value): """ >>> c = FixedSizeLRUCache(maxsize=5) >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' >>> c.size() 5 >>> c.put(6, 'six') >>> c.size() 5 >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.get(2) 'two' >>> c.put(7, 'seven') >>> c.get(2) 'two' >>> c.get(3) Traceback (most recent call last): ... KeyError: 3 """ # check if we're maxed out first if self.size() == self._maxsize: # need to kick something out... self.delete(self.last()) LRUCache.put(self, key, value)
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environment variable it not set. """ if name_hyphen in self._instance_settings: value = self._instance_settings[name_hyphen][1] else: msg = "No setting named '%s'" % name_hyphen raise UserFeedback(msg) if hasattr(value, 'startswith') and value.startswith("$"): env_var = value.lstrip("$") if env_var in os.environ: return os.getenv(env_var) else: msg = "'%s' is not defined in your environment" % env_var raise UserFeedback(msg) elif hasattr(value, 'startswith') and value.startswith("\$"): return value.replace("\$", "$") else: return value
def setting_values(self, skip=None): """ Returns dict of all setting values (removes the helpstrings). """ if not skip: skip = [] return dict( (k, v[1]) for k, v in six.iteritems(self._instance_settings) if not k in skip)
def _update_settings(self, new_settings, enforce_helpstring=True): """ This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system. Preferable to use update_settings (without leading _) in code to do the right thing and always have docstrings. """ for raw_setting_name, value in six.iteritems(new_settings): setting_name = raw_setting_name.replace("_", "-") setting_already_exists = setting_name in self._instance_settings value_is_list_len_2 = isinstance(value, list) and len(value) == 2 treat_as_tuple = not setting_already_exists and value_is_list_len_2 if isinstance(value, tuple) or treat_as_tuple: self._instance_settings[setting_name] = value else: if setting_name not in self._instance_settings: if enforce_helpstring: msg = "You must specify param '%s' as a tuple of (helpstring, value)" raise InternalCashewException(msg % setting_name) else: # Create entry with blank helpstring. self._instance_settings[setting_name] = ('', value,) else: # Save inherited helpstring, replace default value. orig = self._instance_settings[setting_name] self._instance_settings[setting_name] = (orig[0], value,)
def settings_and_attributes(self): """Return a combined dictionary of setting values and attribute values.""" attrs = self.setting_values() attrs.update(self.__dict__) skip = ["_instance_settings", "aliases"] for a in skip: del attrs[a] return attrs
def get_reference_to_class(cls, class_or_class_name): """ Detect if we get a class or a name, convert a name to a class. """ if isinstance(class_or_class_name, type): return class_or_class_name elif isinstance(class_or_class_name, string_types): if ":" in class_or_class_name: mod_name, class_name = class_or_class_name.split(":") if not mod_name in sys.modules: __import__(mod_name) mod = sys.modules[mod_name] return mod.__dict__[class_name] else: return cls.load_class_from_locals(class_or_class_name) else: msg = "Unexpected Type '%s'" % type(class_or_class_name) raise InternalCashewException(msg)
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required for plugin '%s' (%s, defined in %s)" args = (cls.__name__, breadcrumbs, cls.__module__) raise InternalCashewException(msg % args) max_line_length = cls._class_settings.get('max-docstring-length') if max_line_length: for i, line in enumerate(docstring.splitlines()): if len(line) > max_line_length: msg = "docstring line %s of %s is %s chars too long" args = (i, cls.__name__, len(line) - max_line_length) raise Exception(msg % args) return docstring
def resourcePath(self, relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ from os import path import sys try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = path.dirname(path.abspath(__file__)) return path.join(base_path, relative_path)
def addLogbook(self, physDef= "LCLS", mccDef="MCC", initialInstance=False): '''Add new block of logbook selection windows. Only 5 allowed.''' if self.logMenuCount < 5: self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance)) self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef) self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef) self.logMenus[-1].show() self.logMenuCount += 1 if initialInstance: # Initial logbook menu can add additional menus, all others can only remove themselves. QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), self.addLogbook) else: from functools import partial QObject.connect(self.logMenus[-1].logButton, SIGNAL("clicked()"), partial(self.removeLogbook, self.logMenus[-1]))
def removeLogbook(self, menu=None): '''Remove logbook menu set.''' if self.logMenuCount > 1 and menu is not None: menu.removeMenu() self.logMenus.remove(menu) self.logMenuCount -= 1
def selectedLogs(self): '''Return selected log books by type.''' mcclogs = [] physlogs = [] for i in range(len(self.logMenus)): logType = self.logMenus[i].selectedType() log = self.logMenus[i].selectedProgram() if logType == "MCC": if log not in mcclogs: mcclogs.append(log) elif logType == "Physics": if log not in physlogs: physlogs.append(log) return mcclogs, physlogs
def acceptedUser(self, logType): '''Verify enetered user name is on accepted MCC logbook list.''' from urllib2 import urlopen, URLError, HTTPError import json isApproved = False userName = str(self.logui.userName.text()) if userName == "": return False # Must have a user name to submit entry if logType == "MCC": networkFault = False data = [] log_url = "https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=" + userName try: data = urlopen(log_url, None, 5).read() data = json.loads(data) except URLError as error: print("URLError: " + str(error.reason)) networkFault = True except HTTPError as error: print("HTTPError: " + str(error.reason)) networkFault = True # If network fails, ask user to verify if networkFault: msgBox = QMessageBox() msgBox.setText("Cannot connect to MCC Log Server!") msgBox.setInformativeText("Use entered User name anyway?") msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) msgBox.setDefaultButton(QMessageBox.Ok) if msgBox.exec_() == QMessageBox.Ok: isApproved = True if data != [] and (data is not None): isApproved = True else: isApproved = True return isApproved
def xmlSetup(self, logType, logList): """Create xml file with fields from logbook form.""" from xml.etree.ElementTree import Element, SubElement, ElementTree from datetime import datetime curr_time = datetime.now() if logType == "MCC": # Set up xml tags log_entry = Element('log_entry') title = SubElement(log_entry, 'title') program = SubElement(log_entry, 'program') timestamp = SubElement(log_entry, 'timestamp') priority = SubElement(log_entry, 'priority') os_user = SubElement(log_entry, 'os_user') hostname = SubElement(log_entry, 'hostname') text = SubElement(log_entry, 'text') log_user = SubElement(log_entry, 'log_user') # Check for multiple logbooks and parse into seperate tags logbook = [] for i in range(len(logList)): logbook.append(SubElement(log_entry, 'logbook')) logbook[i].text = logList[i].lower() # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" program.text = "152" priority.text = "NORMAL" os_user.text = "nobody" hostname.text = "mccelog" text.attrib['type'] = "text/plain" # Handle attachment if image exists if not self.imagePixmap.isNull(): attachment = SubElement(log_entry, 'attachment') attachment.attrib['name'] = "Figure 1" attachment.attrib['type'] = "image/" + self.imageType attachment.text = curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + "." + self.imageType # Set timestamp format timestamp.text = curr_time.strftime("%Y/%m/%d %H:%M:%S") fileName = "/tmp/" + curr_time.strftime("%Y%m%d_%H%M%S_") + str(curr_time.microsecond) + ".xml" else: # If using Physics logbook timeString = curr_time.strftime("%Y-%m-%dT%H:%M:%S") # Set up xml tags log_entry = Element(None) severity = SubElement(log_entry, 'severity') location = SubElement(log_entry, 'location') keywords = SubElement(log_entry, 'keywords') time = SubElement(log_entry, 'time') isodate = SubElement(log_entry, 'isodate') log_user = SubElement(log_entry, 'author') category = SubElement(log_entry, 'category') title = SubElement(log_entry, 'title') metainfo = SubElement(log_entry, 'metainfo') # Handle attachment if image exists if not self.imagePixmap.isNull(): imageFile = SubElement(log_entry, 'link') imageFile.text = timeString + "-00." + self.imageType thumbnail = SubElement(log_entry, 'file') thumbnail.text = timeString + "-00.png" text = SubElement(log_entry, 'text') # Logbook expects Text tag to come last (for some strange reason) # Take care of dummy, unchanging tags first log_entry.attrib['type'] = "LOGENTRY" category.text = "USERLOG" location.text = "not set" severity.text = "NONE" keywords.text = "none" time.text = curr_time.strftime("%H:%M:%S") isodate.text = curr_time.strftime("%Y-%m-%d") metainfo.text = timeString + "-00.xml" fileName = "/tmp/" + metainfo.text # Fill in user inputs log_user.text = str(self.logui.userName.text()) title.text = str(self.logui.titleEntry.text()) if title.text == "": QMessageBox().warning(self, "No Title entered", "Please enter a title for the entry...") return None text.text = str(self.logui.textEntry.toPlainText()) # If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail if text.text == "": text.text = " " # Create xml file xmlFile = open(fileName, "w") if logType == "MCC": ElementTree(log_entry).write(xmlFile) else: xmlString = self.prettify(log_entry) xmlFile.write(xmlString) xmlFile.write("\n") # Close with newline so cron job parses correctly xmlFile.close() return fileName.rstrip(".xml")
def prettify(self, elem): """Parse xml elements for pretty printing""" from xml.etree import ElementTree from re import sub rawString = ElementTree.tostring(elem, 'utf-8') parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing tag return parsedString[1:]
def prepareImages(self, fileName, logType): """Convert supplied QPixmap object to image file.""" import subprocess if self.imageType == "png": self.imagePixmap.save(fileName + ".png", "PNG", -1) if logType == "Physics": makePostScript = "convert " + fileName + ".png " + fileName + ".ps" process = subprocess.Popen(makePostScript, shell=True) process.wait() thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1) else: renameImage = "cp " + self.image + " " + fileName + ".gif" process = subprocess.Popen(renameImage, shell=True) process.wait() if logType == "Physics": thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio) thumbnailPixmap.save(fileName + ".png", "PNG", -1)
def submitEntry(self): """Process user inputs and subit logbook entry when user clicks Submit button""" # logType = self.logui.logType.currentText() mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MCC"): QMessageBox().warning(self, "Invalid User", "Please enter a valid user name!") return fileName = self.xmlSetup("MCC", mcclogs) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "MCC") success = self.sendToLogbook(fileName, "MCC") if physlogs != []: for i in range(len(physlogs)): fileName = self.xmlSetup("Physics", physlogs[i]) if fileName is None: return if not self.imagePixmap.isNull(): self.prepareImages(fileName, "Physics") success_phys = self.sendToLogbook(fileName, "Physics", physlogs[i]) success = success and success_phys self.done(success)
def sendToLogbook(self, fileName, logType, location=None): '''Process log information and push to selected logbooks.''' import subprocess success = True if logType == "MCC": fileString = "" if not self.imagePixmap.isNull(): fileString = fileName + "." + self.imageType logcmd = "xml2elog " + fileName + ".xml " + fileString process = subprocess.Popen(logcmd, shell=True) process.wait() if process.returncode != 0: success = False else: from shutil import copy path = "/u1/" + location.lower() + "/physics/logbook/data/" # Prod path # path = "/home/softegr/alverson/log_test/" # Dev path try: if not self.imagePixmap.isNull(): copy(fileName + ".png", path) if self.imageType == "png": copy(fileName + ".ps", path) else: copy(fileName + "." + self.imageType, path) # Copy .xml file last to ensure images will be picked up by cron job # print("Copying file " + fileName + " to path " + path) copy(fileName + ".xml", path) except IOError as error: print(error) success = False return success
def clearForm(self): """Clear all form fields (except author).""" self.logui.titleEntry.clear() self.logui.textEntry.clear() # Remove all log selection menus except the first while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
def setupUI(self): '''Create graphical objects for menus.''' labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labelSizePolicy.setHorizontalStretch(0) labelSizePolicy.setVerticalStretch(0) menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) menuSizePolicy.setHorizontalStretch(0) menuSizePolicy.setVerticalStretch(0) logTypeLayout = QHBoxLayout() logTypeLayout.setSpacing(0) typeLabel = QLabel("Log Type:") typeLabel.setMinimumSize(QSize(65, 0)) typeLabel.setMaximumSize(QSize(65, 16777215)) typeLabel.setSizePolicy(labelSizePolicy) logTypeLayout.addWidget(typeLabel) self.logType = QComboBox(self) self.logType.setMinimumSize(QSize(100, 0)) self.logType.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth()) self.logType.setSizePolicy(menuSizePolicy) logTypeLayout.addWidget(self.logType) logTypeLayout.setStretch(1, 6) programLayout = QHBoxLayout() programLayout.setSpacing(0) programLabel = QLabel("Program:") programLabel.setMinimumSize(QSize(60, 0)) programLabel.setMaximumSize(QSize(60, 16777215)) programLabel.setSizePolicy(labelSizePolicy) programLayout.addWidget(programLabel) self.programName = QComboBox(self) self.programName.setMinimumSize(QSize(100, 0)) self.programName.setMaximumSize(QSize(150, 16777215)) menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth()) self.programName.setSizePolicy(menuSizePolicy) programLayout.addWidget(self.programName) programLayout.setStretch(1, 6) # Initial instance allows adding additional menus, all following menus can only remove themselves. if self.initialInstance: self.logButton = QPushButton("+", self) self.logButton.setToolTip("Add logbook") else: self.logButton = QPushButton("-") self.logButton.setToolTip("Remove logbook") self.logButton.setMinimumSize(QSize(16, 16)) # 24x24 self.logButton.setMaximumSize(QSize(16, 16)) # 24x24 self.logButton.setObjectName("roundButton") # self.logButton.setAutoFillBackground(True) # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse) # self.logButton.setMask(region) self.logButton.setStyleSheet("QPushButton {border-radius: 8px;}") self._logSelectLayout = QHBoxLayout() self._logSelectLayout.setSpacing(6) self._logSelectLayout.addLayout(logTypeLayout) self._logSelectLayout.addLayout(programLayout) self._logSelectLayout.addWidget(self.logButton) self._logSelectLayout.setStretch(0, 6) self._logSelectLayout.setStretch(1, 6)
def show(self): '''Display menus and connect even signals.''' self.parent.addLayout(self._logSelectLayout) self.menuCount += 1 self._connectSlots()
def addLogbooks(self, type=None, logs=[], default=""): '''Add or change list of logbooks.''' if type is not None and len(logs) != 0: if type in self.logList: for logbook in logs: if logbook not in self.logList.get(type)[0]: # print("Adding log " + " to " + type + " log type.") self.logList.get(type)[0].append(logbook) else: # print("Adding log type: " + type) self.logList[type] = [] self.logList[type].append(logs) # If default given, auto-select upon menu creation if len(self.logList[type]) > 1 and default != "": self.logList.get(type)[1] == default else: self.logList.get(type).append(default) self.logType.clear() self.logType.addItems(list(self.logList.keys())) self.changeLogType()
def removeLogbooks(self, type=None, logs=[]): '''Remove unwanted logbooks from list.''' if type is not None and type in self.logList: if len(logs) == 0 or logs == "All": del self.logList[type] else: for logbook in logs: if logbook in self.logList[type]: self.logList[type].remove(logbook) self.changeLogType()
def changeLogType(self): '''Populate log program list to correspond with log type selection.''' logType = self.selectedType() programs = self.logList.get(logType)[0] default = self.logList.get(logType)[1] if logType in self.logList: self.programName.clear() self.programName.addItems(programs) self.programName.setCurrentIndex(programs.index(default))
def addMenu(self): '''Add menus to parent gui.''' self.parent.multiLogLayout.addLayout(self.logSelectLayout) self.getPrograms(logType, programName)
def removeLayout(self, layout): '''Iteratively remove graphical objects from layout.''' for cnt in reversed(range(layout.count())): item = layout.takeAt(cnt) widget = item.widget() if widget is not None: widget.deleteLater() else: '''If sublayout encountered, iterate recursively.''' self.removeLayout(item.layout())
def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None): """Adds labels to a plot.""" if (axes is None) and (ax is not None): axes = ax if (windowlabel is not None) and (fig is not None): fig.canvas.set_window_title(windowlabel) if fig is None: fig = _plt.gcf() if fig is not None and axes is None: axes = fig.get_axes() if axes == []: logger.error('No axes found!') if axes is not None: if toplabel is not None: axes.set_title(toplabel) if xlabel is not None: axes.set_xlabel(xlabel) if ylabel is not None: axes.set_ylabel(ylabel) if zlabel is not None: axes.set_zlabel(zlabel) if (clabel is not None) or (cb is not None): if (clabel is not None) and (cb is not None): cb.set_label(clabel) else: if clabel is None: logger.error('Missing colorbar label') else: logger.error('Missing colorbar instance')
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.getsourcelines(obj) except: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = relpath(fn, start=dirname(scisalt.__file__)) if 'dev' in scisalt.__version__: return "http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s" % ( fn, linespec) else: return "http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s" % ( scisalt.__version__, fn, linespec)
def call_manage(cmd, capture=False, ignore_error=False): """Utility function to run commands against Django's `django-admin.py`/`manage.py`. `options.paved.django.project`: the path to the django project files (where `settings.py` typically resides). Will fall back to a DJANGO_SETTINGS_MODULE environment variable. `options.paved.django.manage_py`: the path where the django project's `manage.py` resides. """ settings = (options.paved.django.settings or os.environ.get('DJANGO_SETTINGS_MODULE')) if settings is None: raise BuildFailure("No settings path defined. Use: options.paved.django.settings = 'path.to.project.settings'") manage_py = options.paved.django.manage_py if manage_py is None: manage_py = 'django-admin.py' else: manage_py = path(manage_py) manage_py = 'cd {manage_py.parent}; python ./{manage_py.name}'.format(**locals()) return util.shv('{manage_py} {cmd} --settings={settings}'.format(**locals()), capture=capture, ignore_error=ignore_error)
def syncdb(args): """Update the database with model schema. Shorthand for `paver manage syncdb`. """ cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput' call_manage(cmd) for fixture in options.paved.django.syncdb.fixtures: call_manage("loaddata %s" % fixture)
def start(info): """Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port` """ cmd = options.paved.django.runserver if cmd == 'runserver_plus': try: import django_extensions except ImportError: info("Could not import django_extensions. Using default runserver.") cmd = 'runserver' port = options.paved.django.runserver_port if port: cmd = '%s %s' % (cmd, port) call_manage(cmd)
def schema(args): """Run South's schemamigration command. """ try: import south cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration' call_manage(cmd) except ImportError: error('Could not import south.')
def validate(cls, definition): ''' This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise. ''' schema_path = os.path.join(os.path.dirname(__file__), '../../schema/mapper_definition_schema.json') with open(schema_path, 'r') as jsonfp: schema = json.load(jsonfp) # Validation of JSON schema jsonschema.validate(definition, schema) # Validation of JSON properties relations assert definition['main_key'] in definition['supported_keys'], \ '\'main_key\' must be contained in \'supported_keys\'' assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \ '\'list_valued_keys\' must be a subset of \'supported_keys\'' assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \ '\'disjoint\' must be a subset of \'list_valued_keys\'' assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \ '\'The values of the \'key_synonyms\' mapping must be in \'supported_keys\''
def map(self, ID_s, FROM=None, TO=None, target_as_set=False, no_match_sub=None): ''' The main method of this class and the essence of the package. It allows to "map" stuff. Args: ID_s: Nested lists with strings as leafs (plain strings also possible) FROM (str): Origin key for the mapping (default: main key) TO (str): Destination key for the mapping (default: main key) target_as_set (bool): Whether to summarize the output as a set (removes duplicates) no_match_sub: Object representing the status of an ID not being able to be matched (default: None) Returns: Mapping: a mapping object capturing the result of the mapping request ''' def io_mode(ID_s): ''' Handles the input/output modalities of the mapping. ''' unlist_return = False list_of_lists = False if isinstance(ID_s, str): ID_s = [ID_s] unlist_return = True elif isinstance(ID_s, list): if len(ID_s) > 0 and isinstance(ID_s[0], list): # assuming ID_s is a list of lists of ID strings list_of_lists = True return ID_s, unlist_return, list_of_lists # interpret input if FROM == TO: return ID_s ID_s, unlist_return, list_of_lists = io_mode(ID_s) # map consistent with interpretation of input if list_of_lists: mapped_ids = [self.map(ID, FROM, TO, target_as_set, no_match_sub) for ID in ID_s] else: mapped_ids = self._map(ID_s, FROM, TO, target_as_set, no_match_sub) # return consistent with interpretation of input if unlist_return: return mapped_ids[0] return Mapping(ID_s, mapped_ids)
def get_all(self, key=None): ''' Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key ''' key = self.definition.main_key if key is None else key key = self.definition.key_synonyms.get(key, key) entries = self._get_all(key) if key in self.definition.scalar_nonunique_keys: return set(entries) return entries
def get_requests(self, params={}): """ List requests http://dev.wheniwork.com/#listing-requests """ if "status" in params: params['status'] = ','.join(map(str, params['status'])) requests = [] users = {} messages = {} params['page'] = 0 while True: param_list = [(k, params[k]) for k in sorted(params)] url = "/2/requests/?%s" % urlencode(param_list) data = self._get_resource(url) for entry in data["users"]: user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["requests"]: request = self.request_from_json(entry) requests.append(request) for entry in data["messages"]: message = Messages.message_from_json(entry) if message.request_id not in messages: messages[message.request_id] = [] messages[message.request_id].append(message) if not data['more']: break params['page'] += 1 for request in requests: request.user = users.get(request.user_id, None) request.messages = messages.get(request.request_id, []) return requests
def guess(self, *args): """ Make a guess, comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments, e.g: * for a normal game: 0, 1, 2, 3 * for a hex game: 0xA, 0xB, 5, 4 * alternate for hex game: 'A', 'b', 5, 4 :param args: An iterable of digits (int or str) :return: A dictionary object detailing the analysis and results of the guess """ if self.game is None: raise ValueError("The Game is unexpectedly undefined!") response_object = { "bulls": None, "cows": None, "analysis": None, "status": None } if self.game.status == self.GAME_WON: response_object["status"] = \ self._start_again_message("You already won!") elif self.game.status == self.GAME_LOST: response_object["status"] = \ self._start_again_message("You already lost!") elif self.game.guesses_remaining < 1: response_object["status"] = \ self._start_again_message("You've made too many guesses") else: guess_made = DigitWord(*args, wordtype=self.game.mode.digit_type) comparison = self.game.answer.compare(guess_made) self.game.guesses_made += 1 response_object["bulls"] = 0 response_object["cows"] = 0 response_object["analysis"] = [] for comparison_object in comparison: if comparison_object.match: response_object["bulls"] += 1 elif comparison_object.in_word: response_object["cows"] += 1 response_object["analysis"].append(comparison_object.get_object()) if response_object["bulls"] == self.game.mode.digits: self.game.status = self.GAME_WON self.game.guesses_made = self.game.mode.guesses_allowed response_object["status"] = self._start_again_message( "Congratulations, you win!" ) elif self.game.guesses_remaining < 1: self.game.status = self.GAME_LOST response_object["status"] = self._start_again_message( "Sorry, you lost!" ) return response_object
def load(self, game_json=None, mode=None): """ Load a game from a serialized JSON representation. The game expects a well defined structure as follows (Note JSON string format): '{ "guesses_made": int, "key": "str:a 4 word", "status": "str: one of playing, won, lost", "mode": { "digits": int, "digit_type": DigitWord.DIGIT | DigitWord.HEXDIGIT, "mode": GameMode(), "priority": int, "help_text": str, "instruction_text": str, "guesses_allowed": int }, "ttl": int, "answer": [int|str0, int|str1, ..., int|strN] }' * "mode" will be cast to a GameMode object * "answer" will be cast to a DigitWord object :param game_json: The source JSON - MUST be a string :param mode: A mode (str or GameMode) for the game being loaded :return: A game object """ if game_json is None: # New game_json if mode is not None: if isinstance(mode, str): _game_object = GameObject(mode=self._match_mode(mode=mode)) elif isinstance(mode, GameMode): _game_object = GameObject(mode=mode) else: raise TypeError("Game mode must be a GameMode or string") else: _game_object = GameObject(mode=self._game_modes[0]) _game_object.status = self.GAME_PLAYING else: if not isinstance(game_json, str): raise TypeError("Game must be passed as a serialized JSON string.") game_dict = json.loads(game_json) if not 'mode' in game_dict: raise ValueError("Mode is not provided in JSON; game_json cannot be loaded!") _mode = GameMode(**game_dict["mode"]) _game_object = GameObject(mode=_mode, source_game=game_dict) self.game = copy.deepcopy(_game_object)
def load_modes(self, input_modes=None): """ Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call. :param input_modes: A list of GameMode objects; nb: even if only one new GameMode object is provided, it MUST be passed as a list - for example, passing GameMode gm1 would require passing [gm1] NOT gm1. :return: A list of GameMode objects (both defaults and any added). """ # Set default game modes _modes = [ GameMode( mode="normal", priority=2, digits=4, digit_type=DigitWord.DIGIT, guesses_allowed=10 ), GameMode( mode="easy", priority=1, digits=3, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hard", priority=3, digits=6, digit_type=DigitWord.DIGIT, guesses_allowed=6 ), GameMode( mode="hex", priority=4, digits=4, digit_type=DigitWord.HEXDIGIT, guesses_allowed=10 ) ] if input_modes is not None: if not isinstance(input_modes, list): raise TypeError("Expected list of input_modes") for mode in input_modes: if not isinstance(mode, GameMode): raise TypeError("Expected list to contain only GameMode objects") _modes.append(mode) self._game_modes = copy.deepcopy(_modes)
def _start_again_message(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 = ', '.join( [str(d) for d in self.game.answer][:-1] ) + ', and ' + [str(d) for d in self.game.answer][-1] return "{0}{1} The correct answer was {2}. Please start a new game.".format( message, "." if message[-1] not in [".", ",", ";", ":", "!"] else "", the_answer )
def line(self, line): """Returns list of strings split by input delimeter Argument: line - Input line to cut """ # Remove empty strings in case of multiple instances of delimiter return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']
def get_message(self, message_id): """ Get Existing Message http://dev.wheniwork.com/#get-existing-message """ url = "/2/messages/%s" % message_id return self.message_from_json(self._get_resource(url)["message"])
def get_messages(self, params={}): """ List messages http://dev.wheniwork.com/#listing-messages """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/messages/?%s" % urlencode(param_list) data = self._get_resource(url) messages = [] for entry in data["messages"]: messages.append(self.message_from_json(entry)) return messages
def create_message(self, params={}): """ Creates a message http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/" body = params data = self._post_resource(url, body) return self.message_from_json(data["message"])
def update_message(self, message): """ Modify an existing message. http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/%s" % message.message_id data = self._put_resource(url, message.json_data()) return self.message_from_json(data)
def delete_messages(self, messages): """ Delete existing messages. http://dev.wheniwork.com/#delete-existing-message """ url = "/2/messages/?%s" % urlencode([('ids', ",".join(messages))]) data = self._delete_resource(url) return data
def get_site(self, site_id): """ Returns site data. http://dev.wheniwork.com/#get-existing-site """ url = "/2/sites/%s" % site_id return self.site_from_json(self._get_resource(url)["site"])
def get_sites(self): """ Returns a list of sites. http://dev.wheniwork.com/#listing-sites """ url = "/2/sites" data = self._get_resource(url) sites = [] for entry in data['sites']: sites.append(self.site_from_json(entry)) return sites
def create_site(self, params={}): """ Creates a site http://dev.wheniwork.com/#create-update-site """ url = "/2/sites/" body = params data = self._post_resource(url, body) return self.site_from_json(data["site"])
def admin_link_move_up(obj, link_text='up'): """Returns a link to a view that moves the passed in object up in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "up" :returns: HTML link code to view for moving the object """ if obj.rank == 1: return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank - 1)) return '<a href="%s">%s</a>' % (link, link_text)
def admin_link_move_down(obj, link_text='down'): """Returns a link to a view that moves the passed in object down in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "down" :returns: HTML link code to view for moving the object """ if obj.rank == obj.grouped_filter().count(): return '' content_type = ContentType.objects.get_for_model(obj) link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, obj.rank + 1)) return '<a href="%s">%s</a>' % (link, link_text)
def showfig(fig, aspect="auto"): """ Shows a figure with a typical orientation so that x and y axes are set up as expected. """ ax = fig.gca() # Swap y axis if needed alim = list(ax.axis()) if alim[3] < alim[2]: temp = alim[2] alim[2] = alim[3] alim[3] = temp ax.axis(alim) ax.set_aspect(aspect) fig.show()
def _setup_index(index): """Shifts indicies as needed to account for one based indexing Positive indicies need to be reduced by one to match with zero based indexing. Zero is not a valid input, and as such will throw a value error. Arguments: index - index to shift """ index = int(index) if index > 0: index -= 1 elif index == 0: # Zero indicies should not be allowed by default. raise ValueError return index
def cut(self, line): """Returns selected positions from cut input source in desired arrangement. Argument: line - input to cut """ result = [] line = self.line(line) for i, field in enumerate(self.positions): try: index = _setup_index(field) try: result += line[index] except IndexError: result.append(self.invalid_pos) except ValueError: result.append(str(field)) except TypeError: result.extend(self._cut_range(line, int(field[0]), i)) return ''.join(result)
def _setup_positions(self, positions): """Processes positions to account for ranges Arguments: positions - list of positions and/or ranges to process """ updated_positions = [] for i, position in enumerate(positions): ranger = re.search(r'(?P<start>-?\d*):(?P<end>\d*)', position) if ranger: if i > 0: updated_positions.append(self.separator) start = group_val(ranger.group('start')) end = group_val(ranger.group('end')) if start and end: updated_positions.extend(self._extendrange(start, end + 1)) # Since the number of positions on a line is unknown, # send input to cause exception that can be caught and call # _cut_range helper function elif ranger.group('start'): updated_positions.append([start]) else: updated_positions.extend(self._extendrange(1, end + 1)) else: updated_positions.append(positions[i]) try: if int(position) and int(positions[i+1]): updated_positions.append(self.separator) except (ValueError, IndexError): pass return updated_positions
def _cut_range(self, line, start, current_position): """Performs cut for range from start position to end Arguments: line - input to cut start - start of range current_position - current position in main cut function """ result = [] try: for j in range(start, len(line)): index = _setup_index(j) try: result.append(line[index]) except IndexError: result.append(self.invalid_pos) finally: result.append(self.separator) result.append(line[-1]) except IndexError: pass try: int(self.positions[current_position+1]) result.append(self.separator) except (ValueError, IndexError): pass return result
def _extendrange(self, start, end): """Creates list of values in a range with output delimiters. Arguments: start - range start end - range end """ range_positions = [] for i in range(start, end): if i != 0: range_positions.append(str(i)) if i < end: range_positions.append(self.separator) return range_positions
def lock_file(filename): """Locks the file by writing a '.lock' file. Returns True when the file is locked and False when the file was locked already""" lockfile = "%s.lock"%filename if isfile(lockfile): return False else: with open(lockfile, "w"): pass return True
def unlock_file(filename): """Unlocks the file by remove a '.lock' file. Returns True when the file is unlocked and False when the file was unlocked already""" lockfile = "%s.lock"%filename if isfile(lockfile): os.remove(lockfile) return True else: return False
def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist""" lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")] ccat_noext = cloud_catalog[0:cloud_catalog.rfind(".lrcat")] lsmart = join(dirname(local_catalog),"%s Smart Previews.lrdata"%basename(lcat_noext)) csmart = join(dirname(cloud_catalog),"%s Smart Previews.lrdata"%basename(ccat_noext)) if local2cloud and os.path.isdir(lsmart): logging.info("Copy Smart Previews - local to cloud: %s => %s"%(lsmart, csmart)) distutils.dir_util.copy_tree(lsmart,csmart, update=1) elif os.path.isdir(csmart): logging.info("Copy Smart Previews - cloud to local: %s => %s"%(csmart, lsmart)) distutils.dir_util.copy_tree(csmart,lsmart, update=1)
def hashsum(filename): """Return a hash of the file From <http://stackoverflow.com/a/7829658>""" with open(filename, mode='rb') as f: d = hashlib.sha1() for buf in iter(partial(f.read, 2**20), b''): d.update(buf) return d.hexdigest()
def cmd_init_push_to_cloud(args): """Initiate the local catalog and push it the cloud""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-push-to-cloud]: %s => %s"%(lcat, ccat)) if not isfile(lcat): args.error("[init-push-to-cloud] The local catalog does not exist: %s"%lcat) if isfile(ccat): args.error("[init-push-to-cloud] The cloud catalog already exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-push-to-cloud] The local meta-data already exist: %s"%lmeta) if isfile(cmeta): args.error("[init-push-to-cloud] The cloud meta-data already exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy catalog from local to cloud, which becomes the new "base" changeset util.copy(lcat, ccat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = ccat mfile['last_push']['hash'] = hashsum(lcat) mfile['last_push']['modification_utc'] = utcnow mfile.flush() mfile = MetaFile(cmeta) mfile['changeset']['is_base'] = True mfile['changeset']['hash'] = hashsum(lcat) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(ccat) mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally,let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-push-to-cloud]: Success!")
def cmd_init_pull_from_cloud(args): """Initiate the local catalog by downloading the cloud catalog""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat)) if isfile(lcat): args.error("[init-pull-from-cloud] The local catalog already exist: %s"%lcat) if not isfile(ccat): args.error("[init-pull-from-cloud] The cloud catalog does not exist: %s"%ccat) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if isfile(lmeta): args.error("[init-pull-from-cloud] The local meta-data already exist: %s"%lmeta) if not isfile(cmeta): args.error("[init-pull-from-cloud] The cloud meta-data does not exist: %s"%cmeta) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Copy base from cloud to local util.copy(ccat, lcat) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(cloudDAG.root.hash, cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) # Write meta-data both to local and cloud mfile = MetaFile(lmeta) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['catalog']['filename'] = lcat mfile['last_push']['filename'] = cloudDAG.leafs[0].mfile['changeset']['filename'] mfile['last_push']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['last_push']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile.flush() #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) logging.info("[init-pull-from-cloud]: Success!")
def cmd_normal(args): """Normal procedure: * Pull from cloud (if necessary) * Run Lightroom * Push to cloud """ logging.info("cmd_normal") (lcat, ccat) = (args.local_catalog, args.cloud_catalog) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if not isfile(lcat): args.error("The local catalog does not exist: %s"%lcat) if not isfile(ccat): args.error("The cloud catalog does not exist: %s"%ccat) #Let's "lock" the local catalog logging.info("Locking local catalog: %s"%(lcat)) if not lock_file(lcat): raise RuntimeError("The catalog %s is locked!"%lcat) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) lmfile = MetaFile(lmeta) cmfile = MetaFile(cmeta) #Apply changesets cloudDAG = ChangesetDAG(ccat) path = cloudDAG.path(lmfile['last_push']['hash'], cloudDAG.leafs[0].hash) util.apply_changesets(args, path, lcat) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=False) #Backup the local catalog (overwriting old backup) logging.info("Removed old backup: %s.backup"%lcat) util.remove("%s.backup"%lcat) util.copy(lcat, "%s.backup"%lcat) #Let's unlock the local catalog so that Lightroom can read it logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat) #Now we can start Lightroom if args.lightroom_exec_debug: logging.info("Debug Lightroom appending '%s' to %s"%(args.lightroom_exec_debug, lcat)) with open(lcat, "a") as f: f.write("%s\n"%args.lightroom_exec_debug) elif args.lightroom_exec: logging.info("Starting Lightroom: %s %s"%(args.lightroom_exec, lcat)) subprocess.call([args.lightroom_exec, lcat]) tmpdir = tempfile.mkdtemp() tmp_patch = join(tmpdir, "tmp.patch") diff_cmd = args.diff_cmd.replace("$in1", "%s.backup"%lcat)\ .replace("$in2", lcat)\ .replace("$out", tmp_patch) logging.info("Diff: %s"%diff_cmd) subprocess.call(diff_cmd, shell=True) patch = "%s_%s.zip"%(ccat, hashsum(tmp_patch)) util.copy(tmp_patch, patch) # Write cloud meta-data mfile = MetaFile("%s.lrcloud"%patch) utcnow = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4] mfile['changeset']['is_base'] = False mfile['changeset']['hash'] = hashsum(tmp_patch) mfile['changeset']['modification_utc'] = utcnow mfile['changeset']['filename'] = basename(patch) mfile['parent']['is_base'] = cloudDAG.leafs[0].mfile['changeset']['is_base'] mfile['parent']['hash'] = cloudDAG.leafs[0].mfile['changeset']['hash'] mfile['parent']['modification_utc'] = cloudDAG.leafs[0].mfile['changeset']['modification_utc'] mfile['parent']['filename'] = basename(cloudDAG.leafs[0].mfile['changeset']['filename']) mfile.flush() # Write local meta-data mfile = MetaFile(lmeta) mfile['catalog']['hash'] = hashsum(lcat) mfile['catalog']['modification_utc'] = utcnow mfile['last_push']['filename'] = patch mfile['last_push']['hash'] = hashsum(tmp_patch) mfile['last_push']['modification_utc'] = utcnow mfile.flush() shutil.rmtree(tmpdir, ignore_errors=True) #Let's copy Smart Previews if not args.no_smart_previews: copy_smart_previews(lcat, ccat, local2cloud=True) #Finally, let's unlock the catalog files logging.info("Unlocking local catalog: %s"%(lcat)) unlock_file(lcat)
def parse_arguments(argv=None): """Return arguments""" def default_config_path(): """Returns the platform specific default location of the configure file""" if os.name == "nt": return join(os.getenv('APPDATA'), "lrcloud.ini") else: return join(os.path.expanduser("~"), ".lrcloud.ini") parser = argparse.ArgumentParser( description='Cloud extension to Lightroom', formatter_class=argparse.ArgumentDefaultsHelpFormatter) cmd_group = parser.add_mutually_exclusive_group() cmd_group.add_argument( '--init-push-to-cloud', help='Initiate the local catalog and push it to the cloud', action="store_true" ) cmd_group.add_argument( '--init-pull-from-cloud', help='Download the cloud catalog and initiate a corresponding local catalog', action="store_true" ) parser.add_argument( '--cloud-catalog', help='The cloud/shared catalog file e.g. located in Google Drive or Dropbox', type=lambda x: os.path.expanduser(x) ) parser.add_argument( '--local-catalog', help='The local Lightroom catalog file', type=lambda x: os.path.expanduser(x) ) lr_exec = parser.add_mutually_exclusive_group() lr_exec.add_argument( '--lightroom-exec', help='The Lightroom executable file', type=str ) lr_exec.add_argument( '--lightroom-exec-debug', help='Instead of running Lightroom, append data to the end of the catalog file', type=str ) parser.add_argument( '-v', '--verbose', help='Increase output verbosity', action="store_true" ) parser.add_argument( '--no-smart-previews', help="Don't Sync Smart Previews", action="store_true" ) parser.add_argument( '--config-file', help="Path to the configure (.ini) file", type=str, default=default_config_path() ) parser.add_argument( '--diff-cmd', help="The command that given two files, $in1 and $in2, " "produces a diff file $out", type=str, #default="./jdiff -f $in1 $in2 $out" #default="bsdiff $in1 $in2 $out" ) parser.add_argument( '--patch-cmd', help="The command that given a file, $in1, and a path, " "$patch, produces a file $out", type=str, #default="./jptch $in1 $patch $out" #default="bspatch $in1 $out $patch" ) args = parser.parse_args(args=argv) args.error = parser.error if args.config_file in ['', 'none', 'None', "''", '""']: args.config_file = None if args.verbose: logging.basicConfig(level=logging.INFO) config_parser.read(args) (lcat, ccat) = (args.local_catalog, args.cloud_catalog) if lcat is None: parser.error("No local catalog specified, use --local-catalog") if ccat is None: parser.error("No cloud catalog specified, use --cloud-catalog") return args