Yield an IssueSnapshot for each time the issue changed status or
        resolution
7229
def iter_changes(self, issue, include_resolution_changes=True):
        

        is_resolved = False

        # Find the first status change, if any
        try:
            status_changes = list(filter(
                lambda h: h.field == 'status',
                itertools.chain.from_iterable([c.items for c in issue.changelog.histories])))
        except AttributeError:
            return
        last_status = status_changes[0].fromString if len(status_changes) > 0 else issue.fields.status.name
        last_resolution = None

        # Issue was created
        yield IssueSnapshot(
            change=None,
            key=issue.key,
            date=dateutil.parser.parse(issue.fields.created),
            status=last_status,
            resolution=None,
            is_resolved=is_resolved
        )

        for change in issue.changelog.histories:
            change_date = dateutil.parser.parse(change.created)

            resolutions = list(filter(lambda i: i.field == 'resolution', change.items))
            is_resolved = (resolutions[-1].to is not None) if len(resolutions) > 0 else is_resolved

            for item in change.items:
                if item.field == 'status':
                    # Status was changed
                    last_status = item.toString
                    yield IssueSnapshot(
                        change=item.field,
                        key=issue.key,
                        date=change_date,
                        status=last_status,
                        resolution=last_resolution,
                        is_resolved=is_resolved
                    )
                elif item.field == 'resolution':
                    last_resolution = item.toString
                    if include_resolution_changes:
                        yield IssueSnapshot(
                            change=item.field,
                            key=issue.key,
                            date=change_date,
                            status=last_status,
                            resolution=last_resolution,
                            is_resolved=is_resolved
                        )
465673
function updateSnapshot(app, uid, cb) {
  logger.debug('updateSnapshot entry');

  app.models.snapshot.findOne(
    { where: { current: 'true' } },
    function(err, instance) {
      if (err) {
        // fall through assuming there was no current
      } else if (instance) {
        instance.updateAttributes(
          { current: 'false' },
          function(err, instance) {
            if (err) {
              // fall through assuming instance was deleted
            }
          });
        releaseSnapshot(app, instance.id);
      }
    });

  app.models.snapshot.findById(uid, function(err, instance) {
    if (err) {
      logger.debug('updateSnapshot error(1)');
      cb(err);
      return;
    }

    instance.updateAttributes(
      { current: 'true' },
      function(err, instance) {
        if (err) {
          logger.debug('updateSnapshot error(2)');
          cb(err);
          return;
        }
        logger.debug('updateSnapshot exit');
        cb();
      });
  });
}
178256
def issue_line(issue):
    """"""
    template = '#{number} {tags}{title}'
    tags = issue_tags(issue)
    params = {
        'title': issue['title'].capitalize().rstrip('.'),
        'number': issue['number'],
        'tags': ' '.join('[{}]'.format(tag) for tag in tags) + (' ' if tags else '')
    }
    return template.format(**params)
628336
def run_with_snapshots(self, tsnapstart=0., tsnapint=432000.):
        

        tsnapints = np.ceil(tsnapint/self.dt)

        while(self.t < self.tmax):
            self._step_forward()
            if self.t>=tsnapstart and (self.tc%tsnapints)==0:
                yield self.t
        return
413534
def cli(env, volume_id, notes):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    snapshot = block_manager.create_snapshot(volume_id, notes=notes)

    if 'id' in snapshot:
        click.echo('New snapshot created with id: %s' % snapshot['id'])
    else:
        click.echo('Error occurred while creating snapshot.\n'
                   'Ensure volume is not failed over or in another '
                   'state which prevents taking snapshots.')
886402
def MultiReadClientSnapshot(self, client_ids, cursor=None):
    """"""
    int_ids = [db_utils.ClientIDToInt(cid) for cid in client_ids]
    query = (
        "SELECT h.client_id, h.client_snapshot, UNIX_TIMESTAMP(h.timestamp),"
        "       s.startup_info "
        "FROM clients as c FORCE INDEX (PRIMARY), "
        "client_snapshot_history as h FORCE INDEX (PRIMARY), "
        "client_startup_history as s FORCE INDEX (PRIMARY) "
        "WHERE h.client_id = c.client_id "
        "AND s.client_id = c.client_id "
        "AND h.timestamp = c.last_snapshot_timestamp "
        "AND s.timestamp = c.last_startup_timestamp "
        "AND c.client_id IN ({})").format(", ".join(["%s"] * len(client_ids)))
    ret = {cid: None for cid in client_ids}
    cursor.execute(query, int_ids)

    while True:
      row = cursor.fetchone()
      if not row:
        break
      cid, snapshot, timestamp, startup_info = row
      client_obj = mysql_utils.StringToRDFProto(rdf_objects.ClientSnapshot,
                                                snapshot)
      client_obj.startup_info = mysql_utils.StringToRDFProto(
          rdf_client.StartupInfo, startup_info)
      client_obj.timestamp = mysql_utils.TimestampToRDFDatetime(timestamp)
      ret[db_utils.IntToClientID(cid)] = client_obj
    return ret
601606
def logs(self):
        
        for record in self.history:
            if (record["when"] >= self.options.since.date
                    and record["when"] < self.options.until.date):
                for change in record["changes"]:
                    yield record["who"], change
142780
def _generate_issue(self, run, entry, callablesCount):
        """"""

        trace_frames = []

        for p in entry["preconditions"]:
            tf = self._generate_issue_precondition(run, entry, p)
            trace_frames.append(tf)

        for p in entry["postconditions"]:
            tf = self._generate_issue_postcondition(run, entry, p)
            trace_frames.append(tf)

        features = set()
        for f in entry["features"]:
            features.update(self._generate_issue_feature_contents(entry, f))

        callable = entry["callable"]
        handle = self._get_issue_handle(entry)
        # TODO: record depth in issue_sink and issue_source assoc, but this can
        # be different per instance, so should be stored with the instance.
        initial_sources = {
            self._get_shared_text(SharedTextKind.SOURCE, s)
            for (s, _) in entry["initial_sources"]
        }
        final_sinks = {
            self._get_shared_text(SharedTextKind.SINK, s)
            for (s, _) in entry["final_sinks"]
        }

        issue = Issue.Record(
            id=IssueDBID(),
            code=entry["code"],
            handle=handle,
            status=IssueStatus.UNCATEGORIZED,
            first_seen=run.date,
            run_id=run.id,
        )

        self.graph.add_issue(issue)

        fix_info = None
        fix_info_id = None
        if entry.get("fix_info") is not None:
            fix_info = IssueInstanceFixInfo.Record(
                id=DBID(), fix_info=json.dumps(entry["fix_info"])
            )
            fix_info_id = fix_info.id

        message = self._get_shared_text(SharedTextKind.MESSAGE, entry["message"])
        filename_record = self._get_shared_text(
            SharedTextKind.FILENAME, entry["filename"]
        )
        callable_record = self._get_shared_text(SharedTextKind.CALLABLE, callable)

        instance = IssueInstance.Record(
            id=DBID(),
            issue_id=issue.id,
            location=self.get_location(entry),
            filename_id=filename_record.id,
            callable_id=callable_record.id,
            run_id=run.id,
            fix_info_id=fix_info_id,
            message_id=message.id,
            rank=0,
            min_trace_length_to_sources=self._get_minimum_trace_length(
                entry["postconditions"]
            ),
            min_trace_length_to_sinks=self._get_minimum_trace_length(
                entry["preconditions"]
            ),
            callable_count=callablesCount[callable],
        )

        for sink in final_sinks:
            self.graph.add_issue_instance_shared_text_assoc(instance, sink)
        for source in initial_sources:
            self.graph.add_issue_instance_shared_text_assoc(instance, source)

        if fix_info is not None:
            self.graph.add_issue_instance_fix_info(instance, fix_info)

        for trace_frame in trace_frames:
            self.graph.add_issue_instance_trace_frame_assoc(instance, trace_frame)

        for feature in features:
            feature = self._get_shared_text(SharedTextKind.FEATURE, feature)
            self.graph.add_issue_instance_shared_text_assoc(instance, feature)

        self.graph.add_issue_instance(instance)
1203628
def _populate_issue_and_traces(self, graph: TraceGraph, instance_id: int) -> None:
        
        self._populate_issue(graph, instance_id)
        self._populate_issue_trace(graph, instance_id)
320162
def get_issues_by_resource(resource_id, table):
    """"""

    v1_utils.verify_existence_and_get(resource_id, table)

    # When retrieving the issues for a job, we actually retrieve
    # the issues attach to the job itself + the issues attached to
    # the components the job has been run with.
    if table.name == 'jobs':
        JJI = models.JOIN_JOBS_ISSUES
        JJC = models.JOIN_JOBS_COMPONENTS
        JCI = models.JOIN_COMPONENTS_ISSUES

        # Get all the issues attach to all the components attach to a job
        j1 = sql.join(
            _TABLE,
            sql.join(
                JCI,
                JJC,
                sql.and_(
                    JCI.c.component_id == JJC.c.component_id,
                    JJC.c.job_id == resource_id,
                ),
            ),
            _TABLE.c.id == JCI.c.issue_id,
        )

        query = sql.select([_TABLE]).select_from(j1)
        rows = flask.g.db_conn.execute(query)
        rows = [dict(row) for row in rows]

        # Get all the issues attach to a job
        j2 = sql.join(
            _TABLE,
            JJI,
            sql.and_(
                _TABLE.c.id == JJI.c.issue_id,
                JJI.c.job_id == resource_id
            )
        )
        query2 = sql.select([_TABLE]).select_from(j2)
        rows2 = flask.g.db_conn.execute(query2)
        rows += [dict(row) for row in rows2]

    # When retrieving the issues for a component, we only retrieve the
    # issues attached to the specified component.
    else:
        JCI = models.JOIN_COMPONENTS_ISSUES

        query = (sql.select([_TABLE])
                 .select_from(JCI.join(_TABLE))
                 .where(JCI.c.component_id == resource_id))

        rows = flask.g.db_conn.execute(query)
        rows = [dict(row) for row in rows]

    for row in rows:
        if row['tracker'] == 'github':
            l_tracker = github.Github(row['url'])
        elif row['tracker'] == 'bugzilla':
            l_tracker = bugzilla.Bugzilla(row['url'])
        row.update(l_tracker.dump())

    return flask.jsonify({'issues': rows,
                          '_meta': {'count': len(rows)}})
814132
def WriteClientSnapshot(self, snapshot, cursor=None):
    """"""
    insert_history_query = (
        "INSERT INTO client_snapshot_history(client_id, timestamp, "
        "client_snapshot) VALUES (%s, FROM_UNIXTIME(%s), %s)")
    insert_startup_query = (
        "INSERT INTO client_startup_history(client_id, timestamp, "
        "startup_info) VALUES(%s, FROM_UNIXTIME(%s), %s)")

    now = rdfvalue.RDFDatetime.Now()

    client_platform = snapshot.knowledge_base.os
    current_timestamp = mysql_utils.RDFDatetimeToTimestamp(now)
    client_info = {
        "last_snapshot_timestamp": current_timestamp,
        "last_startup_timestamp": current_timestamp,
        "last_version_string": snapshot.GetGRRVersionString(),
        "last_platform_release": snapshot.Uname(),
    }
    update_clauses = [
        "last_snapshot_timestamp = FROM_UNIXTIME(%(last_snapshot_timestamp)s)",
        "last_startup_timestamp = FROM_UNIXTIME(%(last_startup_timestamp)s)",
        "last_version_string = %(last_version_string)s",
        "last_platform_release = %(last_platform_release)s",
    ]
    if client_platform:
      client_info["last_platform"] = client_platform
      update_clauses.append("last_platform = %(last_platform)s")

    update_query = (
        "UPDATE clients SET {} WHERE client_id = %(client_id)s".format(
            ", ".join(update_clauses)))

    int_client_id = db_utils.ClientIDToInt(snapshot.client_id)
    client_info["client_id"] = int_client_id

    startup_info = snapshot.startup_info
    snapshot.startup_info = None
    try:
      cursor.execute(
          insert_history_query,
          (int_client_id, current_timestamp, snapshot.SerializeToString()))
      cursor.execute(
          insert_startup_query,
          (int_client_id, current_timestamp, startup_info.SerializeToString()))
      cursor.execute(update_query, client_info)
    except MySQLdb.IntegrityError as e:
      raise db.UnknownClientError(snapshot.client_id, cause=e)
    finally:
      snapshot.startup_info = startup_info
577673
def status_handler(args):
    

    repo = _open_repo(args)

    for anchor_id, anchor in repo.items():
        diff_lines = get_anchor_diff(anchor)
        if diff_lines:
            print('{} {}:{} out-of-date'.format(
                anchor_id,
                anchor.file_path,
                anchor.context.offset))

    return ExitCode.OK
313083
def _format_issue(issue):
    '''
    
    '''
    ret = {'id': issue.get('id'),
           'issue_number': issue.get('number'),
           'state': issue.get('state'),
           'title': issue.get('title'),
           'user': issue.get('user').get('login'),
           'html_url': issue.get('html_url')}

    assignee = issue.get('assignee')
    if assignee:
        assignee = assignee.get('login')

    labels = issue.get('labels')
    label_names = []
    for label in labels:
        label_names.append(label.get('name'))

    milestone = issue.get('milestone')
    if milestone:
        milestone = milestone.get('title')

    ret['assignee'] = assignee
    ret['labels'] = label_names
    ret['milestone'] = milestone

    return ret
1224750
def fetch_closed_issues_and_pr
      print "Fetching closed issues...\r" if @options[:verbose]
      issues = []
      page_i      = 0
      count_pages = calculate_pages(@client, "issues", closed_pr_options)

      iterate_pages(@client, "issues", closed_pr_options) do |new_issues|
        page_i += PER_PAGE_NUMBER
        print_in_same_line("Fetching issues... #{page_i}/#{count_pages * PER_PAGE_NUMBER}")
        issues.concat(new_issues)
        break if @options[:max_issues] && issues.length >= @options[:max_issues]
      end
      print_empty_line
      Helper.log.info "Received issues: #{issues.count}"

      # separate arrays of issues and pull requests:
      issues.map { |issue| stringify_keys_deep(issue.to_hash) }
            .partition { |issue_or_pr| issue_or_pr["pull_request"].nil? }
    end
1367809
def MultiReadClientSnapshot(self, client_ids):
    """"""
    res = {}
    for client_id in client_ids:
      history = self.clients.get(client_id, None)
      if not history:
        res[client_id] = None
        continue
      last_timestamp = max(history)
      last_serialized = history[last_timestamp]
      client_obj = rdf_objects.ClientSnapshot.FromSerializedString(
          last_serialized)
      client_obj.timestamp = last_timestamp
      client_obj.startup_info = rdf_client.StartupInfo.FromSerializedString(
          self.startup_history[client_id][last_timestamp])
      res[client_id] = client_obj
    return res
695993
def closed_issue(issue, after=None):
    """"""
    if issue['state'] == 'closed':
        if after is None or parse_timestamp(issue['closed_at']) > after:
            return True
    return False
208812
def relevant_issues(issues, after):
    """"""
    logging.info('finding relevant issues after {}...'.format(after))
    seen = set()
    for issue in issues:
        if relevent_issue(issue, after) and issue['title'] not in seen:
            seen.add(issue['title'])
            yield issue