Search is not available for this dataset
text
stringlengths
75
104k
def launch(title, items, selected=None): """ Launches a new menu. Wraps curses nicely so exceptions won't screw with the terminal too much. """ resp = {"code": -1, "done": False} curses.wrapper(Menu, title, items, selected, resp) return resp
def q(self, x, q0): """ Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`. """ y1_0 = q0 y0_0 = 0 y0 = [y0_0, y1_0] y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol) return y[:, 1]
def save(self, *args, **kwargs): """Overridden method that handles that re-ranking of objects and the integrity of the ``rank`` field. :param rerank: Added parameter, if True will rerank other objects based on the change in this save. Defaults to True. """ rerank = kwargs.pop('rerank', True) if rerank: if not self.id: self._process_new_rank_obj() elif self.rank == self._rank_at_load: # nothing changed pass else: self._process_moved_rank_obj() super(RankedModel, self).save(*args, **kwargs)
def repack(self): """Removes any blank ranks in the order.""" items = self.grouped_filter().order_by('rank').select_for_update() for count, item in enumerate(items): item.rank = count + 1 item.save(rerank=False)
def refetch_for_update(obj): """Queries the database for the same object that is passed in, refetching its contents and runs ``select_for_update()`` to lock the corresponding row until the next commit. :param obj: Object to refetch :returns: Refreshed version of the object """ return obj.__class__.objects.select_for_update().get(id=obj.id)
def get_field_names(obj, ignore_auto=True, ignore_relations=True, exclude=[]): """Returns the field names of a Django model object. :param obj: the Django model class or object instance to get the fields from :param ignore_auto: ignore any fields of type AutoField. Defaults to True :param ignore_relations: ignore any fields that involve relations such as the ForeignKey or ManyToManyField :param exclude: exclude anything in this list from the results :returns: generator of found field names """ from django.db.models import (AutoField, ForeignKey, ManyToManyField, ManyToOneRel, OneToOneField, OneToOneRel) for field in obj._meta.get_fields(): if ignore_auto and isinstance(field, AutoField): continue if ignore_relations and (isinstance(field, ForeignKey) or isinstance(field, ManyToManyField) or isinstance(field, ManyToOneRel) or isinstance(field, OneToOneRel) or isinstance(field, OneToOneField)): # optimization is killing coverage measure, have to put no-op that # does something a = 1; a continue if field.name in exclude: continue yield field.name
def get_obj_attr(obj, attr): """Works like getattr() but supports django's double underscore object dereference notation. Example usage: .. code-block:: python >>> get_obj_attr(book, 'writer__age') 42 >>> get_obj_attr(book, 'publisher__address') <Address object at 105a79ac8> :param obj: Object to start the derference from :param attr: String name of attribute to return :returns: Derferenced object :raises: AttributeError in the attribute in question does not exist """ # handle '__' referencing like in QuerySets fields = attr.split('__') field_obj = getattr(obj, fields[0]) for field in fields[1:]: # keep going down the reference tree field_obj = getattr(field_obj, field) return field_obj
def as_list(self): """Returns a list of strings describing the full paths and patterns along with the name of the urls. Example: .. code-block::python >>> u = URLTree() >>> u.as_list() [ 'admin/', 'admin/$, name=index', 'admin/login/$, name=login', ] """ result = [] for child in self.children: self._depth_traversal(child, result) return result
def register( app): """ Register all HTTP error code error handlers Currently, errors are handled by the JSON error handler. """ # Pick a handler based on the requested format. Currently we assume the # caller wants JSON. error_handler = json.http_exception_error_handler @app.errorhandler(400) def handle_bad_request( exception): return error_handler(exception) @app.errorhandler(404) def handle_not_found( exception): return error_handler(exception) @app.errorhandler(405) def handle_method_not_allowed( exception): return error_handler(exception) @app.errorhandler(422) def handle_unprocessable_entity( exception): return error_handler(exception) @app.errorhandler(500) def handle_internal_server_error( exception): return error_handler(exception)
def plot(*args, ax=None, **kwargs): """ Plots but automatically resizes x axis. .. versionadded:: 1.4 Parameters ---------- args Passed on to :meth:`matplotlib.axis.Axis.plot`. ax : :class:`matplotlib.axis.Axis`, optional The axis to plot to. kwargs Passed on to :meth:`matplotlib.axis.Axis.plot`. """ if ax is None: fig, ax = _setup_axes() pl = ax.plot(*args, **kwargs) if _np.shape(args)[0] > 1: if type(args[1]) is not str: min_x = min(args[0]) max_x = max(args[0]) ax.set_xlim((min_x, max_x)) return pl
def linspacestep(start, stop, step=1): """ Create a vector of values over an interval with a specified step size. Parameters ---------- start : float The beginning of the interval. stop : float The end of the interval. step : float The step size. Returns ------- vector : :class:`numpy.ndarray` The vector of values. """ # Find an integer number of steps numsteps = _np.int((stop-start)/step) # Do a linspace over the new range # that has the correct endpoint return _np.linspace(start, start+step*numsteps, numsteps+1)
def mylogger(name=None, filename=None, indent_offset=7, level=_logging.DEBUG, stream_level=_logging.WARN, file_level=_logging.INFO): """ Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels: * *level*: Parent logging level. * *stream_level*: Logging level for console stream. * *file_level*: Logging level for general file log. """ if name is not None: logger = _logging.getLogger(name) else: logger = _logging.getLogger() logger.setLevel(level) fmtr = IndentFormatter(indent_offset=indent_offset) fmtr_msgonly = IndentFormatter('%(funcName)s:%(lineno)d: %(message)s') ch = _logging.StreamHandler() ch.setLevel(stream_level) ch.setFormatter(fmtr_msgonly) logger.addHandler(ch) if filename is not None: debugh = _logging.FileHandler(filename='{}_debug.log'.format(filename), mode='w') debugh.setLevel(_logging.DEBUG) debugh.setFormatter(fmtr_msgonly) logger.addHandler(debugh) fh = _logging.FileHandler(filename='{}.log'.format(filename), mode='w') fh.setLevel(file_level) fh.setFormatter(fmtr) logger.addHandler(fh) return logger
def selected_course(func): """ Passes the selected course as the first argument to func. """ @wraps(func) def inner(*args, **kwargs): course = Course.get_selected() return func(course, *args, **kwargs) return inner
def selected_exercise(func): """ Passes the selected exercise as the first argument to func. """ @wraps(func) def inner(*args, **kwargs): exercise = Exercise.get_selected() return func(exercise, *args, **kwargs) return inner
def false_exit(func): """ If func returns False the program exits immediately. """ @wraps(func) def inner(*args, **kwargs): ret = func(*args, **kwargs) if ret is False: if "TMC_TESTING" in os.environ: raise TMCExit() else: sys.exit(-1) return ret return inner
def configure(server=None, username=None, password=None, tid=None, auto=False): """ Configure tmc.py to use your account. """ if not server and not username and not password and not tid: if Config.has(): if not yn_prompt("Override old configuration", False): return False reset_db() if not server: while True: server = input("Server url [https://tmc.mooc.fi/mooc/]: ").strip() if len(server) == 0: server = "https://tmc.mooc.fi/mooc/" if not server.endswith('/'): server += '/' if not (server.startswith("http://") or server.startswith("https://")): ret = custom_prompt( "Server should start with http:// or https://\n" + "R: Retry, H: Assume http://, S: Assume https://", ["r", "h", "s"], "r") if ret == "r": continue # Strip previous schema if "://" in server: server = server.split("://")[1] if ret == "h": server = "http://" + server elif ret == "s": server = "https://" + server break print("Using URL: '{0}'".format(server)) while True: if not username: username = input("Username: ") if not password: password = getpass("Password: ") # wow, such security token = b64encode( bytes("{0}:{1}".format(username, password), encoding='utf-8') ).decode("utf-8") try: api.configure(url=server, token=token, test=True) except APIError as e: print(e) if auto is False and yn_prompt("Retry authentication"): username = password = None continue return False break if tid: select(course=True, tid=tid, auto=auto) else: select(course=True)
def download(course, tid=None, dl_all=False, force=False, upgradejava=False, update=False): """ Download the exercises from the server. """ def dl(id): download_exercise(Exercise.get(Exercise.tid == id), force=force, update_java=upgradejava, update=update) if dl_all: for exercise in list(course.exercises): dl(exercise.tid) elif tid is not None: dl(int(tid)) else: for exercise in list(course.exercises): if not exercise.is_completed: dl(exercise.tid) else: exercise.update_downloaded()
def skip(course, num=1): """ Go to the next exercise. """ sel = None try: sel = Exercise.get_selected() if sel.course.tid != course.tid: sel = None except NoExerciseSelected: pass if sel is None: sel = course.exercises.first() else: try: sel = Exercise.get(Exercise.id == sel.id + num) except peewee.DoesNotExist: print("There are no more exercises in this course.") return False sel.set_select() list_all(single=sel)
def run(exercise, command): """ Spawns a process with `command path-of-exercise` """ Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL)
def select(course=False, tid=None, auto=False): """ Select a course or an exercise. """ if course: update(course=True) course = None try: course = Course.get_selected() except NoCourseSelected: pass ret = {} if not tid: ret = Menu.launch("Select a course", Course.select().execute(), course) else: ret["item"] = Course.get(Course.tid == tid) if "item" in ret: ret["item"].set_select() update() if ret["item"].path == "": select_a_path(auto=auto) # Selects the first exercise in this course skip() return else: print("You can select the course with `tmc select --course`") return else: selected = None try: selected = Exercise.get_selected() except NoExerciseSelected: pass ret = {} if not tid: ret = Menu.launch("Select an exercise", Course.get_selected().exercises, selected) else: ret["item"] = Exercise.byid(tid) if "item" in ret: ret["item"].set_select() print("Selected {}".format(ret["item"]))
def submit(course, tid=None, pastebin=False, review=False): """ Submit the selected exercise to the server. """ if tid is not None: return submit_exercise(Exercise.byid(tid), pastebin=pastebin, request_review=review) else: sel = Exercise.get_selected() if not sel: raise NoExerciseSelected() return submit_exercise(sel, pastebin=pastebin, request_review=review)
def paste(tid=None, review=False): """ Sends the selected exercise to the TMC pastebin. """ submit(pastebin=True, tid=tid, review=False)
def list_all(course, single=None): """ Lists all of the exercises in the current course. """ def bs(val): return "●" if val else " " def bc(val): return as_success("✔") if val else as_error("✘") def format_line(exercise): return "{0} │ {1} │ {2} │ {3} │ {4}".format(exercise.tid, bs(exercise.is_selected), bc(exercise.is_downloaded), bc(exercise.is_completed), exercise.menuname()) print("ID{0}│ S │ D │ C │ Name".format( (len(str(course.exercises[0].tid)) - 1) * " " )) if single: print(format_line(single)) return for exercise in course.exercises: # ToDo: use a pager print(format_line(exercise))
def update(course=False): """ Update the data of courses and or exercises from server. """ if course: with Spinner.context(msg="Updated course metadata.", waitmsg="Updating course metadata."): for course in api.get_courses(): old = None try: old = Course.get(Course.tid == course["id"]) except peewee.DoesNotExist: old = None if old: old.details_url = course["details_url"] old.save() continue Course.create(tid=course["id"], name=course["name"], details_url=course["details_url"]) else: selected = Course.get_selected() # with Spinner.context(msg="Updated exercise metadata.", # waitmsg="Updating exercise metadata."): print("Updating exercise data.") for exercise in api.get_exercises(selected): old = None try: old = Exercise.byid(exercise["id"]) except peewee.DoesNotExist: old = None if old is not None: old.name = exercise["name"] old.course = selected.id old.is_attempted = exercise["attempted"] old.is_completed = exercise["completed"] old.deadline = exercise.get("deadline") old.is_downloaded = os.path.isdir(old.path()) old.return_url = exercise["return_url"] old.zip_url = exercise["zip_url"] old.submissions_url = exercise["exercise_submissions_url"] old.save() download_exercise(old, update=True) else: ex = Exercise.create(tid=exercise["id"], name=exercise["name"], course=selected.id, is_attempted=exercise["attempted"], is_completed=exercise["completed"], deadline=exercise.get("deadline"), return_url=exercise["return_url"], zip_url=exercise["zip_url"], submissions_url=exercise[("exercise_" "submissions_" "url")]) ex.is_downloaded = os.path.isdir(ex.path()) ex.save()
def determine_type(x): """Determine the type of x""" types = (int, float, str) _type = filter(lambda a: is_type(a, x), types)[0] return _type(x)
def dmap(fn, record): """map for a directory""" values = (fn(v) for k, v in record.items()) return dict(itertools.izip(record, values))
def apply_types(use_types, guess_type, line): """Apply the types on the elements of the line""" new_line = {} for k, v in line.items(): if use_types.has_key(k): new_line[k] = force_type(use_types[k], v) elif guess_type: new_line[k] = determine_type(v) else: new_line[k] = v return new_line
def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}): """Read a CSV file Usage ----- >>> data = read_csv(filename, delimiter=delimiter, skip=skip, guess_type=guess_type, has_header=True, use_types={}) # Use specific types >>> types = {"sepal.length": int, "petal.width": float} >>> data = read_csv(filename, guess_type=guess_type, use_types=types) keywords :has_header: Determine whether the file has a header or not """ with open(filename, 'r') as f: # Skip the n first lines if has_header: header = f.readline().strip().split(delimiter) else: header = None for i in range(skip): f.readline() for line in csv.DictReader(f, delimiter=delimiter, fieldnames=header): if use_types: yield apply_types(use_types, guess_type, line) elif guess_type: yield dmap(determine_type, line) else: yield line
def write_csv(filename, header, data=None, rows=None, mode="w"): """Write the data to the specified filename Usage ----- >>> write_csv(filename, header, data, mode=mode) Parameters ---------- filename : str The name of the file header : list of strings The names of the columns (or fields): (fieldname1, fieldname2, ...) data : list of dictionaries (optional) [ {fieldname1: a1, fieldname2: a2}, {fieldname1: b1, fieldname2: b2}, ... ] rows : list of lists (optional) [ (a1, a2), (b1, b2), ... ] mode : str (optional) "w": write the data to the file by overwriting it "a": write the data to the file by appending them Returns ------- None. A CSV file is written. """ if data == rows == None: msg = "You must specify either data or rows" raise ValueError(msg) elif data != None and rows != None: msg = "You must specify either data or rows. Not both" raise ValueError(msg) data_header = dict((x, x) for x in header) with open(filename, mode) as f: if data: writer = csv.DictWriter(f, fieldnames=header) if mode == "w": writer.writerow(data_header) writer.writerows(data) elif rows: writer = csv.writer(f) if mode == "w": writer.writerow(header) writer.writerows(rows) print "Saved %s." % filename
def format_to_csv(filename, skiprows=0, delimiter=""): """Convert a file to a .csv file""" if not delimiter: delimiter = "\t" input_file = open(filename, "r") if skiprows: [input_file.readline() for _ in range(skiprows)] new_filename = os.path.splitext(filename)[0] + ".csv" output_file = open(new_filename, "w") header = input_file.readline().split() reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter) writer = csv.DictWriter(output_file, fieldnames=header, delimiter=",") # Write header writer.writerow(dict((x, x) for x in header)) # Write rows for line in reader: if None in line: del line[None] writer.writerow(line) input_file.close() output_file.close() print "Saved %s." % new_filename
def savefig(filename, path="figs", fig=None, ext='eps', verbose=False, **kwargs): """ Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*. *\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`. """ filename = os.path.join(path, filename) final_filename = '{}.{}'.format(filename, ext).replace(" ", "").replace("\n", "") final_filename = os.path.abspath(final_filename) final_path = os.path.dirname(final_filename) if not os.path.exists(final_path): os.makedirs(final_path) if verbose: print('Saving file: {}'.format(final_filename)) if fig is not None: fig.savefig(final_filename, bbox_inches='tight', **kwargs) else: plt.savefig(final_filename, bbox_inches='tight', **kwargs)
def admin_obj_link(obj, display=''): """Returns a link to the django admin change list with a filter set to only the object given. :param obj: Object to create the admin change list display link for :param display: Text to display in the link. Defaults to string call of the object :returns: Text containing HTML for a link """ # get the url for the change list for this object url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label, obj._meta.model_name)) url += '?id__exact=%s' % obj.id text = str(obj) if display: text = display return format_html('<a href="{}">{}</a>', url, text)
def admin_obj_attr(obj, attr): """A safe version of :func:``utils.get_obj_attr`` that returns and empty string in the case of an exception or an empty object """ try: field_obj = get_obj_attr(obj, attr) if not field_obj: return '' except AttributeError: return '' return field_obj
def _obj_display(obj, display=''): """Returns string representation of an object, either the default or based on the display template passed in. """ result = '' if not display: result = str(obj) else: template = Template(display) context = Context({'obj':obj}) result = template.render(context) return result
def make_admin_obj_mixin(name): """This method dynamically creates a mixin to be used with your :class:`ModelAdmin` classes. The mixin provides utility methods that can be referenced in side of the admin object's ``list_display`` and other similar attributes. :param name: Each usage of the mixin must be given a unique name for the mixin class being created :returns: Dynamically created mixin class The created class supports the following methods: .. code-block:: python add_obj_ref(funcname, attr, [title, display]) Django admin ``list_display`` does not support the double underscore semantics of object references. This method adds a function to the mixin that returns the ``str(obj)`` value from object relations. :param funcname: Name of the function to be added to the mixin. In the admin class object that includes the mixin, this name is used in the ``list_display`` tuple. :param attr: Name of the attribute to dereference from the corresponding object, i.e. what will be dereferenced. This name supports double underscore object link referencing for ``models.ForeignKey`` members. :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``attr`` :param display: What to display as the text in the column. If not given it defaults to the string representation of the object for the row: ``str(obj)`` . This parameter supports django templating, the context for which contains a dictionary key named "obj" with the value being the object for the row. .. code-block:: python add_obj_link(funcname, attr, [title, display]) This method adds a function to the mixin that returns a link to a django admin change list page for the member attribute of the object being displayed. :param funcname: Name of the function to be added to the mixin. In the admin class object that includes the mixin, this name is used in the ``list_display`` tuple. :param attr: Name of the attribute to dereference from the corresponding object, i.e. what will be lined to. This name supports double underscore object link referencing for ``models.ForeignKey`` members. :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``attr`` :param display: What to display as the text for the link being shown. If not given it defaults to the string representation of the object for the row: ``str(obj)`` . This parameter supports django templating, the context for which contains a dictionary key named "obj" with the value being the object for the row. Example usage: .. code-block:: python # ---- models.py file ---- class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) .. code-block:: python # ---- admin.py file ---- @admin.register(Author) class Author(admin.ModelAdmin): list_display = ('name', ) mixin = make_admin_obj_mixin('BookMixin') mixin.add_obj_link('show_author', 'Author', 'Our Authors', '{{obj.name}} (id={{obj.id}})') @admin.register(Book) class BookAdmin(admin.ModelAdmin, mixin): list_display = ('name', 'show_author') A sample django admin page for "Book" would have the table: +---------------------------------+------------------------+ | Name | Our Authors | +=================================+========================+ | Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* | +---------------------------------+------------------------+ | War and Peace | *Tolstoy (id=2)* | +---------------------------------+------------------------+ | Dirk Gently | *Douglas Adams (id=1)* | +---------------------------------+------------------------+ Each of the *items* in the "Our Authors" column would be a link to the django admin change list for the "Author" object with a filter set to show just the object that was clicked. For example, if you clicked "Douglas Adams (id=1)" you would be taken to the Author change list page filtered just for Douglas Adams books. The ``add_obj_ref`` method is similar to the above, but instead of showing links, it just shows text and so can be used for view-only attributes of dereferenced objects. """ @classmethod def add_obj_link(cls, funcname, attr, title='', display=''): if not title: title = attr.capitalize() # python scoping is a bit weird with default values, if it isn't # referenced the inner function won't see it, so assign it for use _display = display def _link(self, obj): field_obj = admin_obj_attr(obj, attr) if not field_obj: return '' text = _obj_display(field_obj, _display) return admin_obj_link(field_obj, text) _link.short_description = title _link.allow_tags = True _link.admin_order_field = attr setattr(cls, funcname, _link) @classmethod def add_obj_ref(cls, funcname, attr, title='', display=''): if not title: title = attr.capitalize() # python scoping is a bit weird with default values, if it isn't # referenced the inner function won't see it, so assign it for use _display = display def _ref(self, obj): field_obj = admin_obj_attr(obj, attr) if not field_obj: return '' return _obj_display(field_obj, _display) _ref.short_description = title _ref.allow_tags = True _ref.admin_order_field = attr setattr(cls, funcname, _ref) klass = type(name, (), {}) klass.add_obj_link = add_obj_link klass.add_obj_ref = add_obj_ref return klass
def fancy_modeladmin(*args): """Returns a new copy of a :class:`FancyModelAdmin` class (a class, not an instance!). This can then be inherited from when declaring a model admin class. The :class:`FancyModelAdmin` class has additional methods for managing the ``list_display`` attribute. :param ``*args``: [optional] any arguments given will be added to the ``list_display`` property using regular django ``list_display`` functionality. This function is meant as a replacement for :func:`make_admin_obj_mixin`, it does everything the old one does with fewer bookkeeping needs for the user as well as adding functionality. Example usage: .. code-block:: python # ---- models.py file ---- class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) .. code-block:: python # ---- admin.py file ---- @admin.register(Author) class Author(admin.ModelAdmin): list_display = ('name', ) base = fany_list_display_modeladmin() base.add_displays('id', 'name') base.add_obj_link('author', 'Our Authors', '{{obj.name}} (id={{obj.id}})') @admin.register(Book) class BookAdmin(base): list_display = ('name', 'show_author') A sample django admin page for "Book" would have the table: +----+---------------------------------+------------------------+ | ID | Name | Our Authors | +====+=================================+========================+ | 1 | Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* | +----+---------------------------------+------------------------+ | 2 | War and Peace | *Tolstoy (id=2)* | +----+---------------------------------+------------------------+ | 3 | Dirk Gently | *Douglas Adams (id=1)* | +----+---------------------------------+------------------------+ See :class:`FancyModelAdmin` for a full list of functionality provided by the returned base class. """ global klass_count klass_count += 1 name = 'DynamicAdminClass%d' % klass_count # clone the admin class klass = type(name, (FancyModelAdmin,), {}) klass.list_display = [] if len(args) > 0: klass.add_displays(*args) return klass
def add_display(cls, attr, title=''): """Adds a ``list_display`` property without any extra wrappers, similar to :func:`add_displays`, but can also change the title. :param attr: Name of the attribute to add to the display :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``attr`` """ global klass_count klass_count += 1 fn_name = 'dyn_fn_%d' % klass_count cls.list_display.append(fn_name) if not title: title = attr.capitalize() def _ref(self, obj): # use the django mechanism for field value lookup _, _, value = lookup_field(attr, obj, cls) return value _ref.short_description = title _ref.allow_tags = True _ref.admin_order_field = attr setattr(cls, fn_name, _ref)
def add_link(cls, attr, title='', display=''): """Adds a ``list_display`` attribute that appears as a link to the django admin change page for the type of object being shown. Supports double underscore attribute name dereferencing. :param attr: Name of the attribute to dereference from the corresponding object, i.e. what will be lined to. This name supports double underscore object link referencing for ``models.ForeignKey`` members. :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``attr`` :param display: What to display as the text for the link being shown. If not given it defaults to the string representation of the object for the row: ``str(obj)`` . This parameter supports django templating, the context for which contains a dictionary key named "obj" with the value being the object for the row. Example usage: .. code-block:: python # ---- admin.py file ---- base = fancy_modeladmin('id') base.add_link('author', 'Our Authors', '{{obj.name}} (id={{obj.id}})') @admin.register(Book) class BookAdmin(base): pass The django admin change page for the Book class would have a column for "id" and another titled "Our Authors". The "Our Authors" column would have a link for each Author object referenced by "book.author". The link would go to the Author django admin change listing. The display of the link would be the name of the author with the id in brakcets, e.g. "Douglas Adams (id=42)" """ global klass_count klass_count += 1 fn_name = 'dyn_fn_%d' % klass_count cls.list_display.append(fn_name) if not title: title = attr.capitalize() # python scoping is a bit weird with default values, if it isn't # referenced the inner function won't see it, so assign it for use _display = display def _link(self, obj): field_obj = admin_obj_attr(obj, attr) if not field_obj: return '' text = _obj_display(field_obj, _display) return admin_obj_link(field_obj, text) _link.short_description = title _link.allow_tags = True _link.admin_order_field = attr setattr(cls, fn_name, _link)
def add_object(cls, attr, title='', display=''): """Adds a ``list_display`` attribute showing an object. Supports double underscore attribute name dereferencing. :param attr: Name of the attribute to dereference from the corresponding object, i.e. what will be lined to. This name supports double underscore object link referencing for ``models.ForeignKey`` members. :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``attr`` :param display: What to display as the text for the link being shown. If not given it defaults to the string representation of the object for the row: ``str(obj)``. This parameter supports django templating, the context for which contains a dictionary key named "obj" with the value being the object for the row. """ global klass_count klass_count += 1 fn_name = 'dyn_fn_%d' % klass_count cls.list_display.append(fn_name) if not title: title = attr.capitalize() # python scoping is a bit weird with default values, if it isn't # referenced the inner function won't see it, so assign it for use _display = display def _ref(self, obj): field_obj = admin_obj_attr(obj, attr) if not field_obj: return '' return _obj_display(field_obj, _display) _ref.short_description = title _ref.allow_tags = True _ref.admin_order_field = attr setattr(cls, fn_name, _ref)
def add_formatted_field(cls, field, format_string, title=''): """Adds a ``list_display`` attribute showing a field in the object using a python %formatted string. :param field: Name of the field in the object. :param format_string: A old-style (to remain python 2.x compatible) % string formatter with a single variable reference. The named ``field`` attribute will be passed to the formatter using the "%" operator. :param title: Title for the column of the django admin table. If not given it defaults to a capitalized version of ``field`` """ global klass_count klass_count += 1 fn_name = 'dyn_fn_%d' % klass_count cls.list_display.append(fn_name) if not title: title = field.capitalize() # python scoping is a bit weird with default values, if it isn't # referenced the inner function won't see it, so assign it for use _format_string = format_string def _ref(self, obj): return _format_string % getattr(obj, field) _ref.short_description = title _ref.allow_tags = True _ref.admin_order_field = field setattr(cls, fn_name, _ref)
def post_required(method_or_options=[]): """View decorator that enforces that the method was called using POST. This decorator can be called with or without parameters. As it is expected to wrap a view, the first argument of the method being wrapped is expected to be a ``request`` object. .. code-block:: python @post_required def some_view(request): pass @post_required(['firstname', 'lastname']) def some_view(request): pass The optional parameter contains a single list which specifies the names of the expected fields in the POST dictionary. The list is not exclusive, you can pass in fields that are not checked by the decorator. :param options: List of the names of expected POST keys. """ def decorator(method): # handle wrapping or wrapping with arguments; if no arguments (and no # calling parenthesis) then method_or_options will be a list, # otherwise it will be the wrapped function expected_fields = [] if not callable(method_or_options): # not callable means wrapping with arguments expected_fields = method_or_options @wraps(method) def wrapper(*args, **kwargs): request = args[0] if request.method != 'POST': logger.error('POST required for this url') raise Http404('only POST allowed for this url') missing = [] for field in expected_fields: if field not in request.POST: missing.append(field) if missing: s = 'Expected fields missing in POST: %s' % missing logger.error(s) raise Http404(s) # everything verified, run the view return method(*args, **kwargs) return wrapper if callable(method_or_options): # callable means decorated method without options, call our decorator return decorator(method_or_options) return decorator
def json_post_required(*decorator_args): """View decorator that enforces that the method was called using POST and contains a field containing a JSON dictionary. This method should only be used to wrap views and assumes the first argument of the method being wrapped is a ``request`` object. .. code-block:: python @json_post_required('data', 'json_data') def some_view(request): username = request.json_data['username'] :param field: The name of the POST field that contains a JSON dictionary :param request_name: [optional] Name of the parameter on the request to put the deserialized JSON data. If not given the field name is used """ def decorator(method): @wraps(method) def wrapper(*args, **kwargs): field = decorator_args[0] if len(decorator_args) == 2: request_name = decorator_args[1] else: request_name = field request = args[0] if request.method != 'POST': logger.error('POST required for this url') raise Http404('only POST allowed for this url') if field not in request.POST: s = 'Expected field named %s in POST' % field logger.error(s) raise Http404(s) # deserialize the JSON and put it in the request setattr(request, request_name, json.loads(request.POST[field])) # everything verified, run the view return method(*args, **kwargs) return wrapper return decorator
def hist(x, bins=10, labels=None, aspect="auto", plot=True, ax=None, range=None): """ Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`. """ h, edge = _np.histogram(x, bins=bins, range=range) mids = edge + (edge[1]-edge[0])/2 mids = mids[:-1] if plot: if ax is None: _plt.hist(x, bins=bins, range=range) else: ax.hist(x, bins=bins, range=range) if labels is not None: _addlabel(labels[0], labels[1], labels[2]) return h, mids
def sigma(self): """ Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}` """ return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit)
def sigma_prime(self): """ Divergence of matched beam """ return _np.sqrt(self.emit/self.beta(self.E))
def n_p(self): """ The plasma density in SI units. """ return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2
def plasma(self, species=_pt.hydrogen): """ The matched :class:`Plasma`. """ return _Plasma(self.n_p, species=species)
def main(target, label): """ Semver tag triggered deployment helper """ check_environment(target, label) click.secho('Fetching tags from the upstream ...') handler = TagHandler(git.list_tags()) print_information(handler, label) tag = handler.yield_tag(target, label) confirm(tag)
def check_environment(target, label): """ Performs some environment checks prior to the program's execution """ if not git.exists(): click.secho('You must have git installed to use yld.', fg='red') sys.exit(1) if not os.path.isdir('.git'): click.secho('You must cd into a git repository to use yld.', fg='red') sys.exit(1) if not git.is_committed(): click.secho('You must commit or stash your work before proceeding.', fg='red') sys.exit(1) if target is None and label is None: click.secho('You must specify either a target or a label.', fg='red') sys.exit(1)
def print_information(handler, label): """ Prints latest tag's information """ click.echo('=> Latest stable: {tag}'.format( tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if handler.latest_stable else 'magenta') )) if label is not None: latest_revision = handler.latest_revision(label) click.echo('=> Latest relative revision ({label}): {tag}'.format( label=click.style(label, fg='blue'), tag=click.style(str(latest_revision or 'N/A'), fg='yellow' if latest_revision else 'magenta') ))
def confirm(tag): """ Prompts user before proceeding """ click.echo() if click.confirm('Do you want to create the tag {tag}?'.format( tag=click.style(str(tag), fg='yellow')), default=True, abort=True): git.create_tag(tag) if click.confirm( 'Do you want to push the tag {tag} into the upstream?'.format( tag=click.style(str(tag), fg='yellow')), default=True): git.push_tag(tag) click.echo('Done!') else: git.delete_tag(tag) click.echo('Aborted!')
def imshow(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs): """ Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner. Optional argument *ax* allows an existing axes to be used. *\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.imshow`. .. versionadded:: 1.3 Returns ------- fig, ax, im : if axes aren't specified. im : if axes are specified. """ return _plot_array(X, plottype=_IMSHOW, ax=ax, add_cbar=add_cbar, rescale_fig=rescale_fig, **kwargs)
def scaled_figsize(X, figsize=None, h_pad=None, v_pad=None): """ Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`. .. versionadded:: 1.3 """ if figsize is None: figsize = _mpl.rcParams['figure.figsize'] # ====================================== # Find the height and width # ====================================== width, height = _np.shape(X) ratio = width / height # ====================================== # Find how to rescale the figure # ====================================== if ratio > figsize[0]/figsize[1]: figsize[1] = figsize[0] / ratio else: figsize[0] = figsize[1] * ratio return figsize
def get(f, key, default=None): """ Gets an array from datasets. .. versionadded:: 1.4 """ if key in f.keys(): val = f[key].value if default is None: return val else: if _np.shape(val) == _np.shape(default): return val return default
def get_state(self): """Get the current directory state""" return [os.path.join(dp, f) for dp, _, fn in os.walk(self.dir) for f in fn]
def tick(self): """Add one tick to progress bar""" self.current += 1 if self.current == self.factor: sys.stdout.write('+') sys.stdout.flush() self.current = 0
def push(self, k): """Push k to the top of the list >>> l = DLL() >>> l.push(1) >>> l [1] >>> l.push(2) >>> l [2, 1] >>> l.push(3) >>> l [3, 2, 1] """ if not self._first: # first item self._first = self._last = node = DLL.Node(k) elif self._first.value == k: # it's already at the top return else: try: self.delete(k) # in case we have it already except KeyError: pass self._first = node = self._first.insert_before(k) self._index[k] = node self._size += 1
def deletenode(self, node): """ >>> l = DLL() >>> l.push(1) >>> l [1] >>> l.size() 1 >>> l.deletenode(l._first) >>> l [] >>> l.size() 0 >>> l._index {} >>> l._first """ if self._last == node: self._last = node.previous if self._first == node: self._first = node.next node.pop() del self._index[node.value] self._size -= 1
def pop(self): """ >>> l = DLL() >>> l.push(1) >>> l.pop() 1 """ k = self._last.value self.deletenode(self._last) return k
def increment(cls, name): """Call this method to increment the named counter. This is atomic on the database. :param name: Name for a previously created ``Counter`` object """ with transaction.atomic(): counter = Counter.objects.select_for_update().get(name=name) counter.value += 1 counter.save() return counter.value
def pcolor_axes(array, px_to_units=px_to_units): """ Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`. *px_to_units* is a function to convert pixels to units. By default, returns pixels. """ # ====================================== # Coords need to be +1 larger than array # ====================================== x_size = array.shape[0]+1 y_size = array.shape[1]+1 x = _np.empty((x_size, y_size)) y = _np.empty((x_size, y_size)) for i in range(x_size): for j in range(y_size): x[i, j], y[i, j] = px_to_units(i-0.5, j-0.5) return x, y
def nb0(self): """ On-axis beam density :math:`n_{b,0}`. """ return self.N_e / ( (2*_np.pi)**(3/2) * self.sig_r**2 * self.sig_xi)
def lambda_large(self, r0): """ The wavelength for large (:math:`r_0 < \\sigma_r`) oscillations. """ return 2*_np.sqrt(2*_np.pi/self.k)*r0
def r_small(self, x, r0): """ Approximate trajectory function for small (:math:`r_0 < \\sigma_r`) oscillations. """ return r0*_np.cos(_np.sqrt(self.k_small) * x)
def r_large(self, x, r0): """ Approximate trajectory function for large (:math:`r_0 > \\sigma_r`) oscillations. """ return r0*_np.cos(x*self.omega_big(r0))
def k(self): """ Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)` """ try: return self._k except AttributeError: self._k = e**2 * self.N_e / ( (2*_np.pi)**(5/2) * e0 * self.m * c**2 * self.sig_xi) return self._k
def print_loading(self, wait, message): """ print loading message on screen .. note:: loading message only write to `sys.stdout` :param int wait: seconds to wait :param str message: message to print :return: None """ tags = ['\\', '|', '/', '-'] for i in range(wait): time.sleep(0.25) sys.stdout.write("%(message)s... %(tag)s\r" % { 'message': message, 'tag': tags[i % 4] }) sys.stdout.flush() pass sys.stdout.write("%s... Done...\n" % message) sys.stdout.flush() pass
def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."): """ print warn type message, if file handle is `sys.stdout`, print color message :param str message: message to print :param file fh: file handle,default is `sys.stdout` :param str prefix: message prefix,default is `[warn]` :param str suffix: message suffix ,default is `...` :return: None """ msg = prefix + message + suffix fh = fh or sys.stdout if fh is sys.stdout: termcolor.cprint(msg, color="yellow") else: fh.write(msg) pass
def error_message(self, message, fh=None, prefix="[error]:", suffix="..."): """ print error type message if file handle is `sys.stderr`, print color message :param str message: message to print :param file fh: file handle, default is `sys.stdout` :param str prefix: message prefix,default is `[error]` :param str suffix: message suffix ,default is '...' :return: None """ msg = prefix + message + suffix fh = fh or sys.stderr if fh is sys.stderr: termcolor.cprint(msg, color="red") else: fh.write(msg) pass
def system(self, cmd, fake_code=False): """ a built-in wrapper make dry-run easier. you should use this instead use `os.system` .. note:: to use it,you need add '--dry-run' option in your argparser options :param str cmd: command to execute :param bool fake_code: only display command when is True,default is False :return: """ try: if self.options.dry_run: def fake_system(cmd): self.print_message(cmd) return fake_code return fake_system(cmd) except AttributeError: self.logger.warnning("fake mode enabled," "but you don't set '--dry-run' option " "in your argparser options") pass return os.system(cmd)
def load_resource(path, root=''): """ .. warning:: Experiment feature. BE CAREFUL! WE MAY REMOVE THIS FEATURE! load resource file which in package. this method is used to load file easier in different environment. e.g: consume we have a file named `resource.io` in package `cliez.conf`, and we want to load it. the easiest way may like this: .. code-block:: python open('../conf/resource.io').read() An obvious problem is `..` is relative path. it will cause an error. `load_resource` is designed for solve this problem. The following code are equivalent: .. code-block:: python a = Component() a.load_resource('resource.io', root='cliez/base') a.load_resource('base/resource.io', root='cliez') a.load_resource('/base/resource.io', root='cliez') a.load_resource('cliez/base/resource.io') a.load_resource(__file__.rsplit('/', 2)[0] + '/cliez/base/resource.io') .. note:: The document charset *MUST BE* utf-8 :param str path: file path :param str root: root path :return: str """ if root: full_path = root + '/' + path.strip('/') else: full_path = path buf = '' try: buf = open(full_path).read() except IOError: pkg, path = full_path.split('/', 1) try: import pkg_resources buf = pkg_resources.resource_string(pkg, path) # compatible python3 and only support utf-8 if type(buf) != str: buf = buf.decode('utf-8') pass except AttributeError: # load resource feature not work in python2 pass return buf
def load_description(name, root=''): """ .. warning:: Experiment feature. BE CAREFUL! WE MAY REMOVE THIS FEATURE! Load resource file as description, if resource file not exist,will return empty string. :param str path: name resource path :param str root: same as `load_resource` root :return: `str` """ desc = '' try: desc = Component.load_resource(name, root=root) except (IOError, ImportError): pass return desc
def name(self): ''' Returns the name of the Firebase. If a Firebase instance points to 'https://my_firebase.firebaseio.com/users' its name would be 'users' ''' i = self.__url.rfind('/') if self.__url[:i] == 'https:/': return "/" return self.__url[i+1:]
def url_correct(self, point, auth=None, export=None): ''' Returns a Corrected URL to be used for a Request as per the REST API. ''' newUrl = self.__url + point + '.json' if auth or export: newUrl += "?" if auth: newUrl += ("auth=" + auth) if export: if not newUrl.endswith('?'): newUrl += "&" newUrl += "format=export" return newUrl
def __read(path): ''' Reads a File with contents in correct JSON format. Returns the data as Python objects. path - (string) path to the file ''' try: with open(path, 'r') as data_file: data = data_file.read() data = json.loads(data) return data except IOError as err: pass except Exception as err: # Invalid JSON formatted files pass
def __write(path, data, mode="w"): ''' Writes to a File. Returns the data written. path - (string) path to the file to write to. data - (json) data from a request. mode - (string) mode to open the file in. Default to 'w'. Overwrites. ''' with open(path, mode) as data_file: data = json.dumps(data, indent=4) data_file.write(data) return data
def amust(self, args, argv): ''' Requires the User to provide a certain parameter for the method to function properly. Else, an Exception is raised. args - (tuple) arguments you are looking for. argv - (dict) arguments you have received and want to inspect. ''' for arg in args: if str(arg) not in argv: raise KeyError("ArgMissing: " + str(arg) + " not passed")
def catch_error(response): ''' Checks for Errors in a Response. 401 or 403 - Security Rules Violation. 404 or 417 - Firebase NOT Found. response - (Request.Response) - response from a request. ''' status = response.status_code if status == 401 or status == 403: raise EnvironmentError("Forbidden") elif status == 417 or status == 404: raise EnvironmentError("NotFound")
def get_sync(self, **kwargs): ''' GET: gets data from the Firebase. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point",), kwargs) response = requests.get(self.url_correct(kwargs["point"], kwargs.get("auth", self.__auth))) self.catch_error(response) return response.content
def put_sync(self, **kwargs): ''' PUT: puts data into the Firebase. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point", "data"), kwargs) response = requests.put(self.url_correct(kwargs["point"], kwargs.get("auth", self.__auth)), data=json.dumps(kwargs["data"])) self.catch_error(response) return response.content
def post_sync(self, **kwargs): ''' POST: post data to a Firebase. Requires the 'point' parameter as a keyworded argument. Note: Firebase will give it a randomized "key" and the data will be the "value". Thus a key-value pair ''' self.amust(("point", "data"), kwargs) response = requests.post(self.url_correct( kwargs["point"], kwargs.get("auth", self.__auth)), data=json.dumps(kwargs["data"])) self.catch_error(response) return response.content
def update_sync(self, **kwargs): ''' UPDATE: updates data in the Firebase. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point", "data"), kwargs) # Sending the 'PATCH' request response = requests.patch(self.url_correct( kwargs["point"], kwargs.get("auth", self.__auth)), data=json.dumps(kwargs["data"])) self.catch_error(response) return response.content
def delete_sync(self, **kwargs): ''' DELETE: delete data in the Firebase. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point",), kwargs) response = requests.delete(self.url_correct( kwargs["point"], kwargs.get("auth", self.__auth))) self.catch_error(response) return response.content
def export_sync(self, **kwargs): ''' EXPORT: exports data from the Firebase into a File, if given. Requires the 'point' parameter as a keyworded argument. ''' self.amust(("point",), kwargs) response = requests.get(self.url_correct(kwargs["point"], kwargs.get("auth", self.__auth), True)) self.catch_error(response) path = kwargs.get("path", None) if path: self.__write(path, response.content, kwargs.get("mode", "w")) return response.content
def superable(cls) : '''Provide .__super in python 2.x classes without having to specify the current class name each time super is used (DRY principle).''' name = cls.__name__ super_name = '_%s__super' % (name,) setattr(cls,super_name,super(cls)) return cls
def main(): """ Main method. This method holds what you want to execute when the script is run on command line. """ args = get_arguments() setup_logging(args) version_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '.VERSION' )) try: version_text = open(version_path).read().strip() except Exception: print('Could not open or read the .VERSION file') sys.exit(1) try: semver.parse(version_text) except ValueError: print(('The .VERSION file contains an invalid ' 'version: "{}"').format(version_text)) sys.exit(1) new_version = version_text if args.version: try: if semver.parse(args.version): new_version = args.version except Exception: print('Could not parse "{}" as a version'.format(args.version)) sys.exit(1) elif args.bump_major: new_version = semver.bump_major(version_text) elif args.bump_minor: new_version = semver.bump_minor(version_text) elif args.bump_patch: new_version = semver.bump_patch(version_text) try: with open(version_path, 'w') as version_file: version_file.write(new_version) except Exception: print('Could not write the .VERSION file') sys.exit(1) print(new_version)
def valid_url(name): ''' Validates a Firebase URL. A valid URL must exhibit: - Protocol must be HTTPS - Domain Must be firebaseio.com - firebasename can only contain: - hyphen, small and capital letters - firebasename can not have leading and trailing hyphens - childnames can not contain: - period, dollar sign, square brackets, pound - ASCII Control Chars from \x00 - \x1F and \x7F ''' try: pattern = r'^https://([a-zA-Z0-9][a-zA-Z0-9\-]+[a-zA-Z0-9]).firebaseio.com(/[^\#\$\[\]\.\x00-\x1F\x7F]*)' result = re.search(pattern, name + '/').group() result = result[:len(result) - 1] if result == name: return name else: raise ValueError("InvalidURL") except: raise ValueError("InvalidURL")
def pickle(obj, filepath): """Pickle and compress.""" arr = pkl.dumps(obj, -1) with open(filepath, 'wb') as f: s = 0 while s < len(arr): e = min(s + blosc.MAX_BUFFERSIZE, len(arr)) carr = blosc.compress(arr[s:e], typesize=8) f.write(carr) s = e
def unpickle(filepath): """Decompress and unpickle.""" arr = [] with open(filepath, 'rb') as f: carr = f.read(blosc.MAX_BUFFERSIZE) while len(carr) > 0: arr.append(blosc.decompress(carr)) carr = f.read(blosc.MAX_BUFFERSIZE) return pkl.loads(b"".join(arr))
def contact(request): """Displays the contact form and sends the email""" form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = settings.CONTACTFORM_RECIPIENTS if cc_myself: recipients.append(sender) send_mail(getattr(settings, "CONTACTFORM_SUBJECT_PREFIX", '') + subject, message, sender, recipients) return render(request, 'contactform/thanks.html') return render( request, 'contactform/contact.html', {'form': form})
def load_gitconfig(self): """ try use gitconfig info. author,email etc. """ gitconfig_path = os.path.expanduser('~/.gitconfig') if os.path.exists(gitconfig_path): parser = Parser() parser.read(gitconfig_path) parser.sections() return parser pass
def render(self, match_string, new_string): """ render template string to user string :param str match_string: template string,syntax: '___VAR___' :param str new_string: user string :return: """ current_dir = self.options.dir # safe check,we don't allow handle system root and user root. if os.path.expanduser(current_dir) in ['/', os.path.expanduser("~")]: self.error("invalid directory", -1) pass def match_directory(path): """ exclude indeed directory. .. note:: this function will ignore in all depth. :param path: :return: """ skip = False for include_dir in ['/%s/' % s for s in self.exclude_directories]: if path.find(include_dir) > -1: skip = True break pass return skip # handle files detail first for v in os.walk(current_dir): # skip exclude directories in depth 1 if os.path.basename(v[0]) in self.exclude_directories: continue if match_directory(v[0]): continue for base_name in v[2]: file_name = os.path.join(v[0], base_name) try: with open(file_name, 'r') as fh: buffer = fh.read() buffer = buffer.replace(match_string, new_string) pass with open(file_name, 'w') as fh: fh.write(buffer) pass except UnicodeDecodeError: # ignore binary files continue pass pass # handle directory redo_directories = [] redo_files = [] for v in os.walk(current_dir): if os.path.basename(v[0]) in self.exclude_directories: continue if match_directory(v[0]): continue for sub_dir in v[1]: if match_string in sub_dir: redo_directories.append(os.path.join(v[0], sub_dir)) pass for f in v[2]: if match_string in f: redo_files.append(os.path.join(v[0], f)) pass pass redo_directories.reverse() redo_files.reverse() # redo files first for v in redo_files: dir_name = os.path.dirname(v) file_name = os.path.basename(v) shutil.move(v, os.path.join( dir_name, file_name.replace(match_string, new_string))) pass for v in redo_directories: shutil.move(v, v.replace(match_string, new_string)) pass pass
def add_arguments(cls): """ Init project. """ return [ (('--yes',), dict(action='store_true', help='clean .git repo')), (('--variable', '-s'), dict(nargs='+', help='set extra variable,format is name:value')), (('--skip-builtin',), dict(action='store_true', help='skip replace builtin variable')), ]
def set_signal(self): """ 设置信号处理 默认直接中断,考虑到一些场景用户需要等待线程结束. 可在此自定义操作 :return: """ def signal_handle(signum, frame): self.error("User interrupt.kill threads.") sys.exit(-1) pass signal.signal(signal.SIGINT, signal_handle) pass
def check_exclusive_mode(self): """ 检查是否是独占模式 参数顺序必须一致,也就是说如果参数顺序不一致,则判定为是两个不同的进程 这么设计是考虑到: - 一般而言,排他模式的服务启动都是crontab等脚本来完成的,不存在顺序变更的可能 - 这在调试的时候可以帮助我们不需要结束原有进程就可以继续调试 :return: """ if self.options.exclusive_mode: import psutil current_pid = os.getpid() current = psutil.Process(current_pid).cmdline() for pid in psutil.pids(): p = psutil.Process(pid) try: if current_pid != pid and current == p.cmdline(): self.error_message( "process exist. pid:{}".format(p.pid)) sys.exit(-1) pass except psutil.ZombieProcess: # 僵尸进程,无视 pass except psutil.AccessDenied: # 不具备用户权限 pass pass pass pass
def run(self, options): """ In general, you don't need to overwrite this method. :param options: :return: """ self.set_signal() self.check_exclusive_mode() slot = self.Handle(self) # start thread i = 0 while i < options.threads: t = threading.Thread(target=self.worker, args=[slot]) # only set daemon when once is False if options.once is True or options.no_daemon is True: t.daemon = False else: t.daemon = True t.start() i += 1 # waiting thread if options.once is False: while True: if threading.active_count() > 1: sleep(1) else: if threading.current_thread().name == "MainThread": sys.exit(0) pass
def serial_ports(): ''' Returns ------- pandas.DataFrame Table of serial ports that match the USB vendor ID and product ID for the `Teensy 3.2`_ board. .. Teensy 3.2: https://www.pjrc.com/store/teensy32.html ''' df_comports = sd.comports() # Match COM ports with USB vendor ID and product IDs for [Teensy 3.2 # device][1]. # # [1]: https://www.pjrc.com/store/teensy32.html df_teensy_comports = df_comports.loc[df_comports.hardware_id.str .contains('VID:PID=16c0:0483', case=False)] return df_teensy_comports
def combine_filenames(filenames, max_length=40): """Return a new filename to use as the combined file name for a bunch of files, based on the SHA of their contents. A precondition is that they all have the same file extension Given that the list of files can have different paths, we aim to use the most common path. Example: /somewhere/else/foo.js /somewhere/bar.js /somewhere/different/too/foobar.js The result will be /somewhere/148713695b4a4b9083e506086f061f9c.js Another thing to note, if the filenames have timestamps in them, combine them all and use the highest timestamp. """ # Get the SHA for each file, then sha all the shas. path = None names = [] extension = None timestamps = [] shas = [] filenames.sort() concat_names = "_".join(filenames) if concat_names in COMBINED_FILENAMES_GENERATED: return COMBINED_FILENAMES_GENERATED[concat_names] for filename in filenames: name = os.path.basename(filename) if not extension: extension = os.path.splitext(name)[1] elif os.path.splitext(name)[1] != extension: raise ValueError("Can't combine multiple file extensions") for base in MEDIA_ROOTS: try: shas.append(md5(os.path.join(base, filename))) break except IOError: pass if path is None: path = os.path.dirname(filename) else: if len(os.path.dirname(filename)) < len(path): path = os.path.dirname(filename) m = hashlib.md5() m.update(",".join(shas)) new_filename = "%s-inkmd" % m.hexdigest() new_filename = new_filename[:max_length] new_filename += extension COMBINED_FILENAMES_GENERATED[concat_names] = new_filename return os.path.join(path, new_filename)
def apply_orientation(im): """ Extract the oritentation EXIF tag from the image, which should be a PIL Image instance, and if there is an orientation tag that would rotate the image, apply that rotation to the Image instance given to do an in-place rotation. :param Image im: Image instance to inspect :return: A possibly transposed image instance """ try: kOrientationEXIFTag = 0x0112 if hasattr(im, '_getexif'): # only present in JPEGs e = im._getexif() # returns None if no EXIF data if e is not None: #log.info('EXIF data found: %r', e) orientation = e[kOrientationEXIFTag] f = orientation_funcs[orientation] return f(im) except: # We'd be here with an invalid orientation value or some random error? pass # log.exception("Error applying EXIF Orientation tag") return im
def write(): """Start a new piece""" click.echo("Fantastic. Let's get started. ") title = click.prompt("What's the title?") # Make sure that title doesn't exist. url = slugify(title) url = click.prompt("What's the URL?", default=url) # Make sure that title doesn't exist. click.echo("Got it. Creating %s..." % url) scaffold_piece(title, url)