_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q225200
OneLogin_Saml2_IdPMetadataParser.get_metadata
train
def get_metadata(url, validate_cert=True): """ Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verificati...
python
{ "resource": "" }
q225201
print_xmlsec_errors
train
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg): """ Auxiliary method. It overrides the default xmlsec debug message. """ info = [] if error_object != "unknown": info.append("obj=" + error_object) if error_subject != "unknown": info.append...
python
{ "resource": "" }
q225202
OneLogin_Saml2_Utils.get_self_host
train
def get_self_host(request_data): """ Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string """ if 'http_host' in request_data: current_host = request_data['http_host'] ...
python
{ "resource": "" }
q225203
OneLogin_Saml2_Utils.parse_duration
train
def parse_duration(duration, timestamp=None): """ Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optiona...
python
{ "resource": "" }
q225204
OneLogin_Saml2_Utils.get_status
train
def get_status(dom): """ Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict """ status = {} status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp...
python
{ "resource": "" }
q225205
OneLogin_Saml2_Utils.write_temp_file
train
def write_temp_file(content): """ Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object """ f_temp = NamedTemporaryFile(delete=True) f_temp.f...
python
{ "resource": "" }
q225206
OneLogin_Saml2_Settings.__add_default_values
train
def __add_default_values(self): """ Add default values if the settings info is not complete """ self.__sp.setdefault('assertionConsumerService', {}) self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST) self.__sp.setdefau...
python
{ "resource": "" }
q225207
OneLogin_Saml2_Auth.login
train
def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None): """ Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param ...
python
{ "resource": "" }
q225208
OneLogin_Saml2_Auth.logout
train
def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None): """ Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID...
python
{ "resource": "" }
q225209
OneLogin_Saml2_Auth.get_slo_url
train
def get_slo_url(self): """ Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string """ url = None idp_data = self.__settings.get_idp_data() if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']: ...
python
{ "resource": "" }
q225210
add_pyspark_path
train
def add_pyspark_path(): """Add PySpark to the library path based on the value of SPARK_HOME. """ try: spark_home = os.environ['SPARK_HOME'] sys.path.append(os.path.join(spark_home, 'python')) py4j_src_zip = glob(os.path.join(spark_home, 'python', ...
python
{ "resource": "" }
q225211
datetime_to_nanos
train
def datetime_to_nanos(dt): """ Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch. """ if isinstance(dt, pd.Timestamp): return dt.value elif isinstance(dt, str): return pd.Timestamp(dt).value elif isinstance(dt, long): return dt elif isinst...
python
{ "resource": "" }
q225212
uniform
train
def uniform(start, end=None, periods=None, freq=None, sc=None): """ Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas...
python
{ "resource": "" }
q225213
DateTimeIndex._zdt_to_nanos
train
def _zdt_to_nanos(self, zdt): """Extracts nanoseconds from a ZonedDateTime""" instant = zdt.toInstant() return instant.getNano() + instant.getEpochSecond() * 1000000000
python
{ "resource": "" }
q225214
DateTimeIndex.datetime_at_loc
train
def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))
python
{ "resource": "" }
q225215
DateTimeIndex.islice
train
def islice(self, start, end): """ Returns a new DateTimeIndex, containing a subslice of the timestamps in this index, as specified by the given integer start and end locations. Parameters ---------- start : int The location of the start of the range, inclusiv...
python
{ "resource": "" }
q225216
fit_model
train
def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None): """ Fit an autoregressive model with additional exogenous variables. The model predicts a value at time t of a dependent variable, Y, as a function of previous values of Y, and a combination of previous values of ...
python
{ "resource": "" }
q225217
time_series_rdd_from_pandas_series_rdd
train
def time_series_rdd_from_pandas_series_rdd(series_rdd): """ Instantiates a TimeSeriesRDD from an RDD of Pandas Series objects. The series in the RDD are all expected to have the same DatetimeIndex. Parameters ---------- series_rdd : RDD of (string, pandas.Series) tuples sc : SparkContext ...
python
{ "resource": "" }
q225218
time_series_rdd_from_observations
train
def time_series_rdd_from_observations(dt_index, df, ts_col, key_col, val_col): """ Instantiates a TimeSeriesRDD from a DataFrame of observations. An observation is a row containing a timestamp, a string key, and float value. Parameters ---------- dt_index : DateTimeIndex The index of t...
python
{ "resource": "" }
q225219
TimeSeriesRDD.map_series
train
def map_series(self, fn, dt_index = None): """ Returns a TimeSeriesRDD, with a transformation applied to all the series in this RDD. Either the series produced by the given function should conform to this TimeSeriesRDD's index, or a new DateTimeIndex should be given that they conform to...
python
{ "resource": "" }
q225220
TimeSeriesRDD.to_instants
train
def to_instants(self): """ Returns an RDD of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing an RDD of tuples of datetime and a numpy array containing all the observations that occurred at that time. """...
python
{ "resource": "" }
q225221
TimeSeriesRDD.to_instants_dataframe
train
def to_instants_dataframe(self, sql_ctx): """ Returns a DataFrame of instants, each a horizontal slice of this TimeSeriesRDD at a time. This essentially transposes the TimeSeriesRDD, producing a DataFrame where each column is a key form one of the rows in the TimeSeriesRDD. """ ...
python
{ "resource": "" }
q225222
TimeSeriesRDD.to_observations_dataframe
train
def to_observations_dataframe(self, sql_ctx, ts_col='timestamp', key_col='key', val_col='value'): """ Returns a DataFrame of observations, each containing a timestamp, a key, and a value. Parameters ---------- sql_ctx : SQLContext ts_col : string The name for...
python
{ "resource": "" }
q225223
TimeSeriesRDD.to_pandas_series_rdd
train
def to_pandas_series_rdd(self): """ Returns an RDD of Pandas Series objects indexed with Pandas DatetimeIndexes """ pd_index = self.index().to_pandas_index() return self.map(lambda x: (x[0], pd.Series(x[1], pd_index)))
python
{ "resource": "" }
q225224
TimeSeriesRDD.to_pandas_dataframe
train
def to_pandas_dataframe(self): """ Pulls the contents of the RDD to the driver and places them in a Pandas DataFrame. Each record in the RDD becomes and column, and the DataFrame is indexed with a DatetimeIndex generated from this RDD's index. """ pd_index = self...
python
{ "resource": "" }
q225225
Row._SetHeader
train
def _SetHeader(self, values): """Set the row's header from a list.""" if self._values and len(values) != len(self._values): raise ValueError('Header values not equal to existing data width.') if not self._values: for _ in range(len(values)): self._values.append(None) self._keys = lis...
python
{ "resource": "" }
q225226
Row._SetValues
train
def _SetValues(self, values): """Set values from supplied dictionary or list. Args: values: A Row, dict indexed by column name, or list. Raises: TypeError: Argument is not a list or dict, or list is not equal row length or dictionary keys don't match. """ def _ToStr(value): ...
python
{ "resource": "" }
q225227
TextTable.Filter
train
def Filter(self, function=None): """Construct Textable from the rows of which the function returns true. Args: function: A function applied to each row which returns a bool. If function is None, all rows with empty column values are removed. Returns: A new TextT...
python
{ "resource": "" }
q225228
TextTable._GetTable
train
def _GetTable(self): """Returns table, with column headers and separators. Returns: The whole table including headers as a string. Each row is joined by a newline and each entry by self.separator. """ result = [] # Avoid the global lookup cost on each iteration. lstr = str for r...
python
{ "resource": "" }
q225229
TextTable._SetTable
train
def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselv...
python
{ "resource": "" }
q225230
TextTable._TextJustify
train
def _TextJustify(self, text, col_size): """Formats text within column with white space padding. A single space is prefixed, and a number of spaces are added as a suffix such that the length of the resultant string equals the col_size. If the length of the text exceeds the column width available then i...
python
{ "resource": "" }
q225231
TextTable.index
train
def index(self, name=None): # pylint: disable=C6409 """Returns index number of supplied column name. Args: name: string of column name. Raises: TableError: If name not found. Returns: Index of the specified header entry. """ try: return self.header.index(name) exc...
python
{ "resource": "" }
q225232
CliTable._ParseCmdItem
train
def _ParseCmdItem(self, cmd_input, template_file=None): """Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template wa...
python
{ "resource": "" }
q225233
CliTable._Completion
train
def _Completion(self, match): # pylint: disable=C6114 r"""Replaces double square brackets with variable length completion. Completion cannot be mixed with regexp matching or '\' characters i.e. '[[(\n)]] would become (\(n)?)?.' Args: match: A regex Match() object. Returns: String ...
python
{ "resource": "" }
q225234
main
train
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__...
python
{ "resource": "" }
q225235
TextFSMOptions.ValidOptions
train
def ValidOptions(cls): """Returns a list of valid option names.""" valid_options = [] for obj_name in dir(cls): obj = getattr(cls, obj_name) if inspect.isclass(obj) and issubclass(obj, cls.OptionBase): valid_options.append(obj_name) return valid_options
python
{ "resource": "" }
q225236
TextFSMValue.Header
train
def Header(self): """Fetch the header name of this Value.""" # Call OnGetValue on options. _ = [option.OnGetValue() for option in self.options] return self.name
python
{ "resource": "" }
q225237
TextFSMValue._AddOption
train
def _AddOption(self, name): """Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist. """ # Check for duplicate option declaration if name in [option.name for o...
python
{ "resource": "" }
q225238
TextFSM.Reset
train
def Reset(self): """Preserves FSM but resets starting state and current record.""" # Current state is Start state. self._cur_state = self.states['Start'] self._cur_state_name = 'Start' # Clear table of results and current record. self._result = [] self._ClearAllRecord()
python
{ "resource": "" }
q225239
TextFSM._GetHeader
train
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
python
{ "resource": "" }
q225240
TextFSM._GetValue
train
def _GetValue(self, name): """Returns the TextFSMValue object natching the requested name.""" for value in self.values: if value.name == name: return value
python
{ "resource": "" }
q225241
TextFSM._AppendRecord
train
def _AppendRecord(self): """Adds current record to result if well formed.""" # If no Values then don't output. if not self.values: return cur_record = [] for value in self.values: try: value.OnSaveRecord() except SkipRecord: self._ClearRecord() return ...
python
{ "resource": "" }
q225242
TextFSM._Parse
train
def _Parse(self, template): """Parses template file for FSM structure. Args: template: Valid template file. Raises: TextFSMTemplateError: If template file syntax is invalid. """ if not template: raise TextFSMTemplateError('Null template.') # Parse header with Variables. ...
python
{ "resource": "" }
q225243
TextFSM._ParseFSMVariables
train
def _ParseFSMVariables(self, template): """Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the to...
python
{ "resource": "" }
q225244
TextFSM._ParseFSMState
train
def _ParseFSMState(self, template): """Extracts State and associated Rules from body of template file. After the Value definitions the remainder of the template is state definitions. The routine is expected to be called iteratively until no more states remain - indicated by returning None. The rou...
python
{ "resource": "" }
q225245
TextFSM._ValidateFSM
train
def _ValidateFSM(self): """Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Returns: True if FSM is valid. Ra...
python
{ "resource": "" }
q225246
TextFSM.ParseText
train
def ParseText(self, text, eof=True): """Passes CLI output through FSM and returns list of tuples. First tuple is the header, every subsequent tuple is a row. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. ...
python
{ "resource": "" }
q225247
TextFSM.ParseTextToDicts
train
def ParseTextToDicts(self, *args, **kwargs): """Calls ParseText and turns the result into list of dicts. List items are dicts of rows, dict key is column header and value is column value. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsin...
python
{ "resource": "" }
q225248
TextFSM._AssignVar
train
def _AssignVar(self, matched, value): """Assigns variable into current record from a matched rule. If a record entry is a list then append, otherwise values are replaced. Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value. """ _value = self...
python
{ "resource": "" }
q225249
TextFSM._Operations
train
def _Operations(self, rule, line): """Operators on the data record. Operators come in two parts and are a '.' separated pair: Operators that effect the input line or the current state (line_op). 'Next' Get next input line and restart parsing (default). 'Continue' Keep current input...
python
{ "resource": "" }
q225250
TextFSM.GetValuesByAttrib
train
def GetValuesByAttrib(self, attribute): """Returns the list of values that have a particular attribute.""" if attribute not in self._options_cls.ValidOptions(): raise ValueError("'%s': Not a valid attribute." % attribute) result = [] for value in self.values: if attribute in value.OptionNa...
python
{ "resource": "" }
q225251
_AnsiCmd
train
def _AnsiCmd(command_list): """Takes a list of SGR values and formats them as an ANSI escape sequence. Args: command_list: List of strings, each string represents an SGR value. e.g. 'fg_blue', 'bg_yellow' Returns: The ANSI escape sequence. Raises: ValueError: if a member of command_list d...
python
{ "resource": "" }
q225252
TerminalSize
train
def TerminalSize(): """Returns terminal length and width as a tuple.""" try: with open(os.ctermid(), 'r') as tty_instance: length_width = struct.unpack( 'hh', fcntl.ioctl(tty_instance.fileno(), termios.TIOCGWINSZ, '1234')) except (IOError, OSError): try: length_width = (int(os.enviro...
python
{ "resource": "" }
q225253
main
train
def main(argv=None): """Routine to page text or determine window size via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size']) except getopt.error as msg: raise Usage(msg) # Print usage and return, regardless of presence...
python
{ "resource": "" }
q225254
Pager.Reset
train
def Reset(self): """Reset the pager to the top of the text.""" self._displayed = 0 self._currentpagelines = 0 self._lastscroll = 1 self._lines_to_show = self._cli_lines
python
{ "resource": "" }
q225255
Pager.SetLines
train
def SetLines(self, lines): """Set number of screen lines. Args: lines: An int, number of lines. If None, use terminal dimensions. Raises: ValueError, TypeError: Not a valid integer representation. """ (self._cli_lines, self._cli_cols) = TerminalSize() if lines: self._cli_li...
python
{ "resource": "" }
q225256
Pager.Page
train
def Page(self, text=None, show_percent=None): """Page text. Continues to page through any text supplied in the constructor. Also, any text supplied to this method will be appended to the total text to be displayed. The method returns when all available text has been displayed to the user, or the us...
python
{ "resource": "" }
q225257
Pager._Scroll
train
def _Scroll(self, lines=None): """Set attributes to scroll the buffer correctly. Args: lines: An int, number of lines to scroll. If None, scrolls by the terminal length. """ if lines is None: lines = self._cli_lines if lines < 0: self._displayed -= self._cli_lines s...
python
{ "resource": "" }
q225258
Pager._AskUser
train
def _AskUser(self): """Prompt the user for the next action. Returns: A string, the character entered by the user. """ if self._show_percent: progress = int(self._displayed*100 / (len(self._text.splitlines()))) progress_text = ' (%d%%)' % progress else: progress_text = '' ...
python
{ "resource": "" }
q225259
Pager._GetCh
train
def _GetCh(self): """Read a single character from the user. Returns: A string, the character read. """ fd = self._tty.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) ch = self._tty.read(1) # Also support arrow key shortcuts (escape + 2 chars) if ord(ch) ==...
python
{ "resource": "" }
q225260
add_deflection
train
def add_deflection(position, observer, ephemeris, t, include_earth_deflection, count=3): """Update `position` for how solar system masses will deflect its light. Given the ICRS `position` [x,y,z] of an object (au) that is being viewed from the `observer` also expressed as [x,y,z], and gi...
python
{ "resource": "" }
q225261
_add_deflection
train
def _add_deflection(position, observer, deflector, rmass): """Correct a position vector for how one particular mass deflects light. Given the ICRS `position` [x,y,z] of an object (AU) together with the positions of an `observer` and a `deflector` of reciprocal mass `rmass`, this function updates `posit...
python
{ "resource": "" }
q225262
add_aberration
train
def add_aberration(position, velocity, light_time): """Correct a relative position vector for aberration of light. Given the relative `position` [x,y,z] of an object (AU) from a particular observer, the `velocity` [dx,dy,dz] at which the observer is traveling (AU/day), and the light propagation delay `...
python
{ "resource": "" }
q225263
_center
train
def _center(code, segment_dict): """Starting with `code`, follow segments from target to center.""" while code in segment_dict: segment = segment_dict[code] yield segment code = segment.center
python
{ "resource": "" }
q225264
SpiceKernel.names
train
def names(self): """Return all target names that are valid with this kernel. >>> pprint(planets.names()) {0: ['SOLAR_SYSTEM_BARYCENTER', 'SSB', 'SOLAR SYSTEM BARYCENTER'], 1: ['MERCURY_BARYCENTER', 'MERCURY BARYCENTER'], 2: ['VENUS_BARYCENTER', 'VENUS BARYCENTER'], 3:...
python
{ "resource": "" }
q225265
SpiceKernel.decode
train
def decode(self, name): """Translate a target name into its integer code. >>> planets.decode('Venus') 299 Raises ``ValueError`` if you supply an unknown name, or ``KeyError`` if the target is missing from this kernel. You can supply an integer code if you already have ...
python
{ "resource": "" }
q225266
_search
train
def _search(mapping, filename): """Search a Loader data structure for a filename.""" result = mapping.get(filename) if result is not None: return result name, ext = os.path.splitext(filename) result = mapping.get(ext) if result is not None: for pattern, result2 in result: ...
python
{ "resource": "" }
q225267
load_file
train
def load_file(path): """Open a file on your local drive, using its extension to guess its type. This routine only works on ``.bsp`` ephemeris files right now, but will gain support for additional file types in the future. :: from skyfield.api import load_file planets = load_file('~/Downloa...
python
{ "resource": "" }
q225268
parse_deltat_data
train
def parse_deltat_data(fileobj): """Parse the United States Naval Observatory ``deltat.data`` file. Each line file gives the date and the value of Delta T:: 2016 2 1 68.1577 This function returns a 2xN array of raw Julian dates and matching Delta T values. """ array = np.loadtxt(fileob...
python
{ "resource": "" }
q225269
parse_deltat_preds
train
def parse_deltat_preds(fileobj): """Parse the United States Naval Observatory ``deltat.preds`` file. The old format supplies a floating point year, the value of Delta T, and one or two other fields:: 2015.75 67.97 0.210 0.02 The new format adds a modified Julian day as ...
python
{ "resource": "" }
q225270
parse_leap_seconds
train
def parse_leap_seconds(fileobj): """Parse the IERS file ``Leap_Second.dat``. The leap dates array can be searched with:: index = np.searchsorted(leap_dates, jd, 'right') The resulting index allows (TAI - UTC) to be fetched with:: offset = leap_offsets[index] """ lines = iter(fil...
python
{ "resource": "" }
q225271
parse_tle
train
def parse_tle(fileobj): """Parse a file of TLE satellite element sets. Builds an Earth satellite from each pair of adjacent lines in the file that start with "1 " and "2 " and have 69 or more characters each. If the preceding line is exactly 24 characters long, then it is parsed as the satellite's...
python
{ "resource": "" }
q225272
download
train
def download(url, path, verbose=None, blocksize=128*1024): """Download a file from a URL, possibly displaying a progress bar. Saves the output to the file named by `path`. If the URL cannot be downloaded or the file cannot be written, an IOError is raised. Normally, if the standard error output is a ...
python
{ "resource": "" }
q225273
Loader.tle
train
def tle(self, url, reload=False, filename=None): """Load and parse a satellite TLE file. Given a URL or a local path, this loads a file of three-line records in the common Celestrak file format, or two-line records like those from space-track.org. For a three-line element set, each firs...
python
{ "resource": "" }
q225274
Loader.open
train
def open(self, url, mode='rb', reload=False, filename=None): """Open a file, downloading it first if it does not yet exist. Unlike when you call a loader directly like ``my_loader()``, this ``my_loader.open()`` method does not attempt to parse or interpret the file; it simply returns an...
python
{ "resource": "" }
q225275
Loader.timescale
train
def timescale(self, delta_t=None): """Open or download three time scale files, returning a `Timescale`. This method is how most Skyfield users build a `Timescale` object, which is necessary for building specific `Time` objects that name specific moments. This will open or downl...
python
{ "resource": "" }
q225276
get_summary
train
def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = urllib2.urlopen(url) # retrieve the "tip" of a file at URL bsptip = bspurl.read(10**5) # first 100kB # save data in fake file object (in-memory) ...
python
{ "resource": "" }
q225277
_correct_for_light_travel_time
train
def _correct_for_light_travel_time(observer, target): """Return a light-time corrected astrometric position and velocity. Given an `observer` that is a `Barycentric` position somewhere in the solar system, compute where in the sky they will see the body `target`, by computing the light-time between the...
python
{ "resource": "" }
q225278
VectorFunction.at
train
def at(self, t): """At time ``t``, compute the target's position relative to the center. If ``t`` is an array of times, then the returned position object will specify as many positions as there were times. The kind of position returned depends on the value of the ``center`` att...
python
{ "resource": "" }
q225279
_to_array
train
def _to_array(value): """When `value` is a plain Python sequence, return it as a NumPy array.""" if hasattr(value, 'shape'): return value elif hasattr(value, '__len__'): return array(value) else: return float_(value)
python
{ "resource": "" }
q225280
julian_day
train
def julian_day(year, month=1, day=1): """Given a proleptic Gregorian calendar date, return a Julian day int.""" janfeb = month < 3 return (day + 1461 * (year + 4800 - janfeb) // 4 + 367 * (month - 2 + janfeb * 12) // 12 - 3 * ((year + 4900 - janfeb) // 100) // 4 ...
python
{ "resource": "" }
q225281
julian_date
train
def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0): """Given a proleptic Gregorian calendar date, return a Julian date float.""" return julian_day(year, month, day) - 0.5 + ( second + minute * 60.0 + hour * 3600.0) / DAY_S
python
{ "resource": "" }
q225282
tdb_minus_tt
train
def tdb_minus_tt(jd_tdb): """Computes how far TDB is in advance of TT, given TDB. Given that the two time scales never diverge by more than 2ms, TT can also be given as the argument to perform the conversion in the other direction. """ t = (jd_tdb - T0) / 36525.0 # USNO Circular 179, eq. ...
python
{ "resource": "" }
q225283
interpolate_delta_t
train
def interpolate_delta_t(delta_t_table, tt): """Return interpolated Delta T values for the times in `tt`. The 2xN table should provide TT values as element 0 and corresponding Delta T values for element 1. For times outside the range of the table, a long-term formula is used instead. """ tt_ar...
python
{ "resource": "" }
q225284
build_delta_t_table
train
def build_delta_t_table(delta_t_recent): """Build a table for interpolating Delta T. Given a 2xN array of recent Delta T values, whose element 0 is a sorted array of TT Julian dates and element 1 is Delta T values, this routine returns a more complete table by prepending two built-in data sources t...
python
{ "resource": "" }
q225285
Timescale.utc
train
def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0): """Build a `Time` from a UTC calendar date. You can either specify the date as separate components, or provide a time zone aware Python datetime. The following two calls are equivalent (the ``utc`` time zone object can ...
python
{ "resource": "" }
q225286
Timescale.tai
train
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TAI calendar date. Supply the International Atomic Time (TAI) as a proleptic Gregorian calendar date: >>> t = ts.tai(2014, 1, 18, 1, 35, 37.5) >>> t.tai ...
python
{ "resource": "" }
q225287
Timescale.tai_jd
train
def tai_jd(self, jd): """Build a `Time` from a TAI Julian date. Supply the International Atomic Time (TAI) as a Julian date: >>> t = ts.tai_jd(2456675.56640625) >>> t.tai 2456675.56640625 >>> t.tai_calendar() (2014, 1, 18, 1, 35, 37.5) """ tai =...
python
{ "resource": "" }
q225288
Timescale.tt
train
def tt(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TT calendar date. Supply the Terrestrial Time (TT) as a proleptic Gregorian calendar date: >>> t = ts.tt(2014, 1, 18, 1, 35, 37.5) >>> t.tt 2456675.566406...
python
{ "resource": "" }
q225289
Timescale.tdb
train
def tdb(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a TDB calendar date. Supply the Barycentric Dynamical Time (TDB) as a proleptic Gregorian calendar date: >>> t = ts.tdb(2014, 1, 18, 1, 35, 37.5) >>> t.tdb ...
python
{ "resource": "" }
q225290
Timescale.tdb_jd
train
def tdb_jd(self, jd): """Build a `Time` from a TDB Julian date. Supply the Barycentric Dynamical Time (TDB) as a Julian date: >>> t = ts.tdb_jd(2456675.56640625) >>> t.tdb 2456675.56640625 """ tdb = _to_array(jd) tt = tdb - tdb_minus_tt(tdb) / DAY_S ...
python
{ "resource": "" }
q225291
Timescale.ut1
train
def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0, jd=None): """Build a `Time` from a UT1 calendar date. Supply the Universal Time (UT1) as a proleptic Gregorian calendar date: >>> t = ts.ut1(2014, 1, 18, 1, 35, 37.5) >>> t.ut1 2456675.56...
python
{ "resource": "" }
q225292
Timescale.ut1_jd
train
def ut1_jd(self, jd): """Build a `Time` from UT1 a Julian date. Supply the Universal Time (UT1) as a Julian date: >>> t = ts.ut1_jd(2456675.56640625) >>> t.ut1 2456675.56640625 """ ut1 = _to_array(jd) # Estimate TT = UT1, to get a rough Delta T estimat...
python
{ "resource": "" }
q225293
Time.astimezone_and_leap_second
train
def astimezone_and_leap_second(self, tz): """Convert to a Python ``datetime`` and leap second in a timezone. Convert this time to a Python ``datetime`` and a leap second:: dt, leap_second = t.astimezone_and_leap_second(tz) The argument ``tz`` should be a timezone from the third-pa...
python
{ "resource": "" }
q225294
Time.utc_datetime_and_leap_second
train
def utc_datetime_and_leap_second(self): """Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ...
python
{ "resource": "" }
q225295
Time.utc_strftime
train
def utc_strftime(self, format): """Format the UTC time using a Python date formatting string. This internally calls the Python ``strftime()`` routine from the Standard Library ``time()`` module, for which you can find a quick reference at ``http://strftime.org/``. If this object is ...
python
{ "resource": "" }
q225296
Time._utc_year
train
def _utc_year(self): """Return a fractional UTC year, for convenience when plotting. An experiment, probably superseded by the ``J`` attribute below. """ d = self._utc_float() - 1721059.5 #d += offset C = 365 * 100 + 24 d -= 365 d += d // C - d // (4 * C...
python
{ "resource": "" }
q225297
Time._utc_float
train
def _utc_float(self): """Return UTC as a floating point Julian date.""" tai = self.tai leap_dates = self.ts.leap_dates leap_offsets = self.ts.leap_offsets leap_reverse_dates = leap_dates + leap_offsets / DAY_S i = searchsorted(leap_reverse_dates, tai, 'right') ret...
python
{ "resource": "" }
q225298
terra
train
def terra(latitude, longitude, elevation, gast): """Compute the position and velocity of a terrestrial observer. `latitude` - Latitude in radians. `longitude` - Longitude in radians. `elevation` - Elevation above sea level in au. `gast` - Hours of Greenwich Apparent Sidereal Time (can be an array)....
python
{ "resource": "" }
q225299
compute_limb_angle
train
def compute_limb_angle(position_au, observer_au): """Determine the angle of an object above or below the Earth's limb. Given an object's GCRS `position_au` [x,y,z] vector and the position of an `observer_au` as a vector in the same coordinate system, return a tuple that provides `(limb_ang, nadir_ang)`...
python
{ "resource": "" }