make the dictionary for the clustergram.js visualization
763858
def viz_json(net, dendro=True, links=False):
  '''  '''
  from . import calc_clust
  import numpy as np

  all_dist = calc_clust.group_cutoffs()

  for inst_rc in net.dat['nodes']:

    inst_keys = net.dat['node_info'][inst_rc]
    all_cats = [x for x in inst_keys if 'cat-' in x]

    for i in range(len(net.dat['nodes'][inst_rc])):
      inst_dict = {}
      inst_dict['name'] = net.dat['nodes'][inst_rc][i]
      inst_dict['ini'] = net.dat['node_info'][inst_rc]['ini'][i]
      inst_dict['clust'] = net.dat['node_info'][inst_rc]['clust'].index(i)
      inst_dict['rank'] = net.dat['node_info'][inst_rc]['rank'][i]

      if 'rankvar' in inst_keys:
        inst_dict['rankvar'] = net.dat['node_info'][inst_rc]['rankvar'][i]

      # fix for similarity matrix
      if len(all_cats) > 0:

        for inst_name_cat in all_cats:

          actual_cat_name = net.dat['node_info'][inst_rc][inst_name_cat][i]
          inst_dict[inst_name_cat] = actual_cat_name

          check_pval = 'pval_'+inst_name_cat.replace('-','_')

          if check_pval in net.dat['node_info'][inst_rc]:
            tmp_pval_name = inst_name_cat.replace('-','_') + '_pval'
            inst_dict[tmp_pval_name] = net.dat['node_info'][inst_rc][check_pval][actual_cat_name]

          tmp_index_name = inst_name_cat.replace('-', '_') + '_index'

          inst_dict[tmp_index_name] = net.dat['node_info'][inst_rc] \
              [tmp_index_name][i]


      if len(net.dat['node_info'][inst_rc]['value']) > 0:
        inst_dict['value'] = net.dat['node_info'][inst_rc]['value'][i]

      if len(net.dat['node_info'][inst_rc]['info']) > 0:
        inst_dict['info'] = net.dat['node_info'][inst_rc]['info'][i]

      if dendro is True:
        inst_dict['group'] = []
        for tmp_dist in all_dist:
          tmp_dist = str(tmp_dist).replace('.', '')
          tmp_append = float(
              net.dat['node_info'][inst_rc]['group'][tmp_dist][i])
          inst_dict['group'].append(tmp_append)

      net.viz[inst_rc + '_nodes'].append(inst_dict)

  mat_types = ['mat', 'mat_orig', 'mat_info', 'mat_hl', 'mat_up', 'mat_dn']

  # save data as links or mat
  ###########################
  if links is True:
    for i in range(len(net.dat['nodes']['row'])):
      for j in range(len(net.dat['nodes']['col'])):

        inst_dict = {}
        inst_dict['source'] = i
        inst_dict['target'] = j
        inst_dict['value'] = float(net.dat['mat'][i, j])

        if 'mat_up' in net.dat:
          inst_dict['value_up'] = net.dat['mat_up'][i, j]
          inst_dict['value_dn'] = net.dat['mat_dn'][i, j]

        if 'mat_orig' in net.dat:
          inst_dict['value_orig'] = net.dat['mat_orig'][i, j]

          if np.isnan(inst_dict['value_orig']):
            inst_dict['value_orig'] = 'NaN'


        if 'mat_info' in net.dat:
          inst_dict['info'] = net.dat['mat_info'][str((i, j))]

        if 'mat_hl' in net.dat:
          inst_dict['highlight'] = net.dat['mat_hl'][i, j]

        net.viz['links'].append(inst_dict)

  else:
    for inst_mat in mat_types:
      if inst_mat in net.dat:
        net.viz[inst_mat] = net.dat[inst_mat].tolist()
686974
def colordict(self):
        
        d = {}
        i=0
        n = len(self.constraints)
        for c in self.constraints:
            #self.colordict[c] = colors[i % 6]
            d[c] = cm.jet(1.*i/n)
            i+=1
        return d
201814
function graph (processedTypes, typeTheme) {
  var result = ''

  if (typeTheme.group) {
    result += 'subgraph cluster_' + groupId++ + ' {'
    if (typeTheme.color) {
      result += 'color=' + typeTheme.color + ';'
    }
    if (typeTheme.groupLabel) {
      result += 'label="' + typeTheme.groupLabel + '";'
    }
  }

  result += _.map(processedTypes, v => {
    // sort if desired
    if (this.theme.field.sort) {
      v.fields = _.sortBy(v.fields, 'name')
    }

    var rows = _.map(v.fields, v => {
      return {
        text: createField.call(this, v),
        port: v.name + 'port'
      }
    })

    return createTable.call(this, {
      typeName: getTypeDisplayName(v.name),
      color: typeTheme.color,
      stereotype: typeTheme.stereotype,
      rows: rows
    })
  }).join('\n')

  if (typeTheme.group) {
    result += '}'
  }

  result += '\n\n'
  return result
}
843045
def to_html(self):
        '''
        

        '''
        javascript_to_insert = '\n'.join([
            PackedDataUtils.full_content_of_javascript_files(),
            self.category_scatterplot_structure._visualization_data.to_javascript('getCategoryDataAndInfo'),
            self.category_scatterplot_structure.get_js_to_call_build_scatterplot(self.category_plot_interface),
            self.term_scatterplot_structure._visualization_data.to_javascript('getTermDataAndInfo'),
            self.term_scatterplot_structure.get_js_to_call_build_scatterplot(self.term_plot_interface),
        ])
        html_template = self._get_html_template()
        html_content = (
            html_template
                .replace('<!-- INSERT SCRIPT -->', javascript_to_insert, 1)
                .replace('<!--D3URL-->', self.d3_url_struct.get_d3_url(), 1)
                .replace('<!--D3SCALECHROMATIC-->', self.d3_url_struct.get_d3_scale_chromatic_url())
            # .replace('<!-- INSERT D3 -->', self._get_packaged_file_content('d3.min.js'), 1)
        )
        html_content = (html_content.replace('http://', self.protocol + '://'))
        if self.show_halo:
            axes_labels = self.category_projection.get_nearest_terms(
                num_terms=self.num_terms
            )
            for position, terms in axes_labels.items():
                html_content = html_content.replace('{%s}' % position, self._get_lexicon_html(terms))
        return html_content.replace('{width}', str(self.category_width)).replace('{height}', str(self.category_height))
871477
def asDictionary(self):
        
        template = {"type" : self._type,
                    "mapLayerId" : self._mapLayerId}
        if not self._gdbVersion is None and\
           self._gdbVersion != "":
            template['gdbVersion'] = self._gdbVersion
        return template
644186
def clusters_sites_obj(clusters):
    
    result = {}
    all_clusters = get_all_clusters_sites()
    clusters_sites = {c: s for (c, s) in all_clusters.items()
                        if c in clusters}
    for cluster, site in clusters_sites.items():

        # here we want the site python-grid5000 site object
        result.update({cluster: get_site_obj(site)})
    return result
1286245
def from_json(self, js, groups: Iterable[Group]):
        
        self.index = js["index"]
        self.groupIndex = js["groupIndex"]
        self.label = js["label"]
        self.functionalChannelType = FunctionalChannelType.from_str(
            js["functionalChannelType"], js["functionalChannelType"]
        )
        self.groups = []
        for id in js["groups"]:
            for g in groups:
                if g.id == id:
                    self.groups.append(g)
                    break
697953
function getColormap() {
    var map = [];
    var index = [];

    for (var i = 0; i < netsize; i++)
      index[network[i][3]] = i;

    var k = 0;
    for (var l = 0; l < netsize; l++) {
      var j = index[l];
      map[k++] = (network[j][0]);
      map[k++] = (network[j][1]);
      map[k++] = (network[j][2]);
    }
    return map;
  }
375104
def scale_dict_wet(C):
    """"""
    return {k: v / _scale_dict[k] for k, v in C.items()}
624999
def as_dict( self, key="id" ):
        
        rval = {}
        for motif in self:
            rval[ getattr( motif, key ) ] = motif
        return rval
393564
function hierarchicalClustering(options) {
  var cy = this.cy();
  var nodes = this.nodes(); // Set parameters of algorithm: linkage type, distance metric, etc.

  var opts = setOptions$2(options);
  var attrs = opts.attributes;

  var getDist = function getDist(n1, n2) {
    return clusteringDistance(opts.distance, attrs.length, function (i) {
      return attrs[i](n1);
    }, function (i) {
      return attrs[i](n2);
    });
  }; // Begin hierarchical algorithm


  var clusters = [];
  var dists = []; // distances between each pair of clusters

  var mins = []; // closest cluster for each cluster

  var index = []; // hash of all clusters by key
  // In agglomerative (bottom-up) clustering, each node starts as its own cluster

  for (var n = 0; n < nodes.length; n++) {
    var cluster = {
      value: opts.mode === 'dendrogram' ? nodes[n] : [nodes[n]],
      key: n,
      index: n
    };
    clusters[n] = cluster;
    index[n] = cluster;
    dists[n] = [];
    mins[n] = 0;
  } // Calculate the distance between each pair of clusters


  for (var i = 0; i < clusters.length; i++) {
    for (var j = 0; j <= i; j++) {
      var dist = void 0;

      if (opts.mode === 'dendrogram') {
        // modes store cluster values differently
        dist = i === j ? Infinity : getDist(clusters[i].value, clusters[j].value);
      } else {
        dist = i === j ? Infinity : getDist(clusters[i].value[0], clusters[j].value[0]);
      }

      dists[i][j] = dist;
      dists[j][i] = dist;

      if (dist < dists[i][mins[i]]) {
        mins[i] = j; // Cache mins: closest cluster to cluster i is cluster j
      }
    }
  } // Find the closest pair of clusters and merge them into a single cluster.
  // Update distances between new cluster and each of the old clusters, and loop until threshold reached.


  var merged = mergeClosest(clusters, index, dists, mins, opts);

  while (merged) {
    merged = mergeClosest(clusters, index, dists, mins, opts);
  }

  var retClusters; // Dendrogram mode builds the hierarchy and adds intermediary nodes + edges
  // in addition to returning the clusters.

  if (opts.mode === 'dendrogram') {
    retClusters = buildClustersFromTree(clusters[0], opts.dendrogramDepth, cy);
    if (opts.addDendrogram) buildDendrogram(clusters[0], cy);
  } else {
    // Regular mode simply returns the clusters
    retClusters = new Array(clusters.length);
    clusters.forEach(function (cluster, i) {
      // Clean up meta data used for clustering
      cluster.key = cluster.index = null;
      retClusters[i] = cy.collection(cluster.value);
    });
  }

  return retClusters;
}
1215536
def asDictionary(self):
        
        template = {
            "type" : "esriSMS",
            "style" : self._style,
            "color" : self._color,
            "size" : self._size,
            "angle" : self._angle,
            "xoffset" : self._xoffset,
            "yoffset" : self._yoffset
        }
        if self._outlineColor is not None and \
           self._outlineWidth is not None:
            template["outline"] = {
                "color" : self._outlineColor,
                "width" : self._outlineWidth
            }
        return template
815270
def dict_expand(d, prefix=None):
    
    result = {}
    for k, v in d.items():
        if isinstance(v, dict):
            result.update(dict_expand(v, prefix=k))
        else:
            result[k] = v

    if prefix is not None:
        result = {make_tuple(prefix) + make_tuple(k): v
                  for k, v in result.items()}
    return result
456184
def outdict(self, ndigits=3):
        """"""

        outdict = {}
        for i in range(EMIR_NBARS):
            ibar = i + 1
            cbar = 'slitlet' + str(ibar).zfill(2)
            outdict[cbar] = {}
            outdict[cbar]['_csu_bar_left'] = \
                round(self._csu_bar_left[i], ndigits)
            outdict[cbar]['_csu_bar_right'] = \
                round(self._csu_bar_right[i], ndigits)
            outdict[cbar]['_csu_bar_slit_center'] = \
                round(self._csu_bar_slit_center[i], ndigits)
            outdict[cbar]['_csu_bar_slit_width'] = \
                round(self._csu_bar_slit_width[i], ndigits)

        return outdict
1372144
def _get_cluster_dict(cluster_name, cluster_ref):
    '''
    
    '''

    log.trace('Building a dictionary representation of cluster \'%s\'', cluster_name)
    props = salt.utils.vmware.get_properties_of_managed_object(
        cluster_ref,
        properties=['configurationEx'])
    res = {'ha': {'enabled': props['configurationEx'].dasConfig.enabled},
           'drs': {'enabled': props['configurationEx'].drsConfig.enabled}}
    # Convert HA properties of interest
    ha_conf = props['configurationEx'].dasConfig
    log.trace('ha_conf = %s', ha_conf)
    res['ha']['admission_control_enabled'] = ha_conf.admissionControlEnabled
    if ha_conf.admissionControlPolicy and \
       isinstance(ha_conf.admissionControlPolicy,
                  vim.ClusterFailoverResourcesAdmissionControlPolicy):
        pol = ha_conf.admissionControlPolicy
        res['ha']['admission_control_policy'] = \
                {'cpu_failover_percent': pol.cpuFailoverResourcesPercent,
                 'memory_failover_percent': pol.memoryFailoverResourcesPercent}
    if ha_conf.defaultVmSettings:
        def_vm_set = ha_conf.defaultVmSettings
        res['ha']['default_vm_settings'] = \
                {'isolation_response': def_vm_set.isolationResponse,
                 'restart_priority': def_vm_set.restartPriority}
    res['ha']['hb_ds_candidate_policy'] = \
            ha_conf.hBDatastoreCandidatePolicy
    if ha_conf.hostMonitoring:
        res['ha']['host_monitoring'] = ha_conf.hostMonitoring
    if ha_conf.option:
        res['ha']['options'] = [{'key': o.key, 'value': o.value}
                                for o in ha_conf.option]
    res['ha']['vm_monitoring'] = ha_conf.vmMonitoring
    # Convert DRS properties
    drs_conf = props['configurationEx'].drsConfig
    log.trace('drs_conf = %s', drs_conf)
    res['drs']['vmotion_rate'] = 6 - drs_conf.vmotionRate
    res['drs']['default_vm_behavior'] = drs_conf.defaultVmBehavior
    # vm_swap_placement
    res['vm_swap_placement'] = props['configurationEx'].vmSwapPlacement
    # Convert VSAN properties
    si = salt.utils.vmware.get_service_instance_from_managed_object(
        cluster_ref)

    if salt.utils.vsan.vsan_supported(si):
        # XXX The correct way of retrieving the VSAN data (on the if branch)
        #  is not supported before 60u2 vcenter
        vcenter_info = salt.utils.vmware.get_service_info(si)
        if int(vcenter_info.build) >= 3634794:  # 60u2
            # VSAN API is fully supported by the VC starting with 60u2
            vsan_conf = salt.utils.vsan.get_cluster_vsan_info(cluster_ref)
            log.trace('vsan_conf = %s', vsan_conf)
            res['vsan'] = {'enabled': vsan_conf.enabled,
                           'auto_claim_storage':
                           vsan_conf.defaultConfig.autoClaimStorage}
            if vsan_conf.dataEfficiencyConfig:
                data_eff = vsan_conf.dataEfficiencyConfig
                res['vsan'].update({
                    # We force compression_enabled to be True/False
                    'compression_enabled':
                    data_eff.compressionEnabled or False,
                    'dedup_enabled': data_eff.dedupEnabled})
        else:  # before 60u2 (no advanced vsan info)
            if props['configurationEx'].vsanConfigInfo:
                default_config = \
                        props['configurationEx'].vsanConfigInfo.defaultConfig
                res['vsan'] = {
                    'enabled': props['configurationEx'].vsanConfigInfo.enabled,
                    'auto_claim_storage': default_config.autoClaimStorage}
    return res
787529
def get_dotstr(self):
        """"""
        dotobj = self.gosubdagplot.get_pydot_graph() # pydot.Dot
        dotstr = dotobj.create_dot()
        return dotstr
552546
def make_dict_config(graph):
    
    formatters = {}
    handlers = {}
    loggers = {}

    # create the console handler
    formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
    handlers["console"] = make_stream_handler(graph, formatter="ExtraFormatter")

    # maybe create the loggly handler
    if enable_loggly(graph):
        formatters["JSONFormatter"] = make_json_formatter(graph)
        handlers["LogglyHTTPSHandler"] = make_loggly_handler(graph, formatter="JSONFormatter")

    # configure the root logger to output to all handlers
    loggers[""] = {
        "handlers": handlers.keys(),
        "level": graph.config.logging.level,
    }

    # set log levels for libraries
    loggers.update(make_library_levels(graph))

    return dict(
        version=1,
        disable_existing_loggers=False,
        formatters=formatters,
        handlers=handlers,
        loggers=loggers,
    )