Get CCLE mRNA amounts using cBioClient
178302
def get_ccle_mrna_levels():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    gene_list = body.get('gene_list')
    cell_lines = body.get('cell_lines')
    mrna_amounts = cbio_client.get_ccle_mrna(gene_list, cell_lines)
    res = {'mrna_amounts': mrna_amounts}
    return res
1196628
function getEspruinoPrompt(callback) {
    if (Espruino.Core.Terminal!==undefined &&
        Espruino.Core.Terminal.getTerminalLine()==">") {
      console.log("Found a prompt... great!");
      return callback();
    }

    var receivedData = "";
    var prevReader = Espruino.Core.Serial.startListening(function (readData) {
      var bufView = new Uint8Array(readData);
      for(var i = 0; i < bufView.length; i++) {
        receivedData += String.fromCharCode(bufView[i]);
      }
      if (receivedData[receivedData.length-1] == ">") {
        if (receivedData.substr(-6)=="debug>") {
          console.log("Got debug> - sending Ctrl-C to break out and we'll be good");
          Espruino.Core.Serial.write('\x03');
        } else {
          if (receivedData == "\r\n=undefined\r\n>")
            receivedData=""; // this was just what we expected - so ignore it

          console.log("Received a prompt after sending newline... good!");
          clearTimeout(timeout);
          nextStep();
        }
      }
    });
    // timeout in case something goes wrong...
    var hadToBreak = false;
    var timeout = setTimeout(function() {
      console.log("Got "+JSON.stringify(receivedData));
      // if we haven't had the prompt displayed for us, Ctrl-C to break out of what we had
      console.log("No Prompt found, got "+JSON.stringify(receivedData[receivedData.length-1])+" - issuing Ctrl-C to try and break out");
      Espruino.Core.Serial.write('\x03');
      hadToBreak = true;
      timeout = setTimeout(function() {
        console.log("Still no prompt - issuing another Ctrl-C");
        Espruino.Core.Serial.write('\x03');
        nextStep();
      },500);
    },500);
    // when we're done...
    var nextStep = function() {
      // send data to console anyway...
      if(prevReader) prevReader(receivedData);
      receivedData = "";
      // start the previous reader listening again
      Espruino.Core.Serial.startListening(prevReader);
      // call our callback
      if (callback) callback(hadToBreak);
    };
    // send a newline, and we hope we'll see '=undefined\r\n>'
    Espruino.Core.Serial.write('\n');
  }
21933
public void getTraceSummaryLine(StringBuilder buff) {
    super.getTraceSummaryLine(buff);
    
    buff.append(",originator=");
    buff.append(getOriginator());
    
    appendList(buff,"cellules",getCellules());
    
    appendList(buff,"costs",getCosts());
    
  }
246465
def read_with_buffer(self, command, fct=0 ,ext=0):
        
        if self.tcp:
            MAX_CHUNK = 0xFFc0
        else:
            MAX_CHUNK = 16 * 1024
        command_string = pack('<bhii', 1, command, fct, ext)
        if self.verbose: print ("rwb cs", command_string)
        response_size = 1024
        data = []
        start = 0
        cmd_response = self.__send_command(1503, command_string, response_size)
        if not cmd_response.get('status'):
            raise ZKErrorResponse("RWB Not supported")
        if cmd_response['code'] == const.CMD_DATA:
            if self.tcp:
                if self.verbose: print ("DATA! is {} bytes, tcp length is {}".format(len(self.__data), self.__tcp_length))
                if len(self.__data) < (self.__tcp_length - 8):
                    need = (self.__tcp_length - 8) - len(self.__data)
                    if self.verbose: print ("need more data: {}".format(need))
                    more_data = self.__recieve_raw_data(need)
                    return b''.join([self.__data, more_data]), len(self.__data) + len(more_data)
                else:
                    if self.verbose: print ("Enough data")
                    size = len(self.__data)
                    return self.__data, size
            else:
                size = len(self.__data)
                return self.__data, size
        size = unpack('I', self.__data[1:5])[0]
        if self.verbose: print ("size fill be %i" % size)
        remain = size % MAX_CHUNK
        packets = (size-remain) // MAX_CHUNK # should be size /16k
        if self.verbose: print ("rwb: #{} packets of max {} bytes, and extra {} bytes remain".format(packets, MAX_CHUNK, remain))
        for _wlk in range(packets):
            data.append(self.__read_chunk(start,MAX_CHUNK))
            start += MAX_CHUNK
        if remain:
            data.append(self.__read_chunk(start, remain))
            start += remain
        self.free_data()
        if self.verbose: print ("_read w/chunk %i bytes" % start)
        return b''.join(data), start
670520
def get(self, q, limit=None):
        
        uri = '{}/predict?q={}'.format(self.client.remote, q)
        self.logger.debug(uri)

        body = self.client.get(uri)
        return body['score']
505750
function read(cb) {
				if (callback) throw new Error("already getting");
				if (q.length > 0) {
						var item = q.shift();
						// recycle queue when empty to avoid maintaining arrays that have grown large and shrunk
						if (q.length === 0) q = [];
						exports.setImmediate(function () {
							cb(err, item);
						});
						if (pendingWrites.length > 0) {
								var wr = pendingWrites.shift();
								exports.setImmediate(function () {
									wr[0](err, wr[1]);
								});
							}
					} else {
						callback = cb;
					}
			}
700497
def get_outputs_from_cm(index, cm):
    """"""
    return tuple(i for i in range(cm.shape[0]) if cm[index][i])
1134379
def _get_maxcov_downsample(data):
    
    from bcbio.bam import ref
    from bcbio.ngsalign import alignprep, bwa
    from bcbio.variation import coverage
    fastq_file = data["files"][0]
    params = alignprep.get_downsample_params(data)
    if params:
        num_reads = alignprep.total_reads_from_grabix(fastq_file)
        if num_reads:
            vrs = dd.get_variant_regions_merged(data)
            total_size = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])])
            if vrs:
                callable_size = pybedtools.BedTool(vrs).total_coverage()
                genome_cov_pct = callable_size / float(total_size)
            else:
                callable_size = total_size
                genome_cov_pct = 1.0
            if (genome_cov_pct > coverage.GENOME_COV_THRESH
                  and dd.get_coverage_interval(data) in ["genome", None, False]):
                total_counts, total_sizes = 0, 0
                for count, size in bwa.fastq_size_output(fastq_file, 5000):
                    total_counts += int(count)
                    total_sizes += (int(size) * int(count))
                read_size = float(total_sizes) / float(total_counts)
                avg_cov = float(num_reads * read_size) / callable_size
                if avg_cov >= params["min_coverage_for_downsampling"]:
                    return int(avg_cov * params["maxcov_downsample_multiplier"])
    return None
1010297
def get_argument_parser():
    
    file_mv = cli.file_mv

    desc = 'Extracts gene-level expression data from StringTie output.'
    parser = cli.get_argument_parser(desc)

    parser.add_argument(
        '-s', '--stringtie-file', type=str, required=True, metavar=file_mv,
        help="""Path of the StringTie output file ."""
    )

    parser.add_argument(
        '-g', '--gene-file', type=str, required=True, metavar=file_mv,
        help="""File containing a list of protein-coding genes."""
    )

    parser.add_argument(
        '--no-novel-transcripts', action='store_true',
        help="""Ignore novel transcripts."""
    )

    # parser.add_argument(
    #     '--ambiguous-transcripts', default = 'ignore',
    #      help='Strategy for counting expression of ambiguous novel '
    #            'transcripts.'
    # )
    # possible strategies for ambiguous transcripts: 'ignore','highest','all'

    parser.add_argument(
        '-o', '--output-file', type=str, required=True, metavar=file_mv,
        help="""Path of output file."""
    )

    cli.add_reporting_args(parser)

    return parser
981869
def GetInput(self):
    """"""
    clients = GetAllClients(token=self.token)
    logging.debug("Got %d clients", len(clients))
    return clients
333468
def expressionLevelsGenerator(self, request):
        
        rnaQuantificationId = request.rna_quantification_id
        compoundId = datamodel.RnaQuantificationCompoundId.parse(
            request.rna_quantification_id)
        dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
        rnaQuantSet = dataset.getRnaQuantificationSet(
            compoundId.rna_quantification_set_id)
        rnaQuant = rnaQuantSet.getRnaQuantification(rnaQuantificationId)
        rnaQuantificationId = rnaQuant.getLocalId()
        iterator = paging.ExpressionLevelsIterator(
            request, rnaQuant)
        return iterator
236733
def set_CCLE_context(self, cell_types):
        """"""
        self.get_gene_names()

        # Get expression and mutations from context client
        exp_values = \
            context_client.get_protein_expression(self._gene_names, cell_types)
        mut_values = \
            context_client.get_mutations(self._gene_names, cell_types)

        # Make a dict of presence/absence of mutations
        muts = {cell_line: {} for cell_line in cell_types}
        for cell_line, entries in mut_values.items():
            if entries is not None:
                for gene, mutations in entries.items():
                    if mutations:
                        muts[cell_line][gene] = 1
                    else:
                        muts[cell_line][gene] = 0

        # Create bins for the exp values
        # because colorbrewer only does 3-9 bins and I don't feel like
        # reinventing color scheme theory, this will only bin 3-9 bins
        def bin_exp(expression_dict):
            d = expression_dict
            exp_values = []
            for line in d:
                for gene in d[line]:
                    val = d[line][gene]
                    if val is not None:
                        exp_values.append(val)
            thr_dict = {}
            for n_bins in range(3, 10):
                bin_thr = np.histogram(np.log10(exp_values), n_bins)[1][1:]
                thr_dict[n_bins] = bin_thr
            # this dict isn't yet binned, that happens in the loop
            binned_dict = {x: deepcopy(expression_dict) for x in range(3, 10)}
            for n_bins in binned_dict:
                for line in binned_dict[n_bins]:
                    for gene in binned_dict[n_bins][line]:
                        # last bin is reserved for None
                        if binned_dict[n_bins][line][gene] is None:
                            binned_dict[n_bins][line][gene] = n_bins
                        else:
                            val = np.log10(binned_dict[n_bins][line][gene])
                            for thr_idx, thr in enumerate(thr_dict[n_bins]):
                                if val <= thr:
                                    binned_dict[n_bins][line][gene] = thr_idx
                                    break
            return binned_dict
        binned_exp = bin_exp(exp_values)

        context = {'bin_expression': binned_exp,
                   'mutation': muts}
        self._context['CCLE'] = context
837432
function readInput(cb, filename) {

    function readFile() {
      fs.readFile(filename, 'utf8', function (err, text) {
        if (err) {
          console.error("[ERROR] couldn't read from '" + filename + "':");
          console.error(err.message);
          return;
        }

        cb(err, text);
      });
    }

    function readStdin() {
      var text = ''
        , stdin = process.stdin
        ;

      stdin.resume();

      stdin.on('data', function (chunk) {
        text += chunk;
      });

      stdin.on('end', function () {
        cb(null, text);
      });
    }

    if (filename) {
      readFile();
    }
    else {
      readStdin();
    }

  }
545071
def ccEstablishment():
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x4)  # 00000100
    c = SetupContainer()
    packet = a / b / c
    return packet
727270
def content_bytes(self):
        """"""
        get_message = \
            self._communication.needle_positions.get_line_configuration_message
        return get_message(self._line_number)
72666
public void getData(final String path, Watcher watcher, DataCallback cb,
            Object ctx) {
        verbotenThreadCheck();
        final String clientPath = path;
        PathUtils.validatePath(clientPath);

        // the watch contains the un-chroot path
        WatchRegistration wcb = null;
        if (watcher != null) {
            wcb = new DataWatchRegistration(watcher, clientPath);
        }

        final String serverPath = prependChroot(clientPath);

        RequestHeader h = new RequestHeader();
        h.setType(ZooDefs.OpCode.getData);
        GetDataRequest request = new GetDataRequest();
        request.setPath(serverPath);
        request.setWatch(watcher != null);
        GetDataResponse response = new GetDataResponse();
        cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
                clientPath, serverPath, ctx, wcb);
    }
61158
def get_regulate_amounts(self):
        """"""
        qstr = "$.events.frames[(@.type is 'transcription')]"
        res = self.tree.execute(qstr)
        all_res = []
        if res is not None:
            all_res += list(res)
        qstr = "$.events.frames[(@.type is 'amount')]"
        res = self.tree.execute(qstr)
        if res is not None:
            all_res += list(res)

        for r in all_res:
            subtype = r.get('subtype')
            epistemics = self._get_epistemics(r)
            if epistemics.get('negated'):
                continue
            annotations, context = self._get_annot_context(r)
            frame_id = r['frame_id']
            args = r['arguments']
            theme = None
            for a in args:
                if self._get_arg_type(a) == 'theme':
                    theme = a['arg']
                    break
            if theme is None:
                continue
            theme_agent, theme_coords = self._get_agent_from_entity(theme)
            qstr = "$.events.frames[(@.type is 'regulation') and " + \
                   "(@.arguments[0].arg is '%s')]" % frame_id
            reg_res = self.tree.execute(qstr)
            for reg in reg_res:
                controller_agent, controller_coords = None, None
                for a in reg['arguments']:
                    if self._get_arg_type(a) == 'controller':
                        controller_agent, controller_coords = \
                            self._get_controller_agent(a)
                sentence = reg['verbose-text']
                annotations['agents']['coords'] = [controller_coords,
                                                   theme_coords]
                ev = Evidence(source_api='reach', text=sentence,
                              annotations=annotations, pmid=self.citation,
                              context=context, epistemics=epistemics)
                args = [controller_agent, theme_agent, ev]
                subtype = reg.get('subtype')
                if subtype == 'positive-regulation':
                    st = IncreaseAmount(*args)
                else:
                    st = DecreaseAmount(*args)
                self.statements.append(st)