Creates the first version of all Calculations that hasn't been yet edited
    See: https://github.com/senaite/senaite.core/pull/1260
180304
def fix_calculation_version_inconsistencies(portal):
    
    logger.info("Fix Calculation version inconsistencies ...")
    brains = api.search({"portal_type": "Calculation"}, "bika_setup_catalog")
    total = len(brains)
    for num, brain in enumerate(brains):
        if num % 100 == 0:
            logger.info("Fix Calculation version inconsistencies: {}/{}"
                        .format(num, total))
        calc = api.get_object(brain)
        version = getattr(calc, "version_id", None)
        if version is None:
            pr = api.get_tool("portal_repository")
            pr.save(obj=calc, comment="First version")
            logger.info("First version created for {}".format(calc.Title()))
    logger.info("Fix Calculation version inconsistencies [DONE]")
944214
def _add_versions(samples):
    
    samples[0]["versions"] = {"tools": programs.write_versions(samples[0]["dirs"], samples[0]["config"]),
                              "data": provenancedata.write_versions(samples[0]["dirs"], samples)}
    return samples
217516
protected function createEditPrepare()
    {
        $this->createEditSnippets = $this->getTrackEngine()->getRoundEditSnippetNames();

        \MUtil_JQuery::enableView($this->view);
        $this->view->headScript()->appendFile($this->basepath->getBasePath()  .  '/gems/js/jquery.showOnChecked.js');

        if (\MUtil_Bootstrap::enabled()) {
            $this->view->headScript()->appendScript("jQuery(document).ready(function($) {
                $('input[name=\"organizations[]\"]').closest('div').showOnChecked( { showInput: $('#org_specific_round-1') });
            });");
        } else {
            $this->view->headScript()->appendScript("jQuery(document).ready(function($) {
                $('input[name=\"organizations[]\"]').closest('tr').showOnChecked( { showInput: $('#org_specific_round-1') });
            });");
        }
    }
1205588
def new_version(self, created_at: dt.datetime, expires_at: dt.datetime=None) -> models.Version:
        """"""
        new_version = self.Version(created_at=created_at, expires_at=expires_at)
        return new_version
90925
def get_complete_version(version=None):
    
    if version is None:
        from graphene import VERSION as version
    else:
        assert len(version) == 5
        assert version[3] in ("alpha", "beta", "rc", "final")

    return version
471617
def notimplemented (func):
    """"""
    def newfunc (*args, **kwargs):
        """Raise NotImplementedError"""
        co = func.func_code
        attrs = (co.co_name, co.co_filename, co.co_firstlineno)
        raise NotImplementedError("function %s at %s:%d is not implemented" % attrs)
    return update_func_meta(newfunc, func)
200267
def version_already_uploaded(project_name, version_str, index_url, requests_verify=True):
    
    all_versions = _get_uploaded_versions(project_name, index_url, requests_verify)
    return version_str in all_versions
294794
def get_complete_version(version=None):
    
    if version is None:
        from promise import VERSION

        return VERSION
    else:
        assert len(version) == 5
        assert version[3] in ("alpha", "beta", "rc", "final")

    return version
857741
def derive(self, new_version: Union[tuple, list]=None) -> "Model":
        
        meta = self.meta
        first_time = self._initial_version == self.version
        if new_version is None:
            new_version = meta["version"]
            new_version[-1] += 1
        if not isinstance(new_version, (tuple, list)):
            raise ValueError("new_version must be either a list or a tuple, got %s"
                             % type(new_version))
        meta["version"] = list(new_version)
        if first_time:
            meta["parent"] = meta["uuid"]
        meta["uuid"] = str(uuid.uuid4())
        return self
608818
def build_update(self,
                     alias=None,
                     assigned_to=None,
                     blocks_add=None,
                     blocks_remove=None,
                     blocks_set=None,
                     depends_on_add=None,
                     depends_on_remove=None,
                     depends_on_set=None,
                     cc_add=None,
                     cc_remove=None,
                     is_cc_accessible=None,
                     comment=None,
                     comment_private=None,
                     component=None,
                     deadline=None,
                     dupe_of=None,
                     estimated_time=None,
                     groups_add=None,
                     groups_remove=None,
                     keywords_add=None,
                     keywords_remove=None,
                     keywords_set=None,
                     op_sys=None,
                     platform=None,
                     priority=None,
                     product=None,
                     qa_contact=None,
                     is_creator_accessible=None,
                     remaining_time=None,
                     reset_assigned_to=None,
                     reset_qa_contact=None,
                     resolution=None,
                     see_also_add=None,
                     see_also_remove=None,
                     severity=None,
                     status=None,
                     summary=None,
                     target_milestone=None,
                     target_release=None,
                     url=None,
                     version=None,
                     whiteboard=None,
                     work_time=None,
                     fixed_in=None,
                     qa_whiteboard=None,
                     devel_whiteboard=None,
                     internal_whiteboard=None,
                     sub_component=None,
                     flags=None,
                     comment_tags=None):
        
        ret = {}

        # These are only supported for rhbugzilla
        for key, val in [
            ("fixed_in", fixed_in),
            ("devel_whiteboard", devel_whiteboard),
            ("qa_whiteboard", qa_whiteboard),
            ("internal_whiteboard", internal_whiteboard),
            ("sub_component", sub_component),
        ]:
            if val is not None:
                raise ValueError("bugzilla instance does not support "
                                 "updating '%s'" % key)

        def s(key, val, convert=None):
            if val is None:
                return
            if convert:
                val = convert(val)
            ret[key] = val

        def add_dict(key, add, remove, _set=None, convert=None):
            if add is remove is _set is None:
                return

            def c(val):
                val = self._listify(val)
                if convert:
                    val = [convert(v) for v in val]
                return val

            newdict = {}
            if add is not None:
                newdict["add"] = c(add)
            if remove is not None:
                newdict["remove"] = c(remove)
            if _set is not None:
                newdict["set"] = c(_set)
            ret[key] = newdict


        s("alias", alias)
        s("assigned_to", assigned_to)
        s("is_cc_accessible", is_cc_accessible, bool)
        s("component", component)
        s("deadline", deadline)
        s("dupe_of", dupe_of, int)
        s("estimated_time", estimated_time, int)
        s("op_sys", op_sys)
        s("platform", platform)
        s("priority", priority)
        s("product", product)
        s("qa_contact", qa_contact)
        s("is_creator_accessible", is_creator_accessible, bool)
        s("remaining_time", remaining_time, float)
        s("reset_assigned_to", reset_assigned_to, bool)
        s("reset_qa_contact", reset_qa_contact, bool)
        s("resolution", resolution)
        s("severity", severity)
        s("status", status)
        s("summary", summary)
        s("target_milestone", target_milestone)
        s("target_release", target_release)
        s("url", url)
        s("version", version)
        s("whiteboard", whiteboard)
        s("work_time", work_time, float)
        s("flags", flags)
        s("comment_tags", comment_tags, self._listify)

        add_dict("blocks", blocks_add, blocks_remove, blocks_set,
                 convert=int)
        add_dict("depends_on", depends_on_add, depends_on_remove,
                 depends_on_set, convert=int)
        add_dict("cc", cc_add, cc_remove)
        add_dict("groups", groups_add, groups_remove)
        add_dict("keywords", keywords_add, keywords_remove, keywords_set)
        add_dict("see_also", see_also_add, see_also_remove)

        if comment is not None:
            ret["comment"] = {"comment": comment}
            if comment_private:
                ret["comment"]["is_private"] = comment_private

        return ret
384174
def new(self, fname=None, editorstack=None, text=None):
        
        # If no text is provided, create default content
        empty = False
        try:
            if text is None:
                default_content = True
                text, enc = encoding.read(self.TEMPLATE_PATH)
                enc_match = re.search(r'-*- coding: ?([a-z0-9A-Z\-]*) -*-',
                                      text)
                if enc_match:
                    enc = enc_match.group(1)
                # Initialize template variables
                # Windows
                username = encoding.to_unicode_from_fs(
                                os.environ.get('USERNAME', ''))
                # Linux, Mac OS X
                if not username:
                    username = encoding.to_unicode_from_fs(
                                   os.environ.get('USER', '-'))
                VARS = {
                    'date': time.ctime(),
                    'username': username,
                }
                try:
                    text = text % VARS
                except Exception:
                    pass
            else:
                default_content = False
                enc = encoding.read(self.TEMPLATE_PATH)[1]
        except (IOError, OSError):
            text = ''
            enc = 'utf-8'
            default_content = True
            empty = True

        create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
        # Creating editor widget
        if editorstack is None:
            current_es = self.get_current_editorstack()
        else:
            current_es = editorstack
        created_from_here = fname is None
        if created_from_here:
            while True:
                fname = create_fname(self.untitled_num)
                self.untitled_num += 1
                if not osp.isfile(fname):
                    break
            basedir = getcwd_or_home()

            if self.main.projects.get_active_project() is not None:
                basedir = self.main.projects.get_active_project_path()
            else:
                c_fname = self.get_current_filename()
                if c_fname is not None and c_fname != self.TEMPFILE_PATH:
                    basedir = osp.dirname(c_fname)
            fname = osp.abspath(osp.join(basedir, fname))
        else:
            # QString when triggered by a Qt signal
            fname = osp.abspath(to_text_string(fname))
            index = current_es.has_filename(fname)
            if index is not None and not current_es.close_file(index):
                return

        # Creating the editor widget in the first editorstack (the one that
        # can't be destroyed), then cloning this editor widget in all other
        # editorstacks:
        finfo = self.editorstacks[0].new(fname, enc, text, default_content,
                                         empty)
        finfo.path = self.main.get_spyder_pythonpath()
        self._clone_file_everywhere(finfo)
        current_editor = current_es.set_current_filename(finfo.filename)
        self.register_widget_shortcuts(current_editor)
        if not created_from_here:
            self.save(force=True)
306833
function withInsertions(initial, insertions) {
  if (insertions.length === 0) {
    return initial;
  }
  let edited = '';
  let prevIndex = 0;
  insertions.forEach(({ index, string }) => {
    edited += initial.slice(prevIndex, index) + string;
    prevIndex = index;
  });
  edited += initial.slice(prevIndex);
  return edited;
}
15
def create_or_update(cls, build):
        

        test_summary = build.test_summary
        metrics_summary = MetricsSummary(build)
        now = timezone.now()
        test_runs_total = build.test_runs.count()
        test_runs_completed = build.test_runs.filter(completed=True).count()
        test_runs_incomplete = build.test_runs.filter(completed=False).count()
        regressions = None
        fixes = None

        previous_build = Build.objects.filter(
            status__finished=True,
            datetime__lt=build.datetime,
            project=build.project,
        ).order_by('datetime').last()
        if previous_build is not None:
            comparison = TestComparison(previous_build, build)
            if comparison.regressions:
                regressions = yaml.dump(comparison.regressions)
            if comparison.fixes:
                fixes = yaml.dump(comparison.fixes)

        finished, _ = build.finished
        data = {
            'tests_pass': test_summary.tests_pass,
            'tests_fail': test_summary.tests_fail,
            'tests_xfail': test_summary.tests_xfail,
            'tests_skip': test_summary.tests_skip,
            'metrics_summary': metrics_summary.value,
            'has_metrics': metrics_summary.has_metrics,
            'last_updated': now,
            'finished': finished,
            'test_runs_total': test_runs_total,
            'test_runs_completed': test_runs_completed,
            'test_runs_incomplete': test_runs_incomplete,
            'regressions': regressions,
            'fixes': fixes
        }

        status, created = cls.objects.get_or_create(build=build, defaults=data)
        if not created and test_summary.tests_total >= status.tests_total:
            # XXX the test above for the new total number of tests prevents
            # results that arrived earlier, but are only being processed now,
            # from overwriting a ProjectStatus created by results that arrived
            # later but were already processed.
            status.tests_pass = test_summary.tests_pass
            status.tests_fail = test_summary.tests_fail
            status.tests_xfail = test_summary.tests_xfail
            status.tests_skip = test_summary.tests_skip
            status.metrics_summary = metrics_summary.value
            status.has_metrics = metrics_summary.has_metrics
            status.last_updated = now
            finished, _ = build.finished
            status.finished = finished
            status.build = build
            status.test_runs_total = test_runs_total
            status.test_runs_completed = test_runs_completed
            status.test_runs_incomplete = test_runs_incomplete
            status.regressions = regressions
            status.fixes = fixes
            status.save()
        return status
454393
def create_all(self, checkfirst=True):
        
        log.info('creating tables in %s', self.engine.url)
        models.Base.metadata.create_all(self.engine, checkfirst=checkfirst)
112730
def make_diff(current, revision):
    """"""
    the_diff = []
    dmp = diff_match_patch()

    for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())):
        # These exclusions really should be configurable
        if field == 'id' or field.endswith('_rendered'):
            continue
        # KeyError's may happen if the database structure changes
        # between the creation of revisions. This isn't ideal,
        # but should not be a fatal error.
        # Log this?
        missing_field = False
        try:
            cur_val = current.field_dict[field] or ""
        except KeyError:
            cur_val = "No such field in latest version\n"
            missing_field = True
        try:
            old_val = revision.field_dict[field] or ""
        except KeyError:
            old_val = "No such field in old version\n"
            missing_field = True
        if missing_field:
            # Ensure that the complete texts are marked as changed
            # so new entries containing any of the marker words
            # don't show up as differences
            diffs = [(dmp.DIFF_DELETE, old_val), (dmp.DIFF_INSERT, cur_val)]
            patch =  dmp.diff_prettyHtml(diffs)
        elif isinstance(cur_val, Markup):
            # we roll our own diff here, so we can compare of the raw
            # markdown, rather than the rendered result.
            if cur_val.raw == old_val.raw:
                continue
            diffs = dmp.diff_main(old_val.raw, cur_val.raw)
            patch =  dmp.diff_prettyHtml(diffs)
        elif cur_val == old_val:
            continue
        else:
            # Compare the actual field values
            diffs = dmp.diff_main(force_text(old_val), force_text(cur_val))
            patch = dmp.diff_prettyHtml(diffs)
        the_diff.append((field, patch))

    the_diff.sort()
    return the_diff
528428
def new(self, repo):
        
        #TODO: subclass Commit, pass parent as init param
        try:
            # create new commit instance and set metadata
            commit = Commit()
            author = os.environ.get('USER')
            commit.author = commit.committer = author
            commit.commit_time = commit.author_time = int(time())
            tz = parse_timezone('-0200')[0]
            commit.commit_timezone = commit.author_timezone = tz
            commit.encoding = "UTF-8"
            commit.message = ''

            # set previous version as parent to this one
            parent = repo.versions(-1)
            if parent:
                commit.parents = [parent.id]

            # create new tree, add entries from previous version
            tree = Tree()
            curr = repo.versions(-1)
            if curr:
                for item in curr.items():
                    tree.addItem(item)
            commit.tree = tree.id

            # create new version, and add tree
            version = Version(repo=repo, commit=commit, tree=tree)
            return version

        except Exception, e:
            traceback.print_exc()
            return VersionError(e)
987424
def create_versions(self, project_id, versions):
        

        for v in versions:
            self.create_version(project_id, v)