Precipitation Read from File Method
976733
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Dictionary of keywords/cards and parse function names
        KEYWORDS = ('EVENT',)

        # Parse file into chunks associated with keywords/cards
        with open(path, 'r') as f:
            chunks = pt.chunk(KEYWORDS, f)

        # Parse chunks associated with each key
        for key, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                result = gak.eventChunk(key, chunk)
                self._createGsshaPyObjects(result)

        # Add this PrecipFile to the database session
        session.add(self)
1151401
def parse_json_data(content, raincontent, latitude=52.091579,
                    longitude=5.119734, timeframe=60):
    """"""
    result = {SUCCESS: False, MESSAGE: None, DATA: None}

    if timeframe < 5 or timeframe > 120:
        raise ValueError("Timeframe must be >=5 and <=120.")

    if content is not None:
        try:
            json_content = json.loads(content)
        except json.JSONDecodeError as err:
            result[MESSAGE] = "Unable to parse content as json."
            log.error("Unable to parse content as json. %s", err)
            return result

        result = __parse_ws_data(json_content, latitude, longitude)

        if result[SUCCESS] and raincontent is not None:
            data = __parse_precipfc_data(raincontent, timeframe)
            result[DATA][PRECIPITATION_FORECAST] = data

    log.debug("Extracted weather-data: %s", result[DATA])
    return result
1172639
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Open file and parse into a data structure
        with io_open(path, 'r') as f:
            self.projection = f.read()
519414
def _make_read_func(file_obj):
    """"""
    @ffi.callback("cairo_read_func_t", error=constants.STATUS_READ_ERROR)
    def read_func(_closure, data, length):
        string = file_obj.read(length)
        if len(string) < length:  # EOF too early
            return constants.STATUS_READ_ERROR
        ffi.buffer(data, length)[:len(string)] = string
        return constants.STATUS_SUCCESS
    return read_func
58041
def __parse_fc_data(fc_data):
    """"""
    fc = []
    for day in fc_data:
        fcdata = {
            CONDITION: __cond_from_desc(
                __get_str(
                    day,
                    __WEATHERDESCRIPTION)
            ),
            TEMPERATURE: __get_float(day, __MAXTEMPERATURE),
            MIN_TEMP: __get_float(day, __MINTEMPERATURE),
            MAX_TEMP: __get_float(day, __MAXTEMPERATURE),
            SUN_CHANCE: __get_int(day, __SUNCHANCE),
            RAIN_CHANCE: __get_int(day, __RAINCHANCE),
            RAIN: __get_float(day, __MMRAINMAX),
            MIN_RAIN: __get_float(day, __MMRAINMIN),  # new
            MAX_RAIN: __get_float(day, __MMRAINMAX),  # new
            SNOW: 0,  # for compatibility
            WINDFORCE: __get_int(day, __WIND),
            WINDDIRECTION: __get_str(day, __WINDDIRECTION),      # new
            DATETIME: __to_localdatetime(__get_str(day, __DAY)),
        }
        fcdata[CONDITION][IMAGE] = day[__ICONURL]

        fc.append(fcdata)
    return fc
1250802
@Override
    public void writeFile(String arg0, Map result) {

        long estTime = 0;

        try {
            if (getObjectOr(result, "experiments", new ArrayList()).isEmpty()
                    && getObjectOr(result, "soils", new ArrayList()).isEmpty()
                    && getObjectOr(result, "weathers", new ArrayList()).isEmpty()) {

                // Calculate estimated time consume
                HashMap wth = getObjectOr(result, "weather", new HashMap());
                estTime += getObjectOr(wth, "dailyWeather", new ArrayList()).size();

                // Write files
                recordSWData(result, new DssatSoilOutput());
                recordSWData(result, new DssatWeatherOutput());
                writeWthFiles(arg0);
                writeSoilFiles(arg0);
                String exname = getValueOr(result, "exname", "N/A");
                writeSingleExp(arg0, result, new DssatXFileOutput(), exname + "_X");
                writeSingleExp(arg0, result, new DssatAFileOutput(), exname + "_A");
                writeSingleExp(arg0, result, new DssatTFileOutput(), exname + "_T");
                writeSingleExp(arg0, result, new DssatCulFileOutput(), exname + "_Cul");
                writeSingleExp(arg0, result, new DssatBatchFileOutput(DssatVersion.DSSAT45), "DSSBatch.v45");
                writeSingleExp(arg0, result, new DssatBatchFileOutput(DssatVersion.DSSAT46), "DSSBatch.v46");
                writeSingleExp(arg0, result, new DssatRunFileOutput(DssatVersion.DSSAT45), "Run45.bat");
                writeSingleExp(arg0, result, new DssatRunFileOutput(DssatVersion.DSSAT46), "Run46.bat");

                // compress all output files into one zip file
                outputFile = new File(revisePath(arg0) + exname + ".ZIP");

                //createZip();
            } else {
                // Calculate estimated time consume
                for (HashMap wth : (ArrayList<HashMap>) getObjectOr(result, "weathers", new ArrayList<HashMap>())) {
                    estTime += getObjectOr(wth, "dailyWeather", new ArrayList()).size();
                }
                writeMultipleExp(arg0, result);
            }

            if (estTime > 0) {
                estTime *= 10;
            } else {
                estTime = 10000;
            }

            executor.shutdown();
            long timer = System.currentTimeMillis();
            HashSet<String> keys = new HashSet(futFiles.keySet());
            int counter = 0;
            while (!executor.isTerminated()) {
                if (System.currentTimeMillis() - timer > estTime) {
                    counter++;
                    timer = System.currentTimeMillis();
                    if (keys.isEmpty()) {
                        LOG.info("The executor should be terminated");
                        executor.shutdownNow();
                    } else if (counter > 3) {
                        LOG.info("The executor is going to be force terminated");
                        executor.shutdownNow();
                    }
                    String[] arr = keys.toArray(new String[0]);
                    for (String key : arr) {
                        Future futFile = futFiles.get(key);
                        if (futFile.isCancelled() || futFile.isDone()) {
                            keys.remove(key);
                        } else {
                            LOG.info("DSSAT translation for {} is still under processing...", key);
                        }
                    }
                }
            }
            executor = null;
            LOG.debug("Consume {} s", (System.currentTimeMillis() - timer) / 1000.0);

            // Get output result files into output array
            for (String key : futFiles.keySet()) {
                try {
                    File f = futFiles.get(key).get();
                    if (f != null) {
                        files.put(f.getPath(), f);
                    }
                } catch (InterruptedException ex) {
                    LOG.error(getStackTrace(ex));
                } catch (ExecutionException ex) {
                    if (!ex.getMessage().contains("NoOutputFileException")) {
                        LOG.error(getStackTrace(ex));
                    }
                }
            }

        } catch (FileNotFoundException e) {
            LOG.error(getStackTrace(e));
        } catch (IOException e) {
            LOG.error(getStackTrace(e));
        }
    }
1244274
private String readFileAsString(File file) throws java.io.IOException {
        StringBuilder fileData = new StringBuilder(1000);
        try (BufferedReader reader = new BufferedReader(ReaderFactory.newReader(file, this.encoding))) {
            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
        }
        return fileData.toString();
    }
160396
def read_dew_point(self, t=None, rh=None):
		''
		if t is None: t, rh = self.read_t(), None
		if rh is None: rh = self.read_rh(t)
		t_range = 'water' if t >= 0 else 'ice'
		tn, m = self.c.tn[t_range], self.c.m[t_range]
		return ( # ch 4.4
			tn * (math.log(rh / 100.0) + (m * t) / (tn + t))
			/ (m - math.log(rh / 100.0) - m * t / (tn + t)) )
803242
private void readChunkIfNeeded() {
        if (workBufferSize > workBufferPosition) {
            return;
        }
        if (workBuffer == null) {
            workBuffer = bitmapProvider.obtainByteArray(WORK_BUFFER_SIZE);
        }
        workBufferPosition = 0;
        workBufferSize = Math.min(rawData.remaining(), WORK_BUFFER_SIZE);
        rawData.get(workBuffer, 0, workBufferSize);
    }
1203036
protected function readFromTempFile()
    {
        // Upload temp file
        $sUploadTempFile = $this->getUploadTempFile();
        $aFiles = json_decode(file_get_contents($sUploadTempFile), true);
        foreach($aFiles as $sVarName => $aUserFiles)
        {
            $this->aUserFiles[$sVarName] = [];
            foreach($aUserFiles as $aUserFile)
            {
                $this->aUserFiles[$sVarName][] = UploadedFile::fromTempData($aUserFile);
            }
        }
        unlink($sUploadTempFile);
    }
419603
public void readFrom (File source)
        throws IOException
    {
        // slurp our source file into newline separated strings
        _lines = Lists.newArrayList();
        BufferedReader bin = new BufferedReader(new FileReader(source));
        String line = null;
        while ((line = bin.readLine()) != null) {
            _lines.add(line);
        }
        bin.close();

        // now determine where to insert our static field declarations and our generated methods
        int bstart = -1, bend = -1;
        for (int ii = 0, nn = _lines.size(); ii < nn; ii++) {
            line = _lines.get(ii).trim();

            // look for the start of the class body
            if (GenUtil.NAME_PATTERN.matcher(line).find()) {
                if (line.endsWith("{")) {
                    bstart = ii+1;
                } else {
                    // search down a few lines for the open brace
                    for (int oo = 1; oo < 10; oo++) {
                        if (safeGetLine(ii+oo).trim().endsWith("{")) {
                            bstart = ii+oo+1;
                            break;
                        }
                    }
                }

            // track the last } on a line by itself and we'll call that the end of the class body
            } else if (line.equals("}")) {
                bend = ii;

            // look for our field and method markers
            } else if (line.equals(FIELDS_START)) {
                _nstart = ii;
            } else if (line.equals(FIELDS_END)) {
                _nend = ii+1;
            } else if (line.equals(METHODS_START)) {
                _mstart = ii;
            } else if (line.equals(METHODS_END)) {
                _mend = ii+1;
            }
        }

        // sanity check the markers
        check(source, "fields start", _nstart, "fields end", _nend);
        check(source, "fields end", _nend, "fields start", _nstart);
        check(source, "methods start", _mstart, "methods end", _mend);
        check(source, "methods end", _mend, "methods start", _mstart);

        // we have no previous markers then stuff the fields at the top of the class body and the
        // methods at the bottom
        if (_nstart == -1) {
            _nstart = bstart;
            _nend = bstart;
        }
        if (_mstart == -1) {
            _mstart = bend;
            _mend = bend;
        }
    }
1109097
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Dictionary of keywords/cards and parse function names
        KEYWORDS = {'CONNECT': spc.connectChunk,
                    'SJUNC': spc.sjuncChunk,
                    'SLINK': spc.slinkChunk}

        sjuncs = []
        slinks = []
        connections = []

        # Parse file into chunks associated with keywords/cards
        with open(path, 'r') as f:
            chunks = pt.chunk(KEYWORDS, f)

        # Parse chunks associated with each key
        for key, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                # Call chunk specific parsers for each chunk
                result = KEYWORDS[key](key, chunk)

                # Cases
                if key == 'CONNECT':
                    connections.append(result)
                elif key == 'SJUNC':
                    sjuncs.append(result)
                elif key == 'SLINK':
                    slinks.append(result)

        # Create GSSHAPY objects
        self._createConnection(connections)
        self._createSjunc(sjuncs)
        self._createSlink(slinks)
672200
def _read_temp(data):
    '''
    
    '''
    tout = StringIO()
    tout.write(data)
    tout.seek(0)
    output = tout.readlines()
    tout.close()

    return output
836558
function readFile(file, callback){

		// Run this sequentially
		sync(function(){
			// Create a new FileReader Object
			var reader = new FileReader();

			// Set an onload handler because we load files into it Asynchronously
			reader.onload = function(e){

				// Print onto Canvas
				callback( this.result );

				// Run the next one;
				sync();
			};

			reader.readAsDataURL(file);
		});
	}
1249864
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Keywords
        KEYWORDS = ('STREAMCELLS',
                    'CELLIJ')

        # Parse file into chunks associated with keywords/cards
        with open(path, 'r') as f:
            chunks = pt.chunk(KEYWORDS, f)

        # Parse chunks associated with each key
        for key, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:

                # Cases
                if key == 'STREAMCELLS':
                    # PIPECELLS Handler
                    schunk = chunk[0].strip().split()
                    self.streamCells = schunk[1]

                elif key == 'CELLIJ':
                    # CELLIJ Handler
                    # Parse CELLIJ Chunk
                    result = self._cellChunk(chunk)

                    # Create GSSHAPY object
                    self._createGsshaPyObjects(result)
1370629
def read(varin, fname='MS2_L10.mat.txt'):
    '''

    '''

    # # fname = 'MS09_L10.mat.txt'
    # # fname = 'MS09_L05.mat.txt' # has PAR
    # fname = 'MS2_L10.mat.txt' # empty PAR

    d = np.loadtxt(fname, comments='*')

    if fname == 'MS2_L10.mat.txt':
        var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen',
               'voltage 2', 'voltage 3', 'fluorescence-CDOM', 'fluorescence-ECO',
               'turbidity', 'pressure', 'salinity', 'RINKO temperature',
               'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR']
    elif (fname == 'MS09_L05.mat.txt') or (fname == 'MS09_L10.mat.txt') or (fname == 'MS08_L12.mat.txt'):
        var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen',
               'voltage 2', 'voltage 3', 'voltage 4', 'fluorescence-CDOM', 'fluorescence-ECO',
               'turbidity', 'pressure', 'salinity', 'RINKO temperature',
               'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR']

    # return data for variable varin
    return d[:, 0], d[:, 1], d[:, 2], d[:, var.index(varin)]
880832
private static byte[] readFileAtOnce(final FileInputStream fIn) throws IOException {
		final byte[] ret = new byte[fIn.available()];
		fIn.read(ret);
		fIn.close();
		return ret;
	}