repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
gwpy/gwpy
gwpy/segments/flag.py
DataQualityFlag._parse_name
def _parse_name(self, name): """Internal method to parse a `string` name into constituent `ifo, `name` and `version` components. Parameters ---------- name : `str`, `None` the full name of a `DataQualityFlag` to parse, e.g. ``'H1:DMT-SCIENCE:1'``, or `None` to set all components to `None` Returns ------- (ifo, name, version) A tuple of component string parts Raises ------ `ValueError` If the input ``name`` cannot be parsed into {ifo}:{tag}:{version} format. """ if name is None: self.ifo = None self.tag = None self.version = None elif re_IFO_TAG_VERSION.match(name): match = re_IFO_TAG_VERSION.match(name).groupdict() self.ifo = match['ifo'] self.tag = match['tag'] self.version = int(match['version']) elif re_IFO_TAG.match(name): match = re_IFO_TAG.match(name).groupdict() self.ifo = match['ifo'] self.tag = match['tag'] self.version = None elif re_TAG_VERSION.match(name): match = re_TAG_VERSION.match(name).groupdict() self.ifo = None self.tag = match['tag'] self.version = int(match['version']) else: raise ValueError("No flag name structure detected in '%s', flags " "should be named as '{ifo}:{tag}:{version}'. " "For arbitrary strings, use the " "`DataQualityFlag.label` attribute" % name) return self.ifo, self.tag, self.version
python
def _parse_name(self, name): """Internal method to parse a `string` name into constituent `ifo, `name` and `version` components. Parameters ---------- name : `str`, `None` the full name of a `DataQualityFlag` to parse, e.g. ``'H1:DMT-SCIENCE:1'``, or `None` to set all components to `None` Returns ------- (ifo, name, version) A tuple of component string parts Raises ------ `ValueError` If the input ``name`` cannot be parsed into {ifo}:{tag}:{version} format. """ if name is None: self.ifo = None self.tag = None self.version = None elif re_IFO_TAG_VERSION.match(name): match = re_IFO_TAG_VERSION.match(name).groupdict() self.ifo = match['ifo'] self.tag = match['tag'] self.version = int(match['version']) elif re_IFO_TAG.match(name): match = re_IFO_TAG.match(name).groupdict() self.ifo = match['ifo'] self.tag = match['tag'] self.version = None elif re_TAG_VERSION.match(name): match = re_TAG_VERSION.match(name).groupdict() self.ifo = None self.tag = match['tag'] self.version = int(match['version']) else: raise ValueError("No flag name structure detected in '%s', flags " "should be named as '{ifo}:{tag}:{version}'. " "For arbitrary strings, use the " "`DataQualityFlag.label` attribute" % name) return self.ifo, self.tag, self.version
[ "def", "_parse_name", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "self", ".", "ifo", "=", "None", "self", ".", "tag", "=", "None", "self", ".", "version", "=", "None", "elif", "re_IFO_TAG_VERSION", ".", "match", "(", "name",...
Internal method to parse a `string` name into constituent `ifo, `name` and `version` components. Parameters ---------- name : `str`, `None` the full name of a `DataQualityFlag` to parse, e.g. ``'H1:DMT-SCIENCE:1'``, or `None` to set all components to `None` Returns ------- (ifo, name, version) A tuple of component string parts Raises ------ `ValueError` If the input ``name`` cannot be parsed into {ifo}:{tag}:{version} format.
[ "Internal", "method", "to", "parse", "a", "string", "name", "into", "constituent", "ifo", "name", "and", "version", "components", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L917-L963
train
211,600
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.query_segdb
def query_segdb(cls, flags, *args, **kwargs): """Query the inital LIGO segment database for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs. """ warnings.warn("query_segdb is deprecated and will be removed in a " "future release", DeprecationWarning) # parse segments qsegs = _parse_query_segments(args, cls.query_segdb) url = kwargs.pop('url', DEFAULT_SEGMENT_SERVER) if kwargs.pop('on_error', None) is not None: warnings.warn("DataQualityDict.query_segdb doesn't accept the " "on_error keyword argument") if kwargs.keys(): raise TypeError("DataQualityDict.query_segdb has no keyword " "argument '%s'" % list(kwargs.keys()[0])) # process query from glue.segmentdb import (segmentdb_utils as segdb_utils, query_engine as segdb_engine) connection = segdb_utils.setup_database(url) engine = segdb_engine.LdbdQueryEngine(connection) segdefs = [] for flag in flags: dqflag = DataQualityFlag(name=flag) ifo = dqflag.ifo name = dqflag.tag if dqflag.version is None: vers = '*' else: vers = dqflag.version for gpsstart, gpsend in qsegs: if float(gpsend) == +inf: gpsend = to_gps('now').seconds gpsstart = float(gpsstart) if not gpsstart.is_integer(): raise ValueError("Segment database queries can only" "operate on integer GPS times") gpsend = float(gpsend) if not gpsend.is_integer(): raise ValueError("Segment database queries can only" "operate on integer GPS times") segdefs += segdb_utils.expand_version_number( engine, (ifo, name, vers, gpsstart, gpsend, 0, 0)) segs = segdb_utils.query_segments(engine, 'segment', segdefs) segsum = segdb_utils.query_segments(engine, 'segment_summary', segdefs) # build output out = cls() for definition, segments, summary in zip(segdefs, segs, segsum): # parse flag name flag = ':'.join(map(str, definition[:3])) name = flag.rsplit(':', 1)[0] # if versionless if flag.endswith('*'): flag = name key = name # if asked for versionless, but returned a version elif flag not in flags and name in flags: key = name # other else: key = flag # define flag if key not in out: out[key] = DataQualityFlag(name=flag) # add segments out[key].known.extend(summary) out[key].active.extend(segments) return out
python
def query_segdb(cls, flags, *args, **kwargs): """Query the inital LIGO segment database for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs. """ warnings.warn("query_segdb is deprecated and will be removed in a " "future release", DeprecationWarning) # parse segments qsegs = _parse_query_segments(args, cls.query_segdb) url = kwargs.pop('url', DEFAULT_SEGMENT_SERVER) if kwargs.pop('on_error', None) is not None: warnings.warn("DataQualityDict.query_segdb doesn't accept the " "on_error keyword argument") if kwargs.keys(): raise TypeError("DataQualityDict.query_segdb has no keyword " "argument '%s'" % list(kwargs.keys()[0])) # process query from glue.segmentdb import (segmentdb_utils as segdb_utils, query_engine as segdb_engine) connection = segdb_utils.setup_database(url) engine = segdb_engine.LdbdQueryEngine(connection) segdefs = [] for flag in flags: dqflag = DataQualityFlag(name=flag) ifo = dqflag.ifo name = dqflag.tag if dqflag.version is None: vers = '*' else: vers = dqflag.version for gpsstart, gpsend in qsegs: if float(gpsend) == +inf: gpsend = to_gps('now').seconds gpsstart = float(gpsstart) if not gpsstart.is_integer(): raise ValueError("Segment database queries can only" "operate on integer GPS times") gpsend = float(gpsend) if not gpsend.is_integer(): raise ValueError("Segment database queries can only" "operate on integer GPS times") segdefs += segdb_utils.expand_version_number( engine, (ifo, name, vers, gpsstart, gpsend, 0, 0)) segs = segdb_utils.query_segments(engine, 'segment', segdefs) segsum = segdb_utils.query_segments(engine, 'segment_summary', segdefs) # build output out = cls() for definition, segments, summary in zip(segdefs, segs, segsum): # parse flag name flag = ':'.join(map(str, definition[:3])) name = flag.rsplit(':', 1)[0] # if versionless if flag.endswith('*'): flag = name key = name # if asked for versionless, but returned a version elif flag not in flags and name in flags: key = name # other else: key = flag # define flag if key not in out: out[key] = DataQualityFlag(name=flag) # add segments out[key].known.extend(summary) out[key].active.extend(segments) return out
[ "def", "query_segdb", "(", "cls", ",", "flags", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"query_segdb is deprecated and will be removed in a \"", "\"future release\"", ",", "DeprecationWarning", ")", "# parse segments", "q...
Query the inital LIGO segment database for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs.
[ "Query", "the", "inital", "LIGO", "segment", "database", "for", "a", "list", "of", "flags", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1096-L1183
train
211,601
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.query_dqsegdb
def query_dqsegdb(cls, flags, *args, **kwargs): """Query the advanced LIGO DQSegDB for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs. """ # check on_error flag on_error = kwargs.pop('on_error', 'raise').lower() if on_error not in ['raise', 'warn', 'ignore']: raise ValueError("on_error must be one of 'raise', 'warn', " "or 'ignore'") # parse segments qsegs = _parse_query_segments(args, cls.query_dqsegdb) # set up threading inq = Queue() outq = Queue() for i in range(len(flags)): t = _QueryDQSegDBThread(inq, outq, qsegs, **kwargs) t.setDaemon(True) t.start() for i, flag in enumerate(flags): inq.put((i, flag)) # capture output inq.join() outq.join() new = cls() results = list(zip(*sorted([outq.get() for i in range(len(flags))], key=lambda x: x[0])))[1] for result, flag in zip(results, flags): if isinstance(result, Exception): result.args = ('%s [%s]' % (str(result), str(flag)),) if on_error == 'ignore': pass elif on_error == 'warn': warnings.warn(str(result)) else: raise result else: new[flag] = result return new
python
def query_dqsegdb(cls, flags, *args, **kwargs): """Query the advanced LIGO DQSegDB for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs. """ # check on_error flag on_error = kwargs.pop('on_error', 'raise').lower() if on_error not in ['raise', 'warn', 'ignore']: raise ValueError("on_error must be one of 'raise', 'warn', " "or 'ignore'") # parse segments qsegs = _parse_query_segments(args, cls.query_dqsegdb) # set up threading inq = Queue() outq = Queue() for i in range(len(flags)): t = _QueryDQSegDBThread(inq, outq, qsegs, **kwargs) t.setDaemon(True) t.start() for i, flag in enumerate(flags): inq.put((i, flag)) # capture output inq.join() outq.join() new = cls() results = list(zip(*sorted([outq.get() for i in range(len(flags))], key=lambda x: x[0])))[1] for result, flag in zip(results, flags): if isinstance(result, Exception): result.args = ('%s [%s]' % (str(result), str(flag)),) if on_error == 'ignore': pass elif on_error == 'warn': warnings.warn(str(result)) else: raise result else: new[flag] = result return new
[ "def", "query_dqsegdb", "(", "cls", ",", "flags", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check on_error flag", "on_error", "=", "kwargs", ".", "pop", "(", "'on_error'", ",", "'raise'", ")", ".", "lower", "(", ")", "if", "on_error", "no...
Query the advanced LIGO DQSegDB for a list of flags. Parameters ---------- flags : `iterable` A list of flag names for which to query. *args Either, two `float`-like numbers indicating the GPS [start, stop) interval, or a `SegmentList` defining a number of summary segments. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened url : `str`, optional URL of the segment database, defaults to ``$DEFAULT_SEGMENT_SERVER`` environment variable, or ``'https://segments.ligo.org'`` Returns ------- flagdict : `DataQualityDict` An ordered `DataQualityDict` of (name, `DataQualityFlag`) pairs.
[ "Query", "the", "advanced", "LIGO", "DQSegDB", "for", "a", "list", "of", "flags", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1186-L1253
train
211,602
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.read
def read(cls, source, names=None, format=None, **kwargs): """Read segments from file into a `DataQualityDict` Parameters ---------- source : `str` path of file to read format : `str`, optional source format identifier. If not given, the format will be detected if possible. See below for list of acceptable formats. names : `list`, optional, default: read all names found list of names to read, by default all names are read separately. coalesce : `bool`, optional if `True` coalesce the all segment lists before returning, otherwise return exactly as contained in file(s). nproc : `int`, optional, default: 1 number of CPUs to use for parallel reading of multiple files verbose : `bool`, optional, default: `False` print a progress bar showing read status Returns ------- flagdict : `DataQualityDict` a new `DataQualityDict` of `DataQualityFlag` entries with ``active`` and ``known`` segments seeded from the XML tables in the given file. Notes -----""" on_missing = kwargs.pop('on_missing', 'error') coalesce = kwargs.pop('coalesce', False) if 'flags' in kwargs: # pragma: no cover warnings.warn('\'flags\' keyword was renamed \'names\', this ' 'warning will result in an error in the future') names = kwargs.pop('flags') def combiner(inputs): out = cls() # check all names are contained required = set(names or []) found = set(name for dqdict in inputs for name in dqdict) for name in required - found: # validate all names are found once msg = '{!r} not found in any input file'.format(name) if on_missing == 'ignore': continue if on_missing == 'warn': warnings.warn(msg) else: raise ValueError(msg) # combine flags for dqdict in inputs: for flag in dqdict: try: # repeated occurence out[flag].known.extend(dqdict[flag].known) out[flag].active.extend(dqdict[flag].active) except KeyError: # first occurence out[flag] = dqdict[flag] if coalesce: return out.coalesce() return out return io_read_multi(combiner, cls, source, names=names, format=format, on_missing='ignore', **kwargs)
python
def read(cls, source, names=None, format=None, **kwargs): """Read segments from file into a `DataQualityDict` Parameters ---------- source : `str` path of file to read format : `str`, optional source format identifier. If not given, the format will be detected if possible. See below for list of acceptable formats. names : `list`, optional, default: read all names found list of names to read, by default all names are read separately. coalesce : `bool`, optional if `True` coalesce the all segment lists before returning, otherwise return exactly as contained in file(s). nproc : `int`, optional, default: 1 number of CPUs to use for parallel reading of multiple files verbose : `bool`, optional, default: `False` print a progress bar showing read status Returns ------- flagdict : `DataQualityDict` a new `DataQualityDict` of `DataQualityFlag` entries with ``active`` and ``known`` segments seeded from the XML tables in the given file. Notes -----""" on_missing = kwargs.pop('on_missing', 'error') coalesce = kwargs.pop('coalesce', False) if 'flags' in kwargs: # pragma: no cover warnings.warn('\'flags\' keyword was renamed \'names\', this ' 'warning will result in an error in the future') names = kwargs.pop('flags') def combiner(inputs): out = cls() # check all names are contained required = set(names or []) found = set(name for dqdict in inputs for name in dqdict) for name in required - found: # validate all names are found once msg = '{!r} not found in any input file'.format(name) if on_missing == 'ignore': continue if on_missing == 'warn': warnings.warn(msg) else: raise ValueError(msg) # combine flags for dqdict in inputs: for flag in dqdict: try: # repeated occurence out[flag].known.extend(dqdict[flag].known) out[flag].active.extend(dqdict[flag].active) except KeyError: # first occurence out[flag] = dqdict[flag] if coalesce: return out.coalesce() return out return io_read_multi(combiner, cls, source, names=names, format=format, on_missing='ignore', **kwargs)
[ "def", "read", "(", "cls", ",", "source", ",", "names", "=", "None", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "on_missing", "=", "kwargs", ".", "pop", "(", "'on_missing'", ",", "'error'", ")", "coalesce", "=", "kwargs", ".", "...
Read segments from file into a `DataQualityDict` Parameters ---------- source : `str` path of file to read format : `str`, optional source format identifier. If not given, the format will be detected if possible. See below for list of acceptable formats. names : `list`, optional, default: read all names found list of names to read, by default all names are read separately. coalesce : `bool`, optional if `True` coalesce the all segment lists before returning, otherwise return exactly as contained in file(s). nproc : `int`, optional, default: 1 number of CPUs to use for parallel reading of multiple files verbose : `bool`, optional, default: `False` print a progress bar showing read status Returns ------- flagdict : `DataQualityDict` a new `DataQualityDict` of `DataQualityFlag` entries with ``active`` and ``known`` segments seeded from the XML tables in the given file. Notes -----
[ "Read", "segments", "from", "file", "into", "a", "DataQualityDict" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1256-L1327
train
211,603
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.from_veto_definer_file
def from_veto_definer_file(cls, fp, start=None, end=None, ifo=None, format='ligolw'): """Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS start time at which to restrict returned flags end : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS end time at which to restrict returned flags ifo : `str`, optional interferometer prefix whose flags you want to read format : `str`, optional format of file to read, currently only 'ligolw' is supported Returns ------- flags : `DataQualityDict` a `DataQualityDict` of flags parsed from the `veto_def_table` of the input file. Notes ----- This method does not automatically `~DataQualityDict.populate` the `active` segment list of any flags, a separate call should be made for that as follows >>> flags = DataQualityDict.from_veto_definer_file('/path/to/file.xml') >>> flags.populate() """ if format != 'ligolw': raise NotImplementedError("Reading veto definer from non-ligolw " "format file is not currently " "supported") # read veto definer file with get_readable_fileobj(fp, show_progress=False) as fobj: from ..io.ligolw import read_table as read_ligolw_table veto_def_table = read_ligolw_table(fobj, 'veto_definer') if start is not None: start = to_gps(start) if end is not None: end = to_gps(end) # parse flag definitions out = cls() for row in veto_def_table: if ifo and row.ifo != ifo: continue if start and 0 < row.end_time <= start: continue elif start: row.start_time = max(row.start_time, start) if end and row.start_time >= end: continue elif end and not row.end_time: row.end_time = end elif end: row.end_time = min(row.end_time, end) flag = DataQualityFlag.from_veto_def(row) if flag.name in out: out[flag.name].known.extend(flag.known) out[flag.name].known.coalesce() else: out[flag.name] = flag return out
python
def from_veto_definer_file(cls, fp, start=None, end=None, ifo=None, format='ligolw'): """Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS start time at which to restrict returned flags end : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS end time at which to restrict returned flags ifo : `str`, optional interferometer prefix whose flags you want to read format : `str`, optional format of file to read, currently only 'ligolw' is supported Returns ------- flags : `DataQualityDict` a `DataQualityDict` of flags parsed from the `veto_def_table` of the input file. Notes ----- This method does not automatically `~DataQualityDict.populate` the `active` segment list of any flags, a separate call should be made for that as follows >>> flags = DataQualityDict.from_veto_definer_file('/path/to/file.xml') >>> flags.populate() """ if format != 'ligolw': raise NotImplementedError("Reading veto definer from non-ligolw " "format file is not currently " "supported") # read veto definer file with get_readable_fileobj(fp, show_progress=False) as fobj: from ..io.ligolw import read_table as read_ligolw_table veto_def_table = read_ligolw_table(fobj, 'veto_definer') if start is not None: start = to_gps(start) if end is not None: end = to_gps(end) # parse flag definitions out = cls() for row in veto_def_table: if ifo and row.ifo != ifo: continue if start and 0 < row.end_time <= start: continue elif start: row.start_time = max(row.start_time, start) if end and row.start_time >= end: continue elif end and not row.end_time: row.end_time = end elif end: row.end_time = min(row.end_time, end) flag = DataQualityFlag.from_veto_def(row) if flag.name in out: out[flag.name].known.extend(flag.known) out[flag.name].known.coalesce() else: out[flag.name] = flag return out
[ "def", "from_veto_definer_file", "(", "cls", ",", "fp", ",", "start", "=", "None", ",", "end", "=", "None", ",", "ifo", "=", "None", ",", "format", "=", "'ligolw'", ")", ":", "if", "format", "!=", "'ligolw'", ":", "raise", "NotImplementedError", "(", "...
Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters ---------- fp : `str` path of veto definer file to read start : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS start time at which to restrict returned flags end : `~gwpy.time.LIGOTimeGPS`, `int`, optional GPS end time at which to restrict returned flags ifo : `str`, optional interferometer prefix whose flags you want to read format : `str`, optional format of file to read, currently only 'ligolw' is supported Returns ------- flags : `DataQualityDict` a `DataQualityDict` of flags parsed from the `veto_def_table` of the input file. Notes ----- This method does not automatically `~DataQualityDict.populate` the `active` segment list of any flags, a separate call should be made for that as follows >>> flags = DataQualityDict.from_veto_definer_file('/path/to/file.xml') >>> flags.populate()
[ "Read", "a", "DataQualityDict", "from", "a", "LIGO_LW", "XML", "VetoDefinerTable", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1330-L1399
train
211,604
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.from_ligolw_tables
def from_ligolw_tables(cls, segmentdeftable, segmentsumtable, segmenttable, names=None, gpstype=LIGOTimeGPS, on_missing='error'): """Build a `DataQualityDict` from a set of LIGO_LW segment tables Parameters ---------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table to read segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table to read segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table to read names : `list` of `str`, optional a list of flag names to read, defaults to returning all gpstype : `type`, `callable`, optional class to use for GPS times in returned objects, can be a function to convert GPS time to something else, default is `~gwpy.time.LIGOTimeGPS` on_missing : `str`, optional action to take when a one or more ``names`` are not found in the ``segment_definer`` table, one of - ``'ignore'`` : do nothing - ``'warn'`` : print a warning - ``error'`` : raise a `ValueError` Returns ------- dqdict : `DataQualityDict` a dict of `DataQualityFlag` objects populated from the LIGO_LW tables """ out = cls() id_ = dict() # need to record relative IDs from LIGO_LW # read segment definers and generate DataQualityFlag object for row in segmentdeftable: ifos = sorted(row.instruments) ifo = ''.join(ifos) if ifos else None tag = row.name version = row.version name = ':'.join([str(k) for k in (ifo, tag, version) if k is not None]) if names is None or name in names: out[name] = DataQualityFlag(name) thisid = int(row.segment_def_id) try: id_[name].append(thisid) except (AttributeError, KeyError): id_[name] = [thisid] # verify all requested flags were found for flag in names or []: if flag not in out and on_missing != 'ignore': msg = ("no segment definition found for flag={0!r} in " "file".format(flag)) if on_missing == 'warn': warnings.warn(msg) else: raise ValueError(msg) # parse a table into the target DataQualityDict def _parse_segments(table, listattr): for row in table: for flag in out: # match row ID to list of IDs found for this flag if int(row.segment_def_id) in id_[flag]: getattr(out[flag], listattr).append( Segment(*map(gpstype, row.segment)), ) break # read segment summary table as 'known' _parse_segments(segmentsumtable, "known") # read segment table as 'active' _parse_segments(segmenttable, "active") return out
python
def from_ligolw_tables(cls, segmentdeftable, segmentsumtable, segmenttable, names=None, gpstype=LIGOTimeGPS, on_missing='error'): """Build a `DataQualityDict` from a set of LIGO_LW segment tables Parameters ---------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table to read segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table to read segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table to read names : `list` of `str`, optional a list of flag names to read, defaults to returning all gpstype : `type`, `callable`, optional class to use for GPS times in returned objects, can be a function to convert GPS time to something else, default is `~gwpy.time.LIGOTimeGPS` on_missing : `str`, optional action to take when a one or more ``names`` are not found in the ``segment_definer`` table, one of - ``'ignore'`` : do nothing - ``'warn'`` : print a warning - ``error'`` : raise a `ValueError` Returns ------- dqdict : `DataQualityDict` a dict of `DataQualityFlag` objects populated from the LIGO_LW tables """ out = cls() id_ = dict() # need to record relative IDs from LIGO_LW # read segment definers and generate DataQualityFlag object for row in segmentdeftable: ifos = sorted(row.instruments) ifo = ''.join(ifos) if ifos else None tag = row.name version = row.version name = ':'.join([str(k) for k in (ifo, tag, version) if k is not None]) if names is None or name in names: out[name] = DataQualityFlag(name) thisid = int(row.segment_def_id) try: id_[name].append(thisid) except (AttributeError, KeyError): id_[name] = [thisid] # verify all requested flags were found for flag in names or []: if flag not in out and on_missing != 'ignore': msg = ("no segment definition found for flag={0!r} in " "file".format(flag)) if on_missing == 'warn': warnings.warn(msg) else: raise ValueError(msg) # parse a table into the target DataQualityDict def _parse_segments(table, listattr): for row in table: for flag in out: # match row ID to list of IDs found for this flag if int(row.segment_def_id) in id_[flag]: getattr(out[flag], listattr).append( Segment(*map(gpstype, row.segment)), ) break # read segment summary table as 'known' _parse_segments(segmentsumtable, "known") # read segment table as 'active' _parse_segments(segmenttable, "active") return out
[ "def", "from_ligolw_tables", "(", "cls", ",", "segmentdeftable", ",", "segmentsumtable", ",", "segmenttable", ",", "names", "=", "None", ",", "gpstype", "=", "LIGOTimeGPS", ",", "on_missing", "=", "'error'", ")", ":", "out", "=", "cls", "(", ")", "id_", "=...
Build a `DataQualityDict` from a set of LIGO_LW segment tables Parameters ---------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table to read segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table to read segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table to read names : `list` of `str`, optional a list of flag names to read, defaults to returning all gpstype : `type`, `callable`, optional class to use for GPS times in returned objects, can be a function to convert GPS time to something else, default is `~gwpy.time.LIGOTimeGPS` on_missing : `str`, optional action to take when a one or more ``names`` are not found in the ``segment_definer`` table, one of - ``'ignore'`` : do nothing - ``'warn'`` : print a warning - ``error'`` : raise a `ValueError` Returns ------- dqdict : `DataQualityDict` a dict of `DataQualityFlag` objects populated from the LIGO_LW tables
[ "Build", "a", "DataQualityDict", "from", "a", "set", "of", "LIGO_LW", "segment", "tables" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1402-L1487
train
211,605
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.to_ligolw_tables
def to_ligolw_tables(self, ilwdchar_compat=None, **attrs): """Convert this `DataQualityDict` into a trio of LIGO_LW segment tables Parameters ---------- ilwdchar_compat : `bool`, optional whether to write in the old format, compatible with ILWD characters (`True`), or to use the new format (`False`); the current default is `True` to maintain backwards compatibility, but this will change for gwpy-1.0.0. **attrs other attributes to add to all rows in all tables (e.g. ``'process_id'``) Returns ------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table """ if ilwdchar_compat is None: warnings.warn("ilwdchar_compat currently defaults to `True`, " "but this will change to `False` in the future, to " "maintain compatibility in future releases, " "manually specify `ilwdchar_compat=True`", PendingDeprecationWarning) ilwdchar_compat = True if ilwdchar_compat: from glue.ligolw import lsctables else: from ligo.lw import lsctables from ..io.ligolw import to_table_type as to_ligolw_table_type SegmentDefTable = lsctables.SegmentDefTable SegmentSumTable = lsctables.SegmentSumTable SegmentTable = lsctables.SegmentTable segdeftab = lsctables.New(SegmentDefTable) segsumtab = lsctables.New(SegmentSumTable) segtab = lsctables.New(SegmentTable) def _write_attrs(table, row): for key, val in attrs.items(): setattr(row, key, to_ligolw_table_type(val, table, key)) # write flags to tables for flag in self.values(): # segment definer segdef = segdeftab.RowType() for col in segdeftab.columnnames: # default all columns to None setattr(segdef, col, None) segdef.instruments = {flag.ifo} segdef.name = flag.tag segdef.version = flag.version segdef.comment = flag.description segdef.insertion_time = to_gps(datetime.datetime.now()).gpsSeconds segdef.segment_def_id = SegmentDefTable.get_next_id() _write_attrs(segdeftab, segdef) segdeftab.append(segdef) # write segment summary (known segments) for vseg in flag.known: segsum = segsumtab.RowType() for col in segsumtab.columnnames: # default columns to None setattr(segsum, col, None) segsum.segment_def_id = segdef.segment_def_id segsum.segment = map(LIGOTimeGPS, vseg) segsum.comment = None segsum.segment_sum_id = SegmentSumTable.get_next_id() _write_attrs(segsumtab, segsum) segsumtab.append(segsum) # write segment table (active segments) for aseg in flag.active: seg = segtab.RowType() for col in segtab.columnnames: # default all columns to None setattr(seg, col, None) seg.segment_def_id = segdef.segment_def_id seg.segment = map(LIGOTimeGPS, aseg) seg.segment_id = SegmentTable.get_next_id() _write_attrs(segtab, seg) segtab.append(seg) return segdeftab, segsumtab, segtab
python
def to_ligolw_tables(self, ilwdchar_compat=None, **attrs): """Convert this `DataQualityDict` into a trio of LIGO_LW segment tables Parameters ---------- ilwdchar_compat : `bool`, optional whether to write in the old format, compatible with ILWD characters (`True`), or to use the new format (`False`); the current default is `True` to maintain backwards compatibility, but this will change for gwpy-1.0.0. **attrs other attributes to add to all rows in all tables (e.g. ``'process_id'``) Returns ------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table """ if ilwdchar_compat is None: warnings.warn("ilwdchar_compat currently defaults to `True`, " "but this will change to `False` in the future, to " "maintain compatibility in future releases, " "manually specify `ilwdchar_compat=True`", PendingDeprecationWarning) ilwdchar_compat = True if ilwdchar_compat: from glue.ligolw import lsctables else: from ligo.lw import lsctables from ..io.ligolw import to_table_type as to_ligolw_table_type SegmentDefTable = lsctables.SegmentDefTable SegmentSumTable = lsctables.SegmentSumTable SegmentTable = lsctables.SegmentTable segdeftab = lsctables.New(SegmentDefTable) segsumtab = lsctables.New(SegmentSumTable) segtab = lsctables.New(SegmentTable) def _write_attrs(table, row): for key, val in attrs.items(): setattr(row, key, to_ligolw_table_type(val, table, key)) # write flags to tables for flag in self.values(): # segment definer segdef = segdeftab.RowType() for col in segdeftab.columnnames: # default all columns to None setattr(segdef, col, None) segdef.instruments = {flag.ifo} segdef.name = flag.tag segdef.version = flag.version segdef.comment = flag.description segdef.insertion_time = to_gps(datetime.datetime.now()).gpsSeconds segdef.segment_def_id = SegmentDefTable.get_next_id() _write_attrs(segdeftab, segdef) segdeftab.append(segdef) # write segment summary (known segments) for vseg in flag.known: segsum = segsumtab.RowType() for col in segsumtab.columnnames: # default columns to None setattr(segsum, col, None) segsum.segment_def_id = segdef.segment_def_id segsum.segment = map(LIGOTimeGPS, vseg) segsum.comment = None segsum.segment_sum_id = SegmentSumTable.get_next_id() _write_attrs(segsumtab, segsum) segsumtab.append(segsum) # write segment table (active segments) for aseg in flag.active: seg = segtab.RowType() for col in segtab.columnnames: # default all columns to None setattr(seg, col, None) seg.segment_def_id = segdef.segment_def_id seg.segment = map(LIGOTimeGPS, aseg) seg.segment_id = SegmentTable.get_next_id() _write_attrs(segtab, seg) segtab.append(seg) return segdeftab, segsumtab, segtab
[ "def", "to_ligolw_tables", "(", "self", ",", "ilwdchar_compat", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "ilwdchar_compat", "is", "None", ":", "warnings", ".", "warn", "(", "\"ilwdchar_compat currently defaults to `True`, \"", "\"but this will change to `F...
Convert this `DataQualityDict` into a trio of LIGO_LW segment tables Parameters ---------- ilwdchar_compat : `bool`, optional whether to write in the old format, compatible with ILWD characters (`True`), or to use the new format (`False`); the current default is `True` to maintain backwards compatibility, but this will change for gwpy-1.0.0. **attrs other attributes to add to all rows in all tables (e.g. ``'process_id'``) Returns ------- segmentdeftable : :class:`~ligo.lw.lsctables.SegmentDefTable` the ``segment_definer`` table segmentsumtable : :class:`~ligo.lw.lsctables.SegmentSumTable` the ``segment_summary`` table segmenttable : :class:`~ligo.lw.lsctables.SegmentTable` the ``segment`` table
[ "Convert", "this", "DataQualityDict", "into", "a", "trio", "of", "LIGO_LW", "segment", "tables" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1489-L1578
train
211,606
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.populate
def populate(self, source=DEFAULT_SEGMENT_SERVER, segments=None, pad=True, on_error='raise', **kwargs): """Query the segment database for each flag's active segments. This method assumes all of the metadata for each flag have been filled. Minimally, the following attributes must be filled .. autosummary:: ~DataQualityFlag.name ~DataQualityFlag.known Segments will be fetched from the database, with any :attr:`~DataQualityFlag.padding` added on-the-fly. Entries in this dict will be modified in-place. Parameters ---------- source : `str` source of segments for this flag. This must be either a URL for a segment database or a path to a file on disk. segments : `SegmentList`, optional a list of known segments during which to query, if not given, existing known segments for flags will be used. pad : `bool`, optional, default: `True` apply the `~DataQualityFlag.padding` associated with each flag, default: `True`. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened **kwargs any other keyword arguments to be passed to :meth:`DataQualityFlag.query` or :meth:`DataQualityFlag.read`. Returns ------- self : `DataQualityDict` a reference to the modified DataQualityDict """ # check on_error flag if on_error not in ['raise', 'warn', 'ignore']: raise ValueError("on_error must be one of 'raise', 'warn', " "or 'ignore'") # format source source = urlparse(source) # perform query for all segments if source.netloc and segments is not None: segments = SegmentList(map(Segment, segments)) tmp = type(self).query(self.keys(), segments, url=source.geturl(), on_error=on_error, **kwargs) elif not source.netloc: tmp = type(self).read(source.geturl(), **kwargs) # apply padding and wrap to given known segments for key in self: if segments is None and source.netloc: try: tmp = {key: self[key].query( self[key].name, self[key].known, **kwargs)} except URLError as exc: if on_error == 'ignore': pass elif on_error == 'warn': warnings.warn('Error querying for %s: %s' % (key, exc)) else: raise continue self[key].known &= tmp[key].known self[key].active = tmp[key].active if pad: self[key] = self[key].pad(inplace=True) if segments is not None: self[key].known &= segments self[key].active &= segments return self
python
def populate(self, source=DEFAULT_SEGMENT_SERVER, segments=None, pad=True, on_error='raise', **kwargs): """Query the segment database for each flag's active segments. This method assumes all of the metadata for each flag have been filled. Minimally, the following attributes must be filled .. autosummary:: ~DataQualityFlag.name ~DataQualityFlag.known Segments will be fetched from the database, with any :attr:`~DataQualityFlag.padding` added on-the-fly. Entries in this dict will be modified in-place. Parameters ---------- source : `str` source of segments for this flag. This must be either a URL for a segment database or a path to a file on disk. segments : `SegmentList`, optional a list of known segments during which to query, if not given, existing known segments for flags will be used. pad : `bool`, optional, default: `True` apply the `~DataQualityFlag.padding` associated with each flag, default: `True`. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened **kwargs any other keyword arguments to be passed to :meth:`DataQualityFlag.query` or :meth:`DataQualityFlag.read`. Returns ------- self : `DataQualityDict` a reference to the modified DataQualityDict """ # check on_error flag if on_error not in ['raise', 'warn', 'ignore']: raise ValueError("on_error must be one of 'raise', 'warn', " "or 'ignore'") # format source source = urlparse(source) # perform query for all segments if source.netloc and segments is not None: segments = SegmentList(map(Segment, segments)) tmp = type(self).query(self.keys(), segments, url=source.geturl(), on_error=on_error, **kwargs) elif not source.netloc: tmp = type(self).read(source.geturl(), **kwargs) # apply padding and wrap to given known segments for key in self: if segments is None and source.netloc: try: tmp = {key: self[key].query( self[key].name, self[key].known, **kwargs)} except URLError as exc: if on_error == 'ignore': pass elif on_error == 'warn': warnings.warn('Error querying for %s: %s' % (key, exc)) else: raise continue self[key].known &= tmp[key].known self[key].active = tmp[key].active if pad: self[key] = self[key].pad(inplace=True) if segments is not None: self[key].known &= segments self[key].active &= segments return self
[ "def", "populate", "(", "self", ",", "source", "=", "DEFAULT_SEGMENT_SERVER", ",", "segments", "=", "None", ",", "pad", "=", "True", ",", "on_error", "=", "'raise'", ",", "*", "*", "kwargs", ")", ":", "# check on_error flag", "if", "on_error", "not", "in",...
Query the segment database for each flag's active segments. This method assumes all of the metadata for each flag have been filled. Minimally, the following attributes must be filled .. autosummary:: ~DataQualityFlag.name ~DataQualityFlag.known Segments will be fetched from the database, with any :attr:`~DataQualityFlag.padding` added on-the-fly. Entries in this dict will be modified in-place. Parameters ---------- source : `str` source of segments for this flag. This must be either a URL for a segment database or a path to a file on disk. segments : `SegmentList`, optional a list of known segments during which to query, if not given, existing known segments for flags will be used. pad : `bool`, optional, default: `True` apply the `~DataQualityFlag.padding` associated with each flag, default: `True`. on_error : `str` how to handle an error querying for one flag, one of - `'raise'` (default): raise the Exception - `'warn'`: print a warning - `'ignore'`: move onto the next flag as if nothing happened **kwargs any other keyword arguments to be passed to :meth:`DataQualityFlag.query` or :meth:`DataQualityFlag.read`. Returns ------- self : `DataQualityDict` a reference to the modified DataQualityDict
[ "Query", "the", "segment", "database", "for", "each", "flag", "s", "active", "segments", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1603-L1684
train
211,607
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.copy
def copy(self, deep=False): """Build a copy of this dictionary. Parameters ---------- deep : `bool`, optional, default: `False` perform a deep copy of the original dictionary with a fresh memory address Returns ------- flag2 : `DataQualityFlag` a copy of the original dictionary """ if deep: return deepcopy(self) return super(DataQualityDict, self).copy()
python
def copy(self, deep=False): """Build a copy of this dictionary. Parameters ---------- deep : `bool`, optional, default: `False` perform a deep copy of the original dictionary with a fresh memory address Returns ------- flag2 : `DataQualityFlag` a copy of the original dictionary """ if deep: return deepcopy(self) return super(DataQualityDict, self).copy()
[ "def", "copy", "(", "self", ",", "deep", "=", "False", ")", ":", "if", "deep", ":", "return", "deepcopy", "(", "self", ")", "return", "super", "(", "DataQualityDict", ",", "self", ")", ".", "copy", "(", ")" ]
Build a copy of this dictionary. Parameters ---------- deep : `bool`, optional, default: `False` perform a deep copy of the original dictionary with a fresh memory address Returns ------- flag2 : `DataQualityFlag` a copy of the original dictionary
[ "Build", "a", "copy", "of", "this", "dictionary", "." ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1686-L1702
train
211,608
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.union
def union(self): """Return the union of all flags in this dict Returns ------- union : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the union of those of the values of this dict """ usegs = reduce(operator.or_, self.values()) usegs.name = ' | '.join(self.keys()) return usegs
python
def union(self): """Return the union of all flags in this dict Returns ------- union : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the union of those of the values of this dict """ usegs = reduce(operator.or_, self.values()) usegs.name = ' | '.join(self.keys()) return usegs
[ "def", "union", "(", "self", ")", ":", "usegs", "=", "reduce", "(", "operator", ".", "or_", ",", "self", ".", "values", "(", ")", ")", "usegs", ".", "name", "=", "' | '", ".", "join", "(", "self", ".", "keys", "(", ")", ")", "return", "usegs" ]
Return the union of all flags in this dict Returns ------- union : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the union of those of the values of this dict
[ "Return", "the", "union", "of", "all", "flags", "in", "this", "dict" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1759-L1770
train
211,609
gwpy/gwpy
gwpy/segments/flag.py
DataQualityDict.intersection
def intersection(self): """Return the intersection of all flags in this dict Returns ------- intersection : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the intersection of those of the values of this dict """ isegs = reduce(operator.and_, self.values()) isegs.name = ' & '.join(self.keys()) return isegs
python
def intersection(self): """Return the intersection of all flags in this dict Returns ------- intersection : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the intersection of those of the values of this dict """ isegs = reduce(operator.and_, self.values()) isegs.name = ' & '.join(self.keys()) return isegs
[ "def", "intersection", "(", "self", ")", ":", "isegs", "=", "reduce", "(", "operator", ".", "and_", ",", "self", ".", "values", "(", ")", ")", "isegs", ".", "name", "=", "' & '", ".", "join", "(", "self", ".", "keys", "(", ")", ")", "return", "is...
Return the intersection of all flags in this dict Returns ------- intersection : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments are the intersection of those of the values of this dict
[ "Return", "the", "intersection", "of", "all", "flags", "in", "this", "dict" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1772-L1783
train
211,610
gwpy/gwpy
gwpy/plot/rc.py
rc_params
def rc_params(usetex=None): """Returns a new `matplotlib.RcParams` with updated GWpy parameters The updated parameters are globally stored as `gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as `gwpy.plot.rc.GWPY_TEX_RCPARAMS`. .. note:: This function doesn't apply the new `RcParams` in any way, just creates something that can be used to set `matplotlib.rcParams`. Parameters ---------- usetex : `bool`, `None` value to set for `text.usetex`; if `None` determine automatically using the ``GWPY_USETEX`` environment variable, and whether `tex` is available on the system. If `True` is given (or determined) a number of other parameters are updated to improve TeX formatting. Examples -------- >>> import matplotlib >>> from gwpy.plot.rc import rc_params as gwpy_rc_params() >>> matplotlib.rcParams.update(gwpy_rc_params(usetex=False)) """ # if user didn't specify to use tex or not, guess based on # the `GWPY_USETEX` environment variable, or whether tex is # installed at all. if usetex is None: usetex = bool_env( 'GWPY_USETEX', default=rcParams['text.usetex'] or tex.has_tex()) # build RcParams from matplotlib.rcParams with GWpy extras rcp = GWPY_RCPARAMS.copy() if usetex: rcp.update(GWPY_TEX_RCPARAMS) return rcp
python
def rc_params(usetex=None): """Returns a new `matplotlib.RcParams` with updated GWpy parameters The updated parameters are globally stored as `gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as `gwpy.plot.rc.GWPY_TEX_RCPARAMS`. .. note:: This function doesn't apply the new `RcParams` in any way, just creates something that can be used to set `matplotlib.rcParams`. Parameters ---------- usetex : `bool`, `None` value to set for `text.usetex`; if `None` determine automatically using the ``GWPY_USETEX`` environment variable, and whether `tex` is available on the system. If `True` is given (or determined) a number of other parameters are updated to improve TeX formatting. Examples -------- >>> import matplotlib >>> from gwpy.plot.rc import rc_params as gwpy_rc_params() >>> matplotlib.rcParams.update(gwpy_rc_params(usetex=False)) """ # if user didn't specify to use tex or not, guess based on # the `GWPY_USETEX` environment variable, or whether tex is # installed at all. if usetex is None: usetex = bool_env( 'GWPY_USETEX', default=rcParams['text.usetex'] or tex.has_tex()) # build RcParams from matplotlib.rcParams with GWpy extras rcp = GWPY_RCPARAMS.copy() if usetex: rcp.update(GWPY_TEX_RCPARAMS) return rcp
[ "def", "rc_params", "(", "usetex", "=", "None", ")", ":", "# if user didn't specify to use tex or not, guess based on", "# the `GWPY_USETEX` environment variable, or whether tex is", "# installed at all.", "if", "usetex", "is", "None", ":", "usetex", "=", "bool_env", "(", "'G...
Returns a new `matplotlib.RcParams` with updated GWpy parameters The updated parameters are globally stored as `gwpy.plot.rc.GWPY_RCPARAMS`, with the updated TeX parameters as `gwpy.plot.rc.GWPY_TEX_RCPARAMS`. .. note:: This function doesn't apply the new `RcParams` in any way, just creates something that can be used to set `matplotlib.rcParams`. Parameters ---------- usetex : `bool`, `None` value to set for `text.usetex`; if `None` determine automatically using the ``GWPY_USETEX`` environment variable, and whether `tex` is available on the system. If `True` is given (or determined) a number of other parameters are updated to improve TeX formatting. Examples -------- >>> import matplotlib >>> from gwpy.plot.rc import rc_params as gwpy_rc_params() >>> matplotlib.rcParams.update(gwpy_rc_params(usetex=False))
[ "Returns", "a", "new", "matplotlib", ".", "RcParams", "with", "updated", "GWpy", "parameters" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/rc.py#L100-L138
train
211,611
gwpy/gwpy
gwpy/plot/rc.py
get_subplot_params
def get_subplot_params(figsize): """Return sensible default `SubplotParams` for a figure of the given size Parameters ---------- figsize : `tuple` of `float` the ``(width, height)`` figure size (inches) Returns ------- params : `~matplotlib.figure.SubplotParams` formatted set of subplot parameters """ width, height, = figsize try: left, right = SUBPLOT_WIDTH[width] except KeyError: left = right = None try: bottom, top = SUBPLOT_HEIGHT[height] except KeyError: bottom = top = None return SubplotParams(left=left, bottom=bottom, right=right, top=top)
python
def get_subplot_params(figsize): """Return sensible default `SubplotParams` for a figure of the given size Parameters ---------- figsize : `tuple` of `float` the ``(width, height)`` figure size (inches) Returns ------- params : `~matplotlib.figure.SubplotParams` formatted set of subplot parameters """ width, height, = figsize try: left, right = SUBPLOT_WIDTH[width] except KeyError: left = right = None try: bottom, top = SUBPLOT_HEIGHT[height] except KeyError: bottom = top = None return SubplotParams(left=left, bottom=bottom, right=right, top=top)
[ "def", "get_subplot_params", "(", "figsize", ")", ":", "width", ",", "height", ",", "=", "figsize", "try", ":", "left", ",", "right", "=", "SUBPLOT_WIDTH", "[", "width", "]", "except", "KeyError", ":", "left", "=", "right", "=", "None", "try", ":", "bo...
Return sensible default `SubplotParams` for a figure of the given size Parameters ---------- figsize : `tuple` of `float` the ``(width, height)`` figure size (inches) Returns ------- params : `~matplotlib.figure.SubplotParams` formatted set of subplot parameters
[ "Return", "sensible", "default", "SubplotParams", "for", "a", "figure", "of", "the", "given", "size" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/rc.py#L158-L180
train
211,612
gwpy/gwpy
gwpy/plot/text.py
to_string
def to_string(input_): """Format an input for representation as text This method is just a convenience that handles default LaTeX formatting """ usetex = rcParams['text.usetex'] if isinstance(input_, units.UnitBase): return input_.to_string('latex_inline') if isinstance(input_, (float, int)) and usetex: return tex.float_to_latex(input_) if usetex: return tex.label_to_latex(input_) return str(input_)
python
def to_string(input_): """Format an input for representation as text This method is just a convenience that handles default LaTeX formatting """ usetex = rcParams['text.usetex'] if isinstance(input_, units.UnitBase): return input_.to_string('latex_inline') if isinstance(input_, (float, int)) and usetex: return tex.float_to_latex(input_) if usetex: return tex.label_to_latex(input_) return str(input_)
[ "def", "to_string", "(", "input_", ")", ":", "usetex", "=", "rcParams", "[", "'text.usetex'", "]", "if", "isinstance", "(", "input_", ",", "units", ".", "UnitBase", ")", ":", "return", "input_", ".", "to_string", "(", "'latex_inline'", ")", "if", "isinstan...
Format an input for representation as text This method is just a convenience that handles default LaTeX formatting
[ "Format", "an", "input", "for", "representation", "as", "text" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/text.py#L31-L43
train
211,613
gwpy/gwpy
gwpy/plot/text.py
default_unit_label
def default_unit_label(axis, unit): """Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to use for the label Returns ------- text : `str`, `None` the text for the new label, if set, otherwise `None` """ if not axis.isDefault_label: return label = axis.set_label_text(unit.to_string('latex_inline_dimensional')) axis.isDefault_label = True return label.get_text()
python
def default_unit_label(axis, unit): """Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to use for the label Returns ------- text : `str`, `None` the text for the new label, if set, otherwise `None` """ if not axis.isDefault_label: return label = axis.set_label_text(unit.to_string('latex_inline_dimensional')) axis.isDefault_label = True return label.get_text()
[ "def", "default_unit_label", "(", "axis", ",", "unit", ")", ":", "if", "not", "axis", ".", "isDefault_label", ":", "return", "label", "=", "axis", ".", "set_label_text", "(", "unit", ".", "to_string", "(", "'latex_inline_dimensional'", ")", ")", "axis", ".",...
Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to use for the label Returns ------- text : `str`, `None` the text for the new label, if set, otherwise `None`
[ "Set", "default", "label", "for", "an", "axis", "from", "a", "~astropy", ".", "units", ".", "Unit" ]
7a92b917e7dd2d99b15895293a1fa1d66cdb210a
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/plot/text.py#L46-L68
train
211,614
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.initialize
def initialize(self): """Initialize a connection to the LDAP server. :return: LDAP connection object. """ try: conn = ldap.initialize('{0}://{1}:{2}'.format( current_app.config['LDAP_SCHEMA'], current_app.config['LDAP_HOST'], current_app.config['LDAP_PORT'])) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, current_app.config['LDAP_TIMEOUT']) conn = self._set_custom_options(conn) conn.protocol_version = ldap.VERSION3 if current_app.config['LDAP_USE_TLS']: conn.start_tls_s() return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
python
def initialize(self): """Initialize a connection to the LDAP server. :return: LDAP connection object. """ try: conn = ldap.initialize('{0}://{1}:{2}'.format( current_app.config['LDAP_SCHEMA'], current_app.config['LDAP_HOST'], current_app.config['LDAP_PORT'])) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, current_app.config['LDAP_TIMEOUT']) conn = self._set_custom_options(conn) conn.protocol_version = ldap.VERSION3 if current_app.config['LDAP_USE_TLS']: conn.start_tls_s() return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
[ "def", "initialize", "(", "self", ")", ":", "try", ":", "conn", "=", "ldap", ".", "initialize", "(", "'{0}://{1}:{2}'", ".", "format", "(", "current_app", ".", "config", "[", "'LDAP_SCHEMA'", "]", ",", "current_app", ".", "config", "[", "'LDAP_HOST'", "]",...
Initialize a connection to the LDAP server. :return: LDAP connection object.
[ "Initialize", "a", "connection", "to", "the", "LDAP", "server", "." ]
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L88-L107
train
211,615
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.bind
def bind(self): """Attempts to bind to the LDAP server using the credentials of the service account. :return: Bound LDAP connection object if successful or ``None`` if unsuccessful. """ conn = self.initialize try: conn.simple_bind_s( current_app.config['LDAP_USERNAME'], current_app.config['LDAP_PASSWORD']) return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
python
def bind(self): """Attempts to bind to the LDAP server using the credentials of the service account. :return: Bound LDAP connection object if successful or ``None`` if unsuccessful. """ conn = self.initialize try: conn.simple_bind_s( current_app.config['LDAP_USERNAME'], current_app.config['LDAP_PASSWORD']) return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
[ "def", "bind", "(", "self", ")", ":", "conn", "=", "self", ".", "initialize", "try", ":", "conn", ".", "simple_bind_s", "(", "current_app", ".", "config", "[", "'LDAP_USERNAME'", "]", ",", "current_app", ".", "config", "[", "'LDAP_PASSWORD'", "]", ")", "...
Attempts to bind to the LDAP server using the credentials of the service account. :return: Bound LDAP connection object if successful or ``None`` if unsuccessful.
[ "Attempts", "to", "bind", "to", "the", "LDAP", "server", "using", "the", "credentials", "of", "the", "service", "account", "." ]
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L110-L125
train
211,616
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.bind_user
def bind_user(self, username, password): """Attempts to bind a user to the LDAP server using the credentials supplied. .. note:: Many LDAP servers will grant anonymous access if ``password`` is the empty string, causing this method to return :obj:`True` no matter what username is given. If you want to use this method to validate a username and password, rather than actually connecting to the LDAP server as a particular user, make sure ``password`` is not empty. :param str username: The username to attempt to bind with. :param str password: The password of the username we're attempting to bind with. :return: Returns ``True`` if successful or ``None`` if the credentials are invalid. """ user_dn = self.get_object_details(user=username, dn_only=True) if user_dn is None: return try: conn = self.initialize conn.simple_bind_s(user_dn.decode('utf-8'), password) return True except ldap.LDAPError: return
python
def bind_user(self, username, password): """Attempts to bind a user to the LDAP server using the credentials supplied. .. note:: Many LDAP servers will grant anonymous access if ``password`` is the empty string, causing this method to return :obj:`True` no matter what username is given. If you want to use this method to validate a username and password, rather than actually connecting to the LDAP server as a particular user, make sure ``password`` is not empty. :param str username: The username to attempt to bind with. :param str password: The password of the username we're attempting to bind with. :return: Returns ``True`` if successful or ``None`` if the credentials are invalid. """ user_dn = self.get_object_details(user=username, dn_only=True) if user_dn is None: return try: conn = self.initialize conn.simple_bind_s(user_dn.decode('utf-8'), password) return True except ldap.LDAPError: return
[ "def", "bind_user", "(", "self", ",", "username", ",", "password", ")", ":", "user_dn", "=", "self", ".", "get_object_details", "(", "user", "=", "username", ",", "dn_only", "=", "True", ")", "if", "user_dn", "is", "None", ":", "return", "try", ":", "c...
Attempts to bind a user to the LDAP server using the credentials supplied. .. note:: Many LDAP servers will grant anonymous access if ``password`` is the empty string, causing this method to return :obj:`True` no matter what username is given. If you want to use this method to validate a username and password, rather than actually connecting to the LDAP server as a particular user, make sure ``password`` is not empty. :param str username: The username to attempt to bind with. :param str password: The password of the username we're attempting to bind with. :return: Returns ``True`` if successful or ``None`` if the credentials are invalid.
[ "Attempts", "to", "bind", "a", "user", "to", "the", "LDAP", "server", "using", "the", "credentials", "supplied", "." ]
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L127-L156
train
211,617
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.get_user_groups
def get_user_groups(self, user): """Returns a ``list`` with the user's groups or ``None`` if unsuccessful. :param str user: User we want groups for. """ conn = self.bind try: if current_app.config['LDAP_OPENLDAP']: fields = \ [str(current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'])] records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_GROUP_MEMBER_FILTER'], (self.get_object_details(user, dn_only=True),)), fields) else: records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_USER_OBJECT_FILTER'], (user,)), [current_app.config['LDAP_USER_GROUPS_FIELD']]) conn.unbind_s() if records: if current_app.config['LDAP_OPENLDAP']: group_member_filter = \ current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'] if sys.version_info[0] > 2: groups = [record[1][group_member_filter][0].decode( 'utf-8') for record in records] else: groups = [record[1][group_member_filter][0] for record in records] return groups else: if current_app.config['LDAP_USER_GROUPS_FIELD'] in \ records[0][1]: groups = records[0][1][ current_app.config['LDAP_USER_GROUPS_FIELD']] result = [re.findall(b'(?:cn=|CN=)(.*?),', group)[0] for group in groups] if sys.version_info[0] > 2: result = [r.decode('utf-8') for r in result] return result except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
python
def get_user_groups(self, user): """Returns a ``list`` with the user's groups or ``None`` if unsuccessful. :param str user: User we want groups for. """ conn = self.bind try: if current_app.config['LDAP_OPENLDAP']: fields = \ [str(current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'])] records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_GROUP_MEMBER_FILTER'], (self.get_object_details(user, dn_only=True),)), fields) else: records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_USER_OBJECT_FILTER'], (user,)), [current_app.config['LDAP_USER_GROUPS_FIELD']]) conn.unbind_s() if records: if current_app.config['LDAP_OPENLDAP']: group_member_filter = \ current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'] if sys.version_info[0] > 2: groups = [record[1][group_member_filter][0].decode( 'utf-8') for record in records] else: groups = [record[1][group_member_filter][0] for record in records] return groups else: if current_app.config['LDAP_USER_GROUPS_FIELD'] in \ records[0][1]: groups = records[0][1][ current_app.config['LDAP_USER_GROUPS_FIELD']] result = [re.findall(b'(?:cn=|CN=)(.*?),', group)[0] for group in groups] if sys.version_info[0] > 2: result = [r.decode('utf-8') for r in result] return result except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
[ "def", "get_user_groups", "(", "self", ",", "user", ")", ":", "conn", "=", "self", ".", "bind", "try", ":", "if", "current_app", ".", "config", "[", "'LDAP_OPENLDAP'", "]", ":", "fields", "=", "[", "str", "(", "current_app", ".", "config", "[", "'LDAP_...
Returns a ``list`` with the user's groups or ``None`` if unsuccessful. :param str user: User we want groups for.
[ "Returns", "a", "list", "with", "the", "user", "s", "groups", "or", "None", "if", "unsuccessful", "." ]
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L203-L252
train
211,618
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.get_group_members
def get_group_members(self, group): """Returns a ``list`` with the group's members or ``None`` if unsuccessful. :param str group: Group we want users for. """ conn = self.bind try: records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_GROUP_OBJECT_FILTER'], (group,)), [current_app.config['LDAP_GROUP_MEMBERS_FIELD']]) conn.unbind_s() if records: if current_app.config['LDAP_GROUP_MEMBERS_FIELD'] in \ records[0][1]: members = records[0][1][ current_app.config['LDAP_GROUP_MEMBERS_FIELD']] if sys.version_info[0] > 2: members = [m.decode('utf-8') for m in members] return members except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
python
def get_group_members(self, group): """Returns a ``list`` with the group's members or ``None`` if unsuccessful. :param str group: Group we want users for. """ conn = self.bind try: records = conn.search_s( current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE, ldap_filter.filter_format( current_app.config['LDAP_GROUP_OBJECT_FILTER'], (group,)), [current_app.config['LDAP_GROUP_MEMBERS_FIELD']]) conn.unbind_s() if records: if current_app.config['LDAP_GROUP_MEMBERS_FIELD'] in \ records[0][1]: members = records[0][1][ current_app.config['LDAP_GROUP_MEMBERS_FIELD']] if sys.version_info[0] > 2: members = [m.decode('utf-8') for m in members] return members except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
[ "def", "get_group_members", "(", "self", ",", "group", ")", ":", "conn", "=", "self", ".", "bind", "try", ":", "records", "=", "conn", ".", "search_s", "(", "current_app", ".", "config", "[", "'LDAP_BASE_DN'", "]", ",", "ldap", ".", "SCOPE_SUBTREE", ",",...
Returns a ``list`` with the group's members or ``None`` if unsuccessful. :param str group: Group we want users for.
[ "Returns", "a", "list", "with", "the", "group", "s", "members", "or", "None", "if", "unsuccessful", "." ]
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L254-L278
train
211,619
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.login_required
def login_required(func): """When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests do NOT require membership from a specific group. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user if the credentials are acceptable. :param func: The view function to decorate. """ @wraps(func) def wrapped(*args, **kwargs): if g.user is None: return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'], next=request.path)) return func(*args, **kwargs) return wrapped
python
def login_required(func): """When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests do NOT require membership from a specific group. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user if the credentials are acceptable. :param func: The view function to decorate. """ @wraps(func) def wrapped(*args, **kwargs): if g.user is None: return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'], next=request.path)) return func(*args, **kwargs) return wrapped
[ "def", "login_required", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "g", ".", "user", "is", "None", ":", "return", "redirect", "(", "url_for", "(", "current_ap...
When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests do NOT require membership from a specific group. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user if the credentials are acceptable. :param func: The view function to decorate.
[ "When", "applied", "to", "a", "view", "function", "any", "unauthenticated", "requests", "will", "be", "redirected", "to", "the", "view", "named", "in", "LDAP_LOGIN_VIEW", ".", "Authenticated", "requests", "do", "NOT", "require", "membership", "from", "a", "speci...
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L289-L308
train
211,620
admiralobvious/flask-simpleldap
flask_simpleldap/__init__.py
LDAP.group_required
def group_required(groups=None): """When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests are only permitted if they belong to one of the listed groups. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user and ``flask.g.ldap_groups`` to the authenticated user's groups if the credentials are acceptable. :param list groups: List of groups that should be able to access the view function. """ def wrapper(func): @wraps(func) def wrapped(*args, **kwargs): if g.user is None: return redirect( url_for(current_app.config['LDAP_LOGIN_VIEW'], next=request.path)) match = [group for group in groups if group in g.ldap_groups] if not match: abort(401) return func(*args, **kwargs) return wrapped return wrapper
python
def group_required(groups=None): """When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests are only permitted if they belong to one of the listed groups. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user and ``flask.g.ldap_groups`` to the authenticated user's groups if the credentials are acceptable. :param list groups: List of groups that should be able to access the view function. """ def wrapper(func): @wraps(func) def wrapped(*args, **kwargs): if g.user is None: return redirect( url_for(current_app.config['LDAP_LOGIN_VIEW'], next=request.path)) match = [group for group in groups if group in g.ldap_groups] if not match: abort(401) return func(*args, **kwargs) return wrapped return wrapper
[ "def", "group_required", "(", "groups", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "g", ".", "user", "is", "None", ...
When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated requests are only permitted if they belong to one of the listed groups. The login view is responsible for asking for credentials, checking them, and setting ``flask.g.user`` to the name of the authenticated user and ``flask.g.ldap_groups`` to the authenticated user's groups if the credentials are acceptable. :param list groups: List of groups that should be able to access the view function.
[ "When", "applied", "to", "a", "view", "function", "any", "unauthenticated", "requests", "will", "be", "redirected", "to", "the", "view", "named", "in", "LDAP_LOGIN_VIEW", ".", "Authenticated", "requests", "are", "only", "permitted", "if", "they", "belong", "to",...
c0554780f84c42866b241c0d68fd76aaaf065e02
https://github.com/admiralobvious/flask-simpleldap/blob/c0554780f84c42866b241c0d68fd76aaaf065e02/flask_simpleldap/__init__.py#L311-L340
train
211,621
KartikTalwar/Duolingo
duolingo.py
Duolingo.buy_streak_freeze
def buy_streak_freeze(self): """ figure out the users current learning language use this one as parameter for the shop """ lang = self.get_abbreviation_of(self.get_user_info()['learning_language_string']) if lang is None: raise Exception('No learning language found') try: self.buy_item('streak_freeze', lang) return True except AlreadyHaveStoreItemException: return False
python
def buy_streak_freeze(self): """ figure out the users current learning language use this one as parameter for the shop """ lang = self.get_abbreviation_of(self.get_user_info()['learning_language_string']) if lang is None: raise Exception('No learning language found') try: self.buy_item('streak_freeze', lang) return True except AlreadyHaveStoreItemException: return False
[ "def", "buy_streak_freeze", "(", "self", ")", ":", "lang", "=", "self", ".", "get_abbreviation_of", "(", "self", ".", "get_user_info", "(", ")", "[", "'learning_language_string'", "]", ")", "if", "lang", "is", "None", ":", "raise", "Exception", "(", "'No lea...
figure out the users current learning language use this one as parameter for the shop
[ "figure", "out", "the", "users", "current", "learning", "language", "use", "this", "one", "as", "parameter", "for", "the", "shop" ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L140-L152
train
211,622
KartikTalwar/Duolingo
duolingo.py
Duolingo._compute_dependency_order
def _compute_dependency_order(skills): """ Add a field to each skill indicating the order it was learned based on the skill's dependencies. Multiple skills will have the same position if they have the same dependencies. """ # Key skills by first dependency. Dependency sets can be uniquely # identified by one dependency in the set. dependency_to_skill = MultiDict([(skill['dependencies_name'][0] if skill['dependencies_name'] else '', skill) for skill in skills]) # Start with the first skill and trace the dependency graph through # skill, setting the order it was learned in. index = 0 previous_skill = '' while True: for skill in dependency_to_skill.getlist(previous_skill): skill['dependency_order'] = index index += 1 # Figure out the canonical dependency for the next set of skills. skill_names = set([skill['name'] for skill in dependency_to_skill.getlist(previous_skill)]) canonical_dependency = skill_names.intersection( set(dependency_to_skill.keys())) if canonical_dependency: previous_skill = canonical_dependency.pop() else: # Nothing depends on these skills, so we're done. break return skills
python
def _compute_dependency_order(skills): """ Add a field to each skill indicating the order it was learned based on the skill's dependencies. Multiple skills will have the same position if they have the same dependencies. """ # Key skills by first dependency. Dependency sets can be uniquely # identified by one dependency in the set. dependency_to_skill = MultiDict([(skill['dependencies_name'][0] if skill['dependencies_name'] else '', skill) for skill in skills]) # Start with the first skill and trace the dependency graph through # skill, setting the order it was learned in. index = 0 previous_skill = '' while True: for skill in dependency_to_skill.getlist(previous_skill): skill['dependency_order'] = index index += 1 # Figure out the canonical dependency for the next set of skills. skill_names = set([skill['name'] for skill in dependency_to_skill.getlist(previous_skill)]) canonical_dependency = skill_names.intersection( set(dependency_to_skill.keys())) if canonical_dependency: previous_skill = canonical_dependency.pop() else: # Nothing depends on these skills, so we're done. break return skills
[ "def", "_compute_dependency_order", "(", "skills", ")", ":", "# Key skills by first dependency. Dependency sets can be uniquely", "# identified by one dependency in the set.", "dependency_to_skill", "=", "MultiDict", "(", "[", "(", "skill", "[", "'dependencies_name'", "]", "[", ...
Add a field to each skill indicating the order it was learned based on the skill's dependencies. Multiple skills will have the same position if they have the same dependencies.
[ "Add", "a", "field", "to", "each", "skill", "indicating", "the", "order", "it", "was", "learned", "based", "on", "the", "skill", "s", "dependencies", ".", "Multiple", "skills", "will", "have", "the", "same", "position", "if", "they", "have", "the", "same",...
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L193-L228
train
211,623
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_languages
def get_languages(self, abbreviations=False): """ Get praticed languages. :param abbreviations: Get language as abbreviation or not :type abbreviations: bool :return: List of languages :rtype: list of str """ data = [] for lang in self.user_data.languages: if lang['learning']: if abbreviations: data.append(lang['language']) else: data.append(lang['language_string']) return data
python
def get_languages(self, abbreviations=False): """ Get praticed languages. :param abbreviations: Get language as abbreviation or not :type abbreviations: bool :return: List of languages :rtype: list of str """ data = [] for lang in self.user_data.languages: if lang['learning']: if abbreviations: data.append(lang['language']) else: data.append(lang['language_string']) return data
[ "def", "get_languages", "(", "self", ",", "abbreviations", "=", "False", ")", ":", "data", "=", "[", "]", "for", "lang", "in", "self", ".", "user_data", ".", "languages", ":", "if", "lang", "[", "'learning'", "]", ":", "if", "abbreviations", ":", "data...
Get praticed languages. :param abbreviations: Get language as abbreviation or not :type abbreviations: bool :return: List of languages :rtype: list of str
[ "Get", "praticed", "languages", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L237-L255
train
211,624
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_language_from_abbr
def get_language_from_abbr(self, abbr): """Get language full name from abbreviation.""" for language in self.user_data.languages: if language['language'] == abbr: return language['language_string'] return None
python
def get_language_from_abbr(self, abbr): """Get language full name from abbreviation.""" for language in self.user_data.languages: if language['language'] == abbr: return language['language_string'] return None
[ "def", "get_language_from_abbr", "(", "self", ",", "abbr", ")", ":", "for", "language", "in", "self", ".", "user_data", ".", "languages", ":", "if", "language", "[", "'language'", "]", "==", "abbr", ":", "return", "language", "[", "'language_string'", "]", ...
Get language full name from abbreviation.
[ "Get", "language", "full", "name", "from", "abbreviation", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L257-L262
train
211,625
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_abbreviation_of
def get_abbreviation_of(self, name): """Get abbreviation of a language.""" for language in self.user_data.languages: if language['language_string'] == name: return language['language'] return None
python
def get_abbreviation_of(self, name): """Get abbreviation of a language.""" for language in self.user_data.languages: if language['language_string'] == name: return language['language'] return None
[ "def", "get_abbreviation_of", "(", "self", ",", "name", ")", ":", "for", "language", "in", "self", ".", "user_data", ".", "languages", ":", "if", "language", "[", "'language_string'", "]", "==", "name", ":", "return", "language", "[", "'language'", "]", "r...
Get abbreviation of a language.
[ "Get", "abbreviation", "of", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L264-L269
train
211,626
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_language_details
def get_language_details(self, language): """Get user's status about a language.""" for lang in self.user_data.languages: if language == lang['language_string']: return lang return {}
python
def get_language_details(self, language): """Get user's status about a language.""" for lang in self.user_data.languages: if language == lang['language_string']: return lang return {}
[ "def", "get_language_details", "(", "self", ",", "language", ")", ":", "for", "lang", "in", "self", ".", "user_data", ".", "languages", ":", "if", "language", "==", "lang", "[", "'language_string'", "]", ":", "return", "lang", "return", "{", "}" ]
Get user's status about a language.
[ "Get", "user", "s", "status", "about", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L271-L277
train
211,627
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_certificates
def get_certificates(self): """Get user's certificates.""" for certificate in self.user_data.certificates: certificate['datetime'] = certificate['datetime'].strip() return self.user_data.certificates
python
def get_certificates(self): """Get user's certificates.""" for certificate in self.user_data.certificates: certificate['datetime'] = certificate['datetime'].strip() return self.user_data.certificates
[ "def", "get_certificates", "(", "self", ")", ":", "for", "certificate", "in", "self", ".", "user_data", ".", "certificates", ":", "certificate", "[", "'datetime'", "]", "=", "certificate", "[", "'datetime'", "]", ".", "strip", "(", ")", "return", "self", "...
Get user's certificates.
[ "Get", "user", "s", "certificates", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L289-L294
train
211,628
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_calendar
def get_calendar(self, language_abbr=None): """Get user's last actions.""" if language_abbr: if not self._is_current_language(language_abbr): self._switch_language(language_abbr) return self.user_data.language_data[language_abbr]['calendar'] else: return self.user_data.calendar
python
def get_calendar(self, language_abbr=None): """Get user's last actions.""" if language_abbr: if not self._is_current_language(language_abbr): self._switch_language(language_abbr) return self.user_data.language_data[language_abbr]['calendar'] else: return self.user_data.calendar
[ "def", "get_calendar", "(", "self", ",", "language_abbr", "=", "None", ")", ":", "if", "language_abbr", ":", "if", "not", "self", ".", "_is_current_language", "(", "language_abbr", ")", ":", "self", ".", "_switch_language", "(", "language_abbr", ")", "return",...
Get user's last actions.
[ "Get", "user", "s", "last", "actions", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L305-L312
train
211,629
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_language_progress
def get_language_progress(self, lang): """Get informations about user's progression in a language.""" if not self._is_current_language(lang): self._switch_language(lang) fields = ['streak', 'language_string', 'level_progress', 'num_skills_learned', 'level_percent', 'level_points', 'points_rank', 'next_level', 'level_left', 'language', 'points', 'fluency_score', 'level'] return self._make_dict(fields, self.user_data.language_data[lang])
python
def get_language_progress(self, lang): """Get informations about user's progression in a language.""" if not self._is_current_language(lang): self._switch_language(lang) fields = ['streak', 'language_string', 'level_progress', 'num_skills_learned', 'level_percent', 'level_points', 'points_rank', 'next_level', 'level_left', 'language', 'points', 'fluency_score', 'level'] return self._make_dict(fields, self.user_data.language_data[lang])
[ "def", "get_language_progress", "(", "self", ",", "lang", ")", ":", "if", "not", "self", ".", "_is_current_language", "(", "lang", ")", ":", "self", ".", "_switch_language", "(", "lang", ")", "fields", "=", "[", "'streak'", ",", "'language_string'", ",", "...
Get informations about user's progression in a language.
[ "Get", "informations", "about", "user", "s", "progression", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L314-L324
train
211,630
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_friends
def get_friends(self): """Get user's friends.""" for k, v in iter(self.user_data.language_data.items()): data = [] for friend in v['points_ranking_data']: temp = {'username': friend['username'], 'id': friend['id'], 'points': friend['points_data']['total'], 'languages': [i['language_string'] for i in friend['points_data']['languages']]} data.append(temp) return data
python
def get_friends(self): """Get user's friends.""" for k, v in iter(self.user_data.language_data.items()): data = [] for friend in v['points_ranking_data']: temp = {'username': friend['username'], 'id': friend['id'], 'points': friend['points_data']['total'], 'languages': [i['language_string'] for i in friend['points_data']['languages']]} data.append(temp) return data
[ "def", "get_friends", "(", "self", ")", ":", "for", "k", ",", "v", "in", "iter", "(", "self", ".", "user_data", ".", "language_data", ".", "items", "(", ")", ")", ":", "data", "=", "[", "]", "for", "friend", "in", "v", "[", "'points_ranking_data'", ...
Get user's friends.
[ "Get", "user", "s", "friends", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L326-L338
train
211,631
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_known_words
def get_known_words(self, lang): """Get a list of all words learned by user in a language.""" words = [] for topic in self.user_data.language_data[lang]['skills']: if topic['learned']: words += topic['words'] return set(words)
python
def get_known_words(self, lang): """Get a list of all words learned by user in a language.""" words = [] for topic in self.user_data.language_data[lang]['skills']: if topic['learned']: words += topic['words'] return set(words)
[ "def", "get_known_words", "(", "self", ",", "lang", ")", ":", "words", "=", "[", "]", "for", "topic", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", ":", "if", "topic", "[", "'learned'", "]", ":", "words...
Get a list of all words learned by user in a language.
[ "Get", "a", "list", "of", "all", "words", "learned", "by", "user", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L340-L346
train
211,632
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_learned_skills
def get_learned_skills(self, lang): """ Return the learned skill objects sorted by the order they were learned in. """ skills = [skill for skill in self.user_data.language_data[lang]['skills']] self._compute_dependency_order(skills) return [skill for skill in sorted(skills, key=lambda skill: skill['dependency_order']) if skill['learned']]
python
def get_learned_skills(self, lang): """ Return the learned skill objects sorted by the order they were learned in. """ skills = [skill for skill in self.user_data.language_data[lang]['skills']] self._compute_dependency_order(skills) return [skill for skill in sorted(skills, key=lambda skill: skill['dependency_order']) if skill['learned']]
[ "def", "get_learned_skills", "(", "self", ",", "lang", ")", ":", "skills", "=", "[", "skill", "for", "skill", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", "]", "self", ".", "_compute_dependency_order", "(", ...
Return the learned skill objects sorted by the order they were learned in.
[ "Return", "the", "learned", "skill", "objects", "sorted", "by", "the", "order", "they", "were", "learned", "in", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L348-L360
train
211,633
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_known_topics
def get_known_topics(self, lang): """Return the topics learned by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned']]
python
def get_known_topics(self, lang): """Return the topics learned by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned']]
[ "def", "get_known_topics", "(", "self", ",", "lang", ")", ":", "return", "[", "topic", "[", "'title'", "]", "for", "topic", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", "if", "topic", "[", "'learned'", "...
Return the topics learned by a user in a language.
[ "Return", "the", "topics", "learned", "by", "a", "user", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L362-L366
train
211,634
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_unknown_topics
def get_unknown_topics(self, lang): """Return the topics remaining to learn by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if not topic['learned']]
python
def get_unknown_topics(self, lang): """Return the topics remaining to learn by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if not topic['learned']]
[ "def", "get_unknown_topics", "(", "self", ",", "lang", ")", ":", "return", "[", "topic", "[", "'title'", "]", "for", "topic", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", "if", "not", "topic", "[", "'lea...
Return the topics remaining to learn by a user in a language.
[ "Return", "the", "topics", "remaining", "to", "learn", "by", "a", "user", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L368-L372
train
211,635
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_reviewable_topics
def get_reviewable_topics(self, lang): """Return the topics learned but not golden by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned'] and topic['strength'] < 1.0]
python
def get_reviewable_topics(self, lang): """Return the topics learned but not golden by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned'] and topic['strength'] < 1.0]
[ "def", "get_reviewable_topics", "(", "self", ",", "lang", ")", ":", "return", "[", "topic", "[", "'title'", "]", "for", "topic", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", "if", "topic", "[", "'learned'"...
Return the topics learned but not golden by a user in a language.
[ "Return", "the", "topics", "learned", "but", "not", "golden", "by", "a", "user", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L380-L384
train
211,636
KartikTalwar/Duolingo
duolingo.py
Duolingo.get_vocabulary
def get_vocabulary(self, language_abbr=None): """Get overview of user's vocabulary in a language.""" if not self.password: raise Exception("You must provide a password for this function") if language_abbr and not self._is_current_language(language_abbr): self._switch_language(language_abbr) overview_url = "https://www.duolingo.com/vocabulary/overview" overview_request = self._make_req(overview_url) overview = overview_request.json() return overview
python
def get_vocabulary(self, language_abbr=None): """Get overview of user's vocabulary in a language.""" if not self.password: raise Exception("You must provide a password for this function") if language_abbr and not self._is_current_language(language_abbr): self._switch_language(language_abbr) overview_url = "https://www.duolingo.com/vocabulary/overview" overview_request = self._make_req(overview_url) overview = overview_request.json() return overview
[ "def", "get_vocabulary", "(", "self", ",", "language_abbr", "=", "None", ")", ":", "if", "not", "self", ".", "password", ":", "raise", "Exception", "(", "\"You must provide a password for this function\"", ")", "if", "language_abbr", "and", "not", "self", ".", "...
Get overview of user's vocabulary in a language.
[ "Get", "overview", "of", "user", "s", "vocabulary", "in", "a", "language", "." ]
0f7e9a0d4bfa864ade82890fca3789679ef38bee
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L414-L425
train
211,637
coreGreenberet/homematicip-rest-api
homematicip/HomeMaticIPObject.py
HomeMaticIPObject.fire_update_event
def fire_update_event(self, *args, **kwargs): """Trigger the method tied to _on_update""" for _handler in self._on_update: _handler(*args, **kwargs)
python
def fire_update_event(self, *args, **kwargs): """Trigger the method tied to _on_update""" for _handler in self._on_update: _handler(*args, **kwargs)
[ "def", "fire_update_event", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "_handler", "in", "self", ".", "_on_update", ":", "_handler", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Trigger the method tied to _on_update
[ "Trigger", "the", "method", "tied", "to", "_on_update" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/HomeMaticIPObject.py#L24-L27
train
211,638
coreGreenberet/homematicip-rest-api
homematicip/home.py
Home.download_configuration
def download_configuration(self) -> str: """downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode """ return self._restCall( "home/getCurrentState", json.dumps(self._connection.clientCharacteristics) )
python
def download_configuration(self) -> str: """downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode """ return self._restCall( "home/getCurrentState", json.dumps(self._connection.clientCharacteristics) )
[ "def", "download_configuration", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_restCall", "(", "\"home/getCurrentState\"", ",", "json", ".", "dumps", "(", "self", ".", "_connection", ".", "clientCharacteristics", ")", ")" ]
downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode
[ "downloads", "the", "current", "configuration", "from", "the", "cloud", "Returns", "the", "downloaded", "configuration", "or", "an", "errorCode" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/home.py#L225-L233
train
211,639
coreGreenberet/homematicip-rest-api
homematicip/home.py
Home.get_security_zones_activation
def get_security_zones_activation(self) -> (bool, bool): """ returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed """ internal_active = False external_active = False for g in self.groups: if isinstance(g, SecurityZoneGroup): if g.label == "EXTERNAL": external_active = g.active elif g.label == "INTERNAL": internal_active = g.active return internal_active, external_active
python
def get_security_zones_activation(self) -> (bool, bool): """ returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed """ internal_active = False external_active = False for g in self.groups: if isinstance(g, SecurityZoneGroup): if g.label == "EXTERNAL": external_active = g.active elif g.label == "INTERNAL": internal_active = g.active return internal_active, external_active
[ "def", "get_security_zones_activation", "(", "self", ")", "->", "(", "bool", ",", "bool", ")", ":", "internal_active", "=", "False", "external_active", "=", "False", "for", "g", "in", "self", ".", "groups", ":", "if", "isinstance", "(", "g", ",", "Security...
returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed
[ "returns", "the", "value", "of", "the", "security", "zones", "if", "they", "are", "armed", "or", "not", "Returns", "internal", "True", "if", "the", "internal", "zone", "is", "armed", "external", "True", "if", "the", "external", "zone", "is", "armed" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/home.py#L459-L476
train
211,640
coreGreenberet/homematicip-rest-api
homematicip/aio/home.py
AsyncHome.enable_events
async def enable_events(self) -> asyncio.Task: """Connects to the websocket. Returns a listening task.""" return await self._connection.ws_connect( on_message=self._ws_on_message, on_error=self._ws_on_error )
python
async def enable_events(self) -> asyncio.Task: """Connects to the websocket. Returns a listening task.""" return await self._connection.ws_connect( on_message=self._ws_on_message, on_error=self._ws_on_error )
[ "async", "def", "enable_events", "(", "self", ")", "->", "asyncio", ".", "Task", ":", "return", "await", "self", ".", "_connection", ".", "ws_connect", "(", "on_message", "=", "self", ".", "_ws_on_message", ",", "on_error", "=", "self", ".", "_ws_on_error", ...
Connects to the websocket. Returns a listening task.
[ "Connects", "to", "the", "websocket", ".", "Returns", "a", "listening", "task", "." ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/aio/home.py#L63-L67
train
211,641
coreGreenberet/homematicip-rest-api
homematicip/device.py
Device.load_functionalChannels
def load_functionalChannels(self, groups: Iterable[Group]): """ this function will load the functionalChannels into the device """ self.functionalChannels = [] for channel in self._rawJSONData["functionalChannels"].values(): fc = self._parse_functionalChannel(channel, groups) self.functionalChannels.append(fc) self.functionalChannelCount = Counter( x.functionalChannelType for x in self.functionalChannels )
python
def load_functionalChannels(self, groups: Iterable[Group]): """ this function will load the functionalChannels into the device """ self.functionalChannels = [] for channel in self._rawJSONData["functionalChannels"].values(): fc = self._parse_functionalChannel(channel, groups) self.functionalChannels.append(fc) self.functionalChannelCount = Counter( x.functionalChannelType for x in self.functionalChannels )
[ "def", "load_functionalChannels", "(", "self", ",", "groups", ":", "Iterable", "[", "Group", "]", ")", ":", "self", ".", "functionalChannels", "=", "[", "]", "for", "channel", "in", "self", ".", "_rawJSONData", "[", "\"functionalChannels\"", "]", ".", "value...
this function will load the functionalChannels into the device
[ "this", "function", "will", "load", "the", "functionalChannels", "into", "the", "device" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/device.py#L126-L134
train
211,642
coreGreenberet/homematicip-rest-api
homematicip/device.py
FullFlushShutter.set_shutter_level
def set_shutter_level(self, level=0.0): """ sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall """ data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} return self._restCall("device/control/setShutterLevel", body=json.dumps(data))
python
def set_shutter_level(self, level=0.0): """ sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall """ data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} return self._restCall("device/control/setShutterLevel", body=json.dumps(data))
[ "def", "set_shutter_level", "(", "self", ",", "level", "=", "0.0", ")", ":", "data", "=", "{", "\"channelIndex\"", ":", "1", ",", "\"deviceId\"", ":", "self", ".", "id", ",", "\"shutterLevel\"", ":", "level", "}", "return", "self", ".", "_restCall", "(",...
sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall
[ "sets", "the", "shutter", "level" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/device.py#L938-L947
train
211,643
coreGreenberet/homematicip-rest-api
homematicip/device.py
FullFlushBlind.set_slats_level
def set_slats_level(self, slatsLevel=0.0, shutterLevel=None): """ sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value Returns: the result of the _restCall """ if shutterLevel is None: shutterLevel = self.shutterLevel data = { "channelIndex": 1, "deviceId": self.id, "slatsLevel": slatsLevel, "shutterLevel": shutterLevel, } return self._restCall("device/control/setSlatsLevel", json.dumps(data))
python
def set_slats_level(self, slatsLevel=0.0, shutterLevel=None): """ sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value Returns: the result of the _restCall """ if shutterLevel is None: shutterLevel = self.shutterLevel data = { "channelIndex": 1, "deviceId": self.id, "slatsLevel": slatsLevel, "shutterLevel": shutterLevel, } return self._restCall("device/control/setSlatsLevel", json.dumps(data))
[ "def", "set_slats_level", "(", "self", ",", "slatsLevel", "=", "0.0", ",", "shutterLevel", "=", "None", ")", ":", "if", "shutterLevel", "is", "None", ":", "shutterLevel", "=", "self", ".", "shutterLevel", "data", "=", "{", "\"channelIndex\"", ":", "1", ","...
sets the slats and shutter level Args: slatsLevel(float): the new level of the slats. 0.0 = open, 1.0 = closed, shutterLevel(float): the new level of the shutter. 0.0 = open, 1.0 = closed, None = use the current value Returns: the result of the _restCall
[ "sets", "the", "slats", "and", "shutter", "level" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/device.py#L994-L1011
train
211,644
coreGreenberet/homematicip-rest-api
homematicip/rule.py
Rule.set_label
def set_label(self, label): """ sets the label of the rule """ data = {"ruleId": self.id, "label": label} return self._restCall("rule/setRuleLabel", json.dumps(data))
python
def set_label(self, label): """ sets the label of the rule """ data = {"ruleId": self.id, "label": label} return self._restCall("rule/setRuleLabel", json.dumps(data))
[ "def", "set_label", "(", "self", ",", "label", ")", ":", "data", "=", "{", "\"ruleId\"", ":", "self", ".", "id", ",", "\"label\"", ":", "label", "}", "return", "self", ".", "_restCall", "(", "\"rule/setRuleLabel\"", ",", "json", ".", "dumps", "(", "dat...
sets the label of the rule
[ "sets", "the", "label", "of", "the", "rule" ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/rule.py#L33-L36
train
211,645
coreGreenberet/homematicip-rest-api
homematicip/aio/connection.py
AsyncConnection.api_call
async def api_call(self, path, body=None, full_url=False): """Make the actual call to the HMIP server. Throws `HmipWrongHttpStatusError` or `HmipConnectionError` if connection has failed or response is not correct.""" result = None if not full_url: path = self.full_url(path) for i in range(self._restCallRequestCounter): try: with async_timeout.timeout(self._restCallTimout, loop=self._loop): result = await self._websession.post( path, data=body, headers=self.headers ) if result.status == 200: if result.content_type == "application/json": ret = await result.json() else: ret = True return ret else: raise HmipWrongHttpStatusError except (asyncio.TimeoutError, aiohttp.ClientConnectionError): # Both exceptions occur when connecting to the server does # somehow not work. logger.debug("Connection timed out or another error occurred %s" % path) except JSONDecodeError as err: logger.exception(err) finally: if result is not None: await result.release() raise HmipConnectionError("Failed to connect to HomeMaticIp server")
python
async def api_call(self, path, body=None, full_url=False): """Make the actual call to the HMIP server. Throws `HmipWrongHttpStatusError` or `HmipConnectionError` if connection has failed or response is not correct.""" result = None if not full_url: path = self.full_url(path) for i in range(self._restCallRequestCounter): try: with async_timeout.timeout(self._restCallTimout, loop=self._loop): result = await self._websession.post( path, data=body, headers=self.headers ) if result.status == 200: if result.content_type == "application/json": ret = await result.json() else: ret = True return ret else: raise HmipWrongHttpStatusError except (asyncio.TimeoutError, aiohttp.ClientConnectionError): # Both exceptions occur when connecting to the server does # somehow not work. logger.debug("Connection timed out or another error occurred %s" % path) except JSONDecodeError as err: logger.exception(err) finally: if result is not None: await result.release() raise HmipConnectionError("Failed to connect to HomeMaticIp server")
[ "async", "def", "api_call", "(", "self", ",", "path", ",", "body", "=", "None", ",", "full_url", "=", "False", ")", ":", "result", "=", "None", "if", "not", "full_url", ":", "path", "=", "self", ".", "full_url", "(", "path", ")", "for", "i", "in", ...
Make the actual call to the HMIP server. Throws `HmipWrongHttpStatusError` or `HmipConnectionError` if connection has failed or response is not correct.
[ "Make", "the", "actual", "call", "to", "the", "HMIP", "server", ".", "Throws", "HmipWrongHttpStatusError", "or", "HmipConnectionError", "if", "connection", "has", "failed", "or", "response", "is", "not", "correct", "." ]
d4c8df53281577e01709f75cacb78b1a5a1d00db
https://github.com/coreGreenberet/homematicip-rest-api/blob/d4c8df53281577e01709f75cacb78b1a5a1d00db/homematicip/aio/connection.py#L76-L107
train
211,646
rckclmbr/pyportify
pyportify/gpsoauth/__init__.py
perform_master_login
def perform_master_login(email, password, android_id, service='ac2dm', device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Perform a master login, which is what Android does when you first add a Google account. Return a dict, eg:: { 'Auth': '...', 'Email': 'email@gmail.com', 'GooglePlusUpgrade': '1', 'LSID': '...', 'PicasaUser': 'My Name', 'RopRevision': '1', 'RopText': ' ', 'SID': '...', 'Token': 'oauth2rt_1/...', 'firstName': 'My', 'lastName': 'Name', 'services': 'hist,mail,googleme,...' } """ data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'add_account': 1, 'EncryptedPasswd': google.signature(email, password, android_key_7_3_29), 'service': service, 'source': 'android', 'androidId': android_id, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version, } return _perform_auth_request(data)
python
def perform_master_login(email, password, android_id, service='ac2dm', device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Perform a master login, which is what Android does when you first add a Google account. Return a dict, eg:: { 'Auth': '...', 'Email': 'email@gmail.com', 'GooglePlusUpgrade': '1', 'LSID': '...', 'PicasaUser': 'My Name', 'RopRevision': '1', 'RopText': ' ', 'SID': '...', 'Token': 'oauth2rt_1/...', 'firstName': 'My', 'lastName': 'Name', 'services': 'hist,mail,googleme,...' } """ data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'add_account': 1, 'EncryptedPasswd': google.signature(email, password, android_key_7_3_29), 'service': service, 'source': 'android', 'androidId': android_id, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version, } return _perform_auth_request(data)
[ "def", "perform_master_login", "(", "email", ",", "password", ",", "android_id", ",", "service", "=", "'ac2dm'", ",", "device_country", "=", "'us'", ",", "operatorCountry", "=", "'us'", ",", "lang", "=", "'en'", ",", "sdk_version", "=", "17", ")", ":", "da...
Perform a master login, which is what Android does when you first add a Google account. Return a dict, eg:: { 'Auth': '...', 'Email': 'email@gmail.com', 'GooglePlusUpgrade': '1', 'LSID': '...', 'PicasaUser': 'My Name', 'RopRevision': '1', 'RopText': ' ', 'SID': '...', 'Token': 'oauth2rt_1/...', 'firstName': 'My', 'lastName': 'Name', 'services': 'hist,mail,googleme,...' }
[ "Perform", "a", "master", "login", "which", "is", "what", "Android", "does", "when", "you", "first", "add", "a", "Google", "account", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/gpsoauth/__init__.py#L26-L67
train
211,647
rckclmbr/pyportify
pyportify/gpsoauth/__init__.py
perform_oauth
def perform_oauth(email, master_token, android_id, service, app, client_sig, device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Use a master token from master_login to perform OAuth to a specific Google service. Return a dict, eg:: { 'Auth': '...', 'LSID': '...', 'SID': '..', 'issueAdvice': 'auto', 'services': 'hist,mail,googleme,...' } To authenticate requests to this service, include a header ``Authorization: GoogleLogin auth=res['Auth']``. """ data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'EncryptedPasswd': master_token, 'service': service, 'source': 'android', 'androidId': android_id, 'app': app, 'client_sig': client_sig, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version } return _perform_auth_request(data)
python
def perform_oauth(email, master_token, android_id, service, app, client_sig, device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Use a master token from master_login to perform OAuth to a specific Google service. Return a dict, eg:: { 'Auth': '...', 'LSID': '...', 'SID': '..', 'issueAdvice': 'auto', 'services': 'hist,mail,googleme,...' } To authenticate requests to this service, include a header ``Authorization: GoogleLogin auth=res['Auth']``. """ data = { 'accountType': 'HOSTED_OR_GOOGLE', 'Email': email, 'has_permission': 1, 'EncryptedPasswd': master_token, 'service': service, 'source': 'android', 'androidId': android_id, 'app': app, 'client_sig': client_sig, 'device_country': device_country, 'operatorCountry': device_country, 'lang': lang, 'sdk_version': sdk_version } return _perform_auth_request(data)
[ "def", "perform_oauth", "(", "email", ",", "master_token", ",", "android_id", ",", "service", ",", "app", ",", "client_sig", ",", "device_country", "=", "'us'", ",", "operatorCountry", "=", "'us'", ",", "lang", "=", "'en'", ",", "sdk_version", "=", "17", "...
Use a master token from master_login to perform OAuth to a specific Google service. Return a dict, eg:: { 'Auth': '...', 'LSID': '...', 'SID': '..', 'issueAdvice': 'auto', 'services': 'hist,mail,googleme,...' } To authenticate requests to this service, include a header ``Authorization: GoogleLogin auth=res['Auth']``.
[ "Use", "a", "master", "token", "from", "master_login", "to", "perform", "OAuth", "to", "a", "specific", "Google", "service", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/gpsoauth/__init__.py#L70-L107
train
211,648
rckclmbr/pyportify
pyportify/pkcs1/primes.py
is_prime
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION, algorithm=None): '''Test if n is a prime number m - the integer to test rnd - the random number generator to use for the probalistic primality algorithms, k - the number of iterations to use for the probabilistic primality algorithms, algorithm - the primality algorithm to use, default is Miller-Rabin. The gmpy implementation is used if gmpy is installed. Return value: True is n seems prime, False otherwise. ''' if algorithm is None: algorithm = PRIME_ALGO if algorithm == 'gmpy-miller-rabin': if not gmpy: raise NotImplementedError return gmpy.is_prime(n, k) elif algorithm == 'miller-rabin': # miller rabin probability of primality is 1/4**k return miller_rabin(n, k, rnd=rnd) elif algorithm == 'solovay-strassen': # for jacobi it's 1/2**k return randomized_primality_testing(n, rnd=rnd, k=k*2) else: raise NotImplementedError
python
def is_prime(n, rnd=default_pseudo_random, k=DEFAULT_ITERATION, algorithm=None): '''Test if n is a prime number m - the integer to test rnd - the random number generator to use for the probalistic primality algorithms, k - the number of iterations to use for the probabilistic primality algorithms, algorithm - the primality algorithm to use, default is Miller-Rabin. The gmpy implementation is used if gmpy is installed. Return value: True is n seems prime, False otherwise. ''' if algorithm is None: algorithm = PRIME_ALGO if algorithm == 'gmpy-miller-rabin': if not gmpy: raise NotImplementedError return gmpy.is_prime(n, k) elif algorithm == 'miller-rabin': # miller rabin probability of primality is 1/4**k return miller_rabin(n, k, rnd=rnd) elif algorithm == 'solovay-strassen': # for jacobi it's 1/2**k return randomized_primality_testing(n, rnd=rnd, k=k*2) else: raise NotImplementedError
[ "def", "is_prime", "(", "n", ",", "rnd", "=", "default_pseudo_random", ",", "k", "=", "DEFAULT_ITERATION", ",", "algorithm", "=", "None", ")", ":", "if", "algorithm", "is", "None", ":", "algorithm", "=", "PRIME_ALGO", "if", "algorithm", "==", "'gmpy-miller-r...
Test if n is a prime number m - the integer to test rnd - the random number generator to use for the probalistic primality algorithms, k - the number of iterations to use for the probabilistic primality algorithms, algorithm - the primality algorithm to use, default is Miller-Rabin. The gmpy implementation is used if gmpy is installed. Return value: True is n seems prime, False otherwise.
[ "Test", "if", "n", "is", "a", "prime", "number" ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primes.py#L19-L47
train
211,649
rckclmbr/pyportify
pyportify/pkcs1/primes.py
jacobi_witness
def jacobi_witness(x, n): '''Returns False if n is an Euler pseudo-prime with base x, and True otherwise. ''' j = jacobi(x, n) % n f = pow(x, n >> 1, n) return j != f
python
def jacobi_witness(x, n): '''Returns False if n is an Euler pseudo-prime with base x, and True otherwise. ''' j = jacobi(x, n) % n f = pow(x, n >> 1, n) return j != f
[ "def", "jacobi_witness", "(", "x", ",", "n", ")", ":", "j", "=", "jacobi", "(", "x", ",", "n", ")", "%", "n", "f", "=", "pow", "(", "x", ",", "n", ">>", "1", ",", "n", ")", "return", "j", "!=", "f" ]
Returns False if n is an Euler pseudo-prime with base x, and True otherwise.
[ "Returns", "False", "if", "n", "is", "an", "Euler", "pseudo", "-", "prime", "with", "base", "x", "and", "True", "otherwise", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primes.py#L100-L106
train
211,650
rckclmbr/pyportify
pyportify/pkcs1/primes.py
miller_rabin
def miller_rabin(n, k, rnd=default_pseudo_random): ''' Pure python implementation of the Miller-Rabin algorithm. n - the integer number to test, k - the number of iteration, the probability of n being prime if the algorithm returns True is 1/2**k, rnd - a random generator ''' s = 0 d = n-1 # Find nearest power of 2 s = primitives.integer_bit_size(n) # Find greatest factor which is a power of 2 s = fractions.gcd(2**s, n-1) d = (n-1) // s s = primitives.integer_bit_size(s) - 1 while k: k = k - 1 a = rnd.randint(2, n-2) x = pow(a, d, n) if x == 1 or x == n - 1: continue for r in range(1, s-1): x = pow(x, 2, n) if x == 1: return False if x == n - 1: break else: return False return True
python
def miller_rabin(n, k, rnd=default_pseudo_random): ''' Pure python implementation of the Miller-Rabin algorithm. n - the integer number to test, k - the number of iteration, the probability of n being prime if the algorithm returns True is 1/2**k, rnd - a random generator ''' s = 0 d = n-1 # Find nearest power of 2 s = primitives.integer_bit_size(n) # Find greatest factor which is a power of 2 s = fractions.gcd(2**s, n-1) d = (n-1) // s s = primitives.integer_bit_size(s) - 1 while k: k = k - 1 a = rnd.randint(2, n-2) x = pow(a, d, n) if x == 1 or x == n - 1: continue for r in range(1, s-1): x = pow(x, 2, n) if x == 1: return False if x == n - 1: break else: return False return True
[ "def", "miller_rabin", "(", "n", ",", "k", ",", "rnd", "=", "default_pseudo_random", ")", ":", "s", "=", "0", "d", "=", "n", "-", "1", "# Find nearest power of 2", "s", "=", "primitives", ".", "integer_bit_size", "(", "n", ")", "# Find greatest factor which ...
Pure python implementation of the Miller-Rabin algorithm. n - the integer number to test, k - the number of iteration, the probability of n being prime if the algorithm returns True is 1/2**k, rnd - a random generator
[ "Pure", "python", "implementation", "of", "the", "Miller", "-", "Rabin", "algorithm", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primes.py#L135-L166
train
211,651
rckclmbr/pyportify
pyportify/util.py
find_closest_match
def find_closest_match(target_track, tracks): """ Return closest match to target track """ track = None # Get a list of (track, artist match ratio, name match ratio) tracks_with_match_ratio = [( track, get_similarity(target_track.artist, track.artist), get_similarity(target_track.name, track.name), ) for track in tracks] # Sort by artist then by title sorted_tracks = sorted( tracks_with_match_ratio, key=lambda t: (t[1], t[2]), reverse=True # Descending, highest match ratio first ) if sorted_tracks: track = sorted_tracks[0][0] # Closest match to query return track
python
def find_closest_match(target_track, tracks): """ Return closest match to target track """ track = None # Get a list of (track, artist match ratio, name match ratio) tracks_with_match_ratio = [( track, get_similarity(target_track.artist, track.artist), get_similarity(target_track.name, track.name), ) for track in tracks] # Sort by artist then by title sorted_tracks = sorted( tracks_with_match_ratio, key=lambda t: (t[1], t[2]), reverse=True # Descending, highest match ratio first ) if sorted_tracks: track = sorted_tracks[0][0] # Closest match to query return track
[ "def", "find_closest_match", "(", "target_track", ",", "tracks", ")", ":", "track", "=", "None", "# Get a list of (track, artist match ratio, name match ratio)", "tracks_with_match_ratio", "=", "[", "(", "track", ",", "get_similarity", "(", "target_track", ".", "artist", ...
Return closest match to target track
[ "Return", "closest", "match", "to", "target", "track" ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/util.py#L35-L54
train
211,652
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
integer_ceil
def integer_ceil(a, b): '''Return the ceil integer of a div b.''' quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
python
def integer_ceil(a, b): '''Return the ceil integer of a div b.''' quanta, mod = divmod(a, b) if mod: quanta += 1 return quanta
[ "def", "integer_ceil", "(", "a", ",", "b", ")", ":", "quanta", ",", "mod", "=", "divmod", "(", "a", ",", "b", ")", "if", "mod", ":", "quanta", "+=", "1", "return", "quanta" ]
Return the ceil integer of a div b.
[ "Return", "the", "ceil", "integer", "of", "a", "div", "b", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L14-L19
train
211,653
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
integer_byte_size
def integer_byte_size(n): '''Returns the number of bytes necessary to store the integer n.''' quanta, mod = divmod(integer_bit_size(n), 8) if mod or n == 0: quanta += 1 return quanta
python
def integer_byte_size(n): '''Returns the number of bytes necessary to store the integer n.''' quanta, mod = divmod(integer_bit_size(n), 8) if mod or n == 0: quanta += 1 return quanta
[ "def", "integer_byte_size", "(", "n", ")", ":", "quanta", ",", "mod", "=", "divmod", "(", "integer_bit_size", "(", "n", ")", ",", "8", ")", "if", "mod", "or", "n", "==", "0", ":", "quanta", "+=", "1", "return", "quanta" ]
Returns the number of bytes necessary to store the integer n.
[ "Returns", "the", "number", "of", "bytes", "necessary", "to", "store", "the", "integer", "n", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L22-L27
train
211,654
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
i2osp
def i2osp(x, x_len): '''Converts the integer x to its big-endian representation of length x_len. ''' if x > 256**x_len: raise exceptions.IntegerTooLarge h = hex(x)[2:] if h[-1] == 'L': h = h[:-1] if len(h) & 1 == 1: h = '0%s' % h x = binascii.unhexlify(h) return b'\x00' * int(x_len-len(x)) + x
python
def i2osp(x, x_len): '''Converts the integer x to its big-endian representation of length x_len. ''' if x > 256**x_len: raise exceptions.IntegerTooLarge h = hex(x)[2:] if h[-1] == 'L': h = h[:-1] if len(h) & 1 == 1: h = '0%s' % h x = binascii.unhexlify(h) return b'\x00' * int(x_len-len(x)) + x
[ "def", "i2osp", "(", "x", ",", "x_len", ")", ":", "if", "x", ">", "256", "**", "x_len", ":", "raise", "exceptions", ".", "IntegerTooLarge", "h", "=", "hex", "(", "x", ")", "[", "2", ":", "]", "if", "h", "[", "-", "1", "]", "==", "'L'", ":", ...
Converts the integer x to its big-endian representation of length x_len.
[ "Converts", "the", "integer", "x", "to", "its", "big", "-", "endian", "representation", "of", "length", "x_len", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L67-L79
train
211,655
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
string_xor
def string_xor(a, b): '''Computes the XOR operator between two byte strings. If the strings are of different lengths, the result string is as long as the shorter. ''' if sys.version_info[0] < 3: return ''.join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b))) else: return bytes(x ^ y for (x, y) in zip(a, b))
python
def string_xor(a, b): '''Computes the XOR operator between two byte strings. If the strings are of different lengths, the result string is as long as the shorter. ''' if sys.version_info[0] < 3: return ''.join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b))) else: return bytes(x ^ y for (x, y) in zip(a, b))
[ "def", "string_xor", "(", "a", ",", "b", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "return", "''", ".", "join", "(", "(", "chr", "(", "ord", "(", "x", ")", "^", "ord", "(", "y", ")", ")", "for", "(", "x", "...
Computes the XOR operator between two byte strings. If the strings are of different lengths, the result string is as long as the shorter.
[ "Computes", "the", "XOR", "operator", "between", "two", "byte", "strings", ".", "If", "the", "strings", "are", "of", "different", "lengths", "the", "result", "string", "is", "as", "long", "as", "the", "shorter", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L90-L97
train
211,656
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
get_nonzero_random_bytes
def get_nonzero_random_bytes(length, rnd=default_crypto_random): ''' Accumulate random bit string and remove \0 bytes until the needed length is obtained. ''' result = [] i = 0 while i < length: rnd = rnd.getrandbits(12*length) s = i2osp(rnd, 3*length) s = s.replace('\x00', '') result.append(s) i += len(s) return (''.join(result))[:length]
python
def get_nonzero_random_bytes(length, rnd=default_crypto_random): ''' Accumulate random bit string and remove \0 bytes until the needed length is obtained. ''' result = [] i = 0 while i < length: rnd = rnd.getrandbits(12*length) s = i2osp(rnd, 3*length) s = s.replace('\x00', '') result.append(s) i += len(s) return (''.join(result))[:length]
[ "def", "get_nonzero_random_bytes", "(", "length", ",", "rnd", "=", "default_crypto_random", ")", ":", "result", "=", "[", "]", "i", "=", "0", "while", "i", "<", "length", ":", "rnd", "=", "rnd", ".", "getrandbits", "(", "12", "*", "length", ")", "s", ...
Accumulate random bit string and remove \0 bytes until the needed length is obtained.
[ "Accumulate", "random", "bit", "string", "and", "remove", "\\", "0", "bytes", "until", "the", "needed", "length", "is", "obtained", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L105-L118
train
211,657
rckclmbr/pyportify
pyportify/pkcs1/primitives.py
constant_time_cmp
def constant_time_cmp(a, b): '''Compare two strings using constant time.''' result = True for x, y in zip(a, b): result &= (x == y) return result
python
def constant_time_cmp(a, b): '''Compare two strings using constant time.''' result = True for x, y in zip(a, b): result &= (x == y) return result
[ "def", "constant_time_cmp", "(", "a", ",", "b", ")", ":", "result", "=", "True", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ":", "result", "&=", "(", "x", "==", "y", ")", "return", "result" ]
Compare two strings using constant time.
[ "Compare", "two", "strings", "using", "constant", "time", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L121-L126
train
211,658
rckclmbr/pyportify
pyportify/pkcs1/rsaes_oaep.py
encrypt
def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1, seed=None, rnd=default_crypto_random): '''Encrypt a byte message using a RSA public key and the OAEP wrapping algorithm, Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function seed - a seed to use instead of generating it using a random generator rnd - a random generator class, respecting the random generator interface from the random module, if seed is None, it is used to generate it. Return value: the encrypted string of the same length as the public key ''' hash = hash_class() h_len = hash.digest_size k = public_key.byte_size max_message_length = k - 2 * h_len - 2 if len(message) > max_message_length: raise exceptions.MessageTooLong hash.update(label) label_hash = hash.digest() ps = b'\0' * int(max_message_length - len(message)) db = b''.join((label_hash, ps, b'\x01', message)) if not seed: seed = primitives.i2osp(rnd.getrandbits(h_len*8), h_len) db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class) masked_db = primitives.string_xor(db, db_mask) seed_mask = mgf(masked_db, h_len, hash_class=hash_class) masked_seed = primitives.string_xor(seed, seed_mask) em = b''.join((b'\x00', masked_seed, masked_db)) m = primitives.os2ip(em) c = public_key.rsaep(m) output = primitives.i2osp(c, k) return output
python
def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1, seed=None, rnd=default_crypto_random): '''Encrypt a byte message using a RSA public key and the OAEP wrapping algorithm, Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function seed - a seed to use instead of generating it using a random generator rnd - a random generator class, respecting the random generator interface from the random module, if seed is None, it is used to generate it. Return value: the encrypted string of the same length as the public key ''' hash = hash_class() h_len = hash.digest_size k = public_key.byte_size max_message_length = k - 2 * h_len - 2 if len(message) > max_message_length: raise exceptions.MessageTooLong hash.update(label) label_hash = hash.digest() ps = b'\0' * int(max_message_length - len(message)) db = b''.join((label_hash, ps, b'\x01', message)) if not seed: seed = primitives.i2osp(rnd.getrandbits(h_len*8), h_len) db_mask = mgf(seed, k - h_len - 1, hash_class=hash_class) masked_db = primitives.string_xor(db, db_mask) seed_mask = mgf(masked_db, h_len, hash_class=hash_class) masked_seed = primitives.string_xor(seed, seed_mask) em = b''.join((b'\x00', masked_seed, masked_db)) m = primitives.os2ip(em) c = public_key.rsaep(m) output = primitives.i2osp(c, k) return output
[ "def", "encrypt", "(", "public_key", ",", "message", ",", "label", "=", "b''", ",", "hash_class", "=", "hashlib", ".", "sha1", ",", "mgf", "=", "mgf", ".", "mgf1", ",", "seed", "=", "None", ",", "rnd", "=", "default_crypto_random", ")", ":", "hash", ...
Encrypt a byte message using a RSA public key and the OAEP wrapping algorithm, Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function seed - a seed to use instead of generating it using a random generator rnd - a random generator class, respecting the random generator interface from the random module, if seed is None, it is used to generate it. Return value: the encrypted string of the same length as the public key
[ "Encrypt", "a", "byte", "message", "using", "a", "RSA", "public", "key", "and", "the", "OAEP", "wrapping", "algorithm" ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/rsaes_oaep.py#L9-L50
train
211,659
rckclmbr/pyportify
pyportify/pkcs1/rsaes_oaep.py
decrypt
def decrypt(private_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1): '''Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function Return value: the string before encryption (decrypted) ''' hash = hash_class() h_len = hash.digest_size k = private_key.byte_size # 1. check length if len(message) != k or k < 2 * h_len + 2: raise ValueError('decryption error') # 2. RSA decryption c = primitives.os2ip(message) m = private_key.rsadp(c) em = primitives.i2osp(m, k) # 4. EME-OAEP decoding hash.update(label) label_hash = hash.digest() y, masked_seed, masked_db = em[0], em[1:h_len+1], em[1+h_len:] if y != b'\x00' and y != 0: raise ValueError('decryption error') seed_mask = mgf(masked_db, h_len) seed = primitives.string_xor(masked_seed, seed_mask) db_mask = mgf(seed, k - h_len - 1) db = primitives.string_xor(masked_db, db_mask) label_hash_prime, rest = db[:h_len], db[h_len:] i = rest.find(b'\x01') if i == -1: raise exceptions.DecryptionError if rest[:i].strip(b'\x00') != b'': print(rest[:i].strip(b'\x00')) raise exceptions.DecryptionError m = rest[i+1:] if label_hash_prime != label_hash: raise exceptions.DecryptionError return m
python
def decrypt(private_key, message, label=b'', hash_class=hashlib.sha1, mgf=mgf.mgf1): '''Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function Return value: the string before encryption (decrypted) ''' hash = hash_class() h_len = hash.digest_size k = private_key.byte_size # 1. check length if len(message) != k or k < 2 * h_len + 2: raise ValueError('decryption error') # 2. RSA decryption c = primitives.os2ip(message) m = private_key.rsadp(c) em = primitives.i2osp(m, k) # 4. EME-OAEP decoding hash.update(label) label_hash = hash.digest() y, masked_seed, masked_db = em[0], em[1:h_len+1], em[1+h_len:] if y != b'\x00' and y != 0: raise ValueError('decryption error') seed_mask = mgf(masked_db, h_len) seed = primitives.string_xor(masked_seed, seed_mask) db_mask = mgf(seed, k - h_len - 1) db = primitives.string_xor(masked_db, db_mask) label_hash_prime, rest = db[:h_len], db[h_len:] i = rest.find(b'\x01') if i == -1: raise exceptions.DecryptionError if rest[:i].strip(b'\x00') != b'': print(rest[:i].strip(b'\x00')) raise exceptions.DecryptionError m = rest[i+1:] if label_hash_prime != label_hash: raise exceptions.DecryptionError return m
[ "def", "decrypt", "(", "private_key", ",", "message", ",", "label", "=", "b''", ",", "hash_class", "=", "hashlib", ".", "sha1", ",", "mgf", "=", "mgf", ".", "mgf1", ")", ":", "hash", "=", "hash_class", "(", ")", "h_len", "=", "hash", ".", "digest_siz...
Decrypt a byte message using a RSA private key and the OAEP wrapping algorithm Parameters: public_key - an RSA public key message - a byte string label - a label a per-se PKCS#1 standard hash_class - a Python class for a message digest algorithme respecting the hashlib interface mgf1 - a mask generation function Return value: the string before encryption (decrypted)
[ "Decrypt", "a", "byte", "message", "using", "a", "RSA", "private", "key", "and", "the", "OAEP", "wrapping", "algorithm" ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/rsaes_oaep.py#L53-L99
train
211,660
rckclmbr/pyportify
pyportify/pkcs1/keys.py
generate_key_pair
def generate_key_pair(size=512, number=2, rnd=default_crypto_random, k=DEFAULT_ITERATION, primality_algorithm=None, strict_size=True, e=0x10001): '''Generates an RSA key pair. size: the bit size of the modulus, default to 512. number: the number of primes to use, default to 2. rnd: the random number generator to use, default to SystemRandom from the random library. k: the number of iteration to use for the probabilistic primality tests. primality_algorithm: the primality algorithm to use. strict_size: whether to use size as a lower bound or a strict goal. e: the public key exponent. Returns the pair (public_key, private_key). ''' primes = [] lbda = 1 bits = size // number + 1 n = 1 while len(primes) < number: if number - len(primes) == 1: bits = size - primitives.integer_bit_size(n) + 1 prime = get_prime(bits, rnd, k, algorithm=primality_algorithm) if prime in primes: continue if e is not None and fractions.gcd(e, lbda) != 1: continue if (strict_size and number - len(primes) == 1 and primitives.integer_bit_size(n*prime) != size): continue primes.append(prime) n *= prime lbda *= prime - 1 if e is None: e = 0x10001 while e < lbda: if fractions.gcd(e, lbda) == 1: break e += 2 assert 3 <= e <= n-1 public = RsaPublicKey(n, e) private = MultiPrimeRsaPrivateKey(primes, e, blind=True, rnd=rnd) return public, private
python
def generate_key_pair(size=512, number=2, rnd=default_crypto_random, k=DEFAULT_ITERATION, primality_algorithm=None, strict_size=True, e=0x10001): '''Generates an RSA key pair. size: the bit size of the modulus, default to 512. number: the number of primes to use, default to 2. rnd: the random number generator to use, default to SystemRandom from the random library. k: the number of iteration to use for the probabilistic primality tests. primality_algorithm: the primality algorithm to use. strict_size: whether to use size as a lower bound or a strict goal. e: the public key exponent. Returns the pair (public_key, private_key). ''' primes = [] lbda = 1 bits = size // number + 1 n = 1 while len(primes) < number: if number - len(primes) == 1: bits = size - primitives.integer_bit_size(n) + 1 prime = get_prime(bits, rnd, k, algorithm=primality_algorithm) if prime in primes: continue if e is not None and fractions.gcd(e, lbda) != 1: continue if (strict_size and number - len(primes) == 1 and primitives.integer_bit_size(n*prime) != size): continue primes.append(prime) n *= prime lbda *= prime - 1 if e is None: e = 0x10001 while e < lbda: if fractions.gcd(e, lbda) == 1: break e += 2 assert 3 <= e <= n-1 public = RsaPublicKey(n, e) private = MultiPrimeRsaPrivateKey(primes, e, blind=True, rnd=rnd) return public, private
[ "def", "generate_key_pair", "(", "size", "=", "512", ",", "number", "=", "2", ",", "rnd", "=", "default_crypto_random", ",", "k", "=", "DEFAULT_ITERATION", ",", "primality_algorithm", "=", "None", ",", "strict_size", "=", "True", ",", "e", "=", "0x10001", ...
Generates an RSA key pair. size: the bit size of the modulus, default to 512. number: the number of primes to use, default to 2. rnd: the random number generator to use, default to SystemRandom from the random library. k: the number of iteration to use for the probabilistic primality tests. primality_algorithm: the primality algorithm to use. strict_size: whether to use size as a lower bound or a strict goal. e: the public key exponent. Returns the pair (public_key, private_key).
[ "Generates", "an", "RSA", "key", "pair", "." ]
696a1caad8a47b191f3bec44cc8fc3c437779512
https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/keys.py#L122-L173
train
211,661
click-contrib/click-completion
click_completion/core.py
do_zsh_complete
def do_zsh_complete(cli, prog_name): """Do the zsh completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise """ commandline = os.environ['COMMANDLINE'] args = split_args(commandline)[1:] if args and not commandline.endswith(' '): incomplete = args[-1] args = args[:-1] else: incomplete = '' def escape(s): return s.replace('"', '""').replace("'", "''").replace('$', '\\$').replace('`', '\\`') res = [] for item, help in get_choices(cli, prog_name, args, incomplete): if help: res.append(r'"%s"\:"%s"' % (escape(item), escape(help))) else: res.append('"%s"' % escape(item)) if res: echo("_arguments '*: :((%s))'" % '\n'.join(res)) else: echo("_files") return True
python
def do_zsh_complete(cli, prog_name): """Do the zsh completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise """ commandline = os.environ['COMMANDLINE'] args = split_args(commandline)[1:] if args and not commandline.endswith(' '): incomplete = args[-1] args = args[:-1] else: incomplete = '' def escape(s): return s.replace('"', '""').replace("'", "''").replace('$', '\\$').replace('`', '\\`') res = [] for item, help in get_choices(cli, prog_name, args, incomplete): if help: res.append(r'"%s"\:"%s"' % (escape(item), escape(help))) else: res.append('"%s"' % escape(item)) if res: echo("_arguments '*: :((%s))'" % '\n'.join(res)) else: echo("_files") return True
[ "def", "do_zsh_complete", "(", "cli", ",", "prog_name", ")", ":", "commandline", "=", "os", ".", "environ", "[", "'COMMANDLINE'", "]", "args", "=", "split_args", "(", "commandline", ")", "[", "1", ":", "]", "if", "args", "and", "not", "commandline", ".",...
Do the zsh completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise
[ "Do", "the", "zsh", "completion" ]
49cae2e0fb05cfcfc03e813cc533bc04110d73df
https://github.com/click-contrib/click-completion/blob/49cae2e0fb05cfcfc03e813cc533bc04110d73df/click_completion/core.py#L205-L241
train
211,662
guzzle/guzzle_sphinx_theme
guzzle_sphinx_theme/__init__.py
setup
def setup(app): """Setup conntects events to the sitemap builder""" app.connect('html-page-context', add_html_link) app.connect('build-finished', create_sitemap) app.set_translator('html', HTMLTranslator) app.sitemap_links = []
python
def setup(app): """Setup conntects events to the sitemap builder""" app.connect('html-page-context', add_html_link) app.connect('build-finished', create_sitemap) app.set_translator('html', HTMLTranslator) app.sitemap_links = []
[ "def", "setup", "(", "app", ")", ":", "app", ".", "connect", "(", "'html-page-context'", ",", "add_html_link", ")", "app", ".", "connect", "(", "'build-finished'", ",", "create_sitemap", ")", "app", ".", "set_translator", "(", "'html'", ",", "HTMLTranslator", ...
Setup conntects events to the sitemap builder
[ "Setup", "conntects", "events", "to", "the", "sitemap", "builder" ]
eefd45b79383b1b4aab1607444e41366fd1348a6
https://github.com/guzzle/guzzle_sphinx_theme/blob/eefd45b79383b1b4aab1607444e41366fd1348a6/guzzle_sphinx_theme/__init__.py#L15-L20
train
211,663
django-parler/django-parler
parler/templatetags/parler_tags.py
get_translated_url
def get_translated_url(context, lang_code, object=None): """ Get the proper URL for this page in a different language. Note that this algorithm performs a "best effect" approach to give a proper URL. To make sure the proper view URL is returned, add the :class:`~parler.views.ViewUrlMixin` to your view. Example, to build a language menu:: <ul> {% for lang_code, title in LANGUAGES %} {% get_language_info for lang_code as lang %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<li{% if lang_code == LANGUAGE_CODE %} class="is-selected"{% endif %}><a href="{{ tr_url }}" hreflang="{{ lang_code }}">{{ lang.name_local|capfirst }}</a></li>{% endif %} {% endfor %} </ul> Or to inform search engines about the translated pages:: {% for lang_code, title in LANGUAGES %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<link rel="alternate" hreflang="{{ lang_code }}" href="{{ tr_url }}" />{% endif %} {% endfor %} Note that using this tag is not thread-safe if the object is shared between threads. It temporary changes the current language of the view object. The query string of the current page is preserved in the translated URL. When the ``object`` variable is explicitly provided however, the query string will not be added. In such situation, *django-parler* assumes that the object may point to a completely different page, hence to query string is added. """ view = context.get('view', None) request = context['request'] if object is not None: # Cannot reliable determine whether the current page is being translated, # or the template code provides a custom object to translate. # Hence, not passing the querystring of the current page qs = '' else: # Try a few common object variables, the SingleObjectMixin object, # The Django CMS "current_page" variable, or the "page" from django-fluent-pages and Mezzanine. # This makes this tag work with most CMSes out of the box. object = context.get('object', None) \ or context.get('current_page', None) \ or context.get('page', None) # Assuming current page, preserve query string filters. qs = request.META.get('QUERY_STRING', '') try: if view is not None: # Allow a view to specify what the URL should be. # This handles situations where the slug might be translated, # and gives you complete control over the results of this template tag. get_view_url = getattr(view, 'get_view_url', None) if get_view_url: with smart_override(lang_code): return _url_qs(view.get_view_url(), qs) # Now, the "best effort" part starts. # See if it's a DetailView that exposes the object. if object is None: object = getattr(view, 'object', None) if object is not None and hasattr(object, 'get_absolute_url'): # There is an object, get the URL in the different language. # NOTE: this *assumes* that there is a detail view, not some edit view. # In such case, a language menu would redirect a user from the edit page # to a detail page; which is still way better a 404 or homepage. if isinstance(object, TranslatableModel): # Need to handle object URL translations. # Just using smart_override() should be enough, as a translated object # should use `switch_language(self)` internally before returning an URL. # However, it doesn't hurt to help a bit here. with switch_language(object, lang_code): return _url_qs(object.get_absolute_url(), qs) else: # Always switch the language before resolving, so i18n_patterns() are supported. with smart_override(lang_code): return _url_qs(object.get_absolute_url(), qs) except TranslationDoesNotExist: # Typically projects have a fallback language, so even unknown languages will return something. # This either means fallbacks are disabled, or the fallback language is not found! return '' # Just reverse the current URL again in a new language, and see where we end up. # This doesn't handle translated slugs, but will resolve to the proper view name. resolver_match = request.resolver_match if resolver_match is None: # Can't resolve the page itself, the page is apparently a 404. # This can also happen for the homepage in an i18n_patterns situation. return '' with smart_override(lang_code): clean_kwargs = _cleanup_urlpattern_kwargs(resolver_match.kwargs) return _url_qs(reverse(resolver_match.view_name, args=resolver_match.args, kwargs=clean_kwargs, current_app=resolver_match.app_name), qs)
python
def get_translated_url(context, lang_code, object=None): """ Get the proper URL for this page in a different language. Note that this algorithm performs a "best effect" approach to give a proper URL. To make sure the proper view URL is returned, add the :class:`~parler.views.ViewUrlMixin` to your view. Example, to build a language menu:: <ul> {% for lang_code, title in LANGUAGES %} {% get_language_info for lang_code as lang %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<li{% if lang_code == LANGUAGE_CODE %} class="is-selected"{% endif %}><a href="{{ tr_url }}" hreflang="{{ lang_code }}">{{ lang.name_local|capfirst }}</a></li>{% endif %} {% endfor %} </ul> Or to inform search engines about the translated pages:: {% for lang_code, title in LANGUAGES %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<link rel="alternate" hreflang="{{ lang_code }}" href="{{ tr_url }}" />{% endif %} {% endfor %} Note that using this tag is not thread-safe if the object is shared between threads. It temporary changes the current language of the view object. The query string of the current page is preserved in the translated URL. When the ``object`` variable is explicitly provided however, the query string will not be added. In such situation, *django-parler* assumes that the object may point to a completely different page, hence to query string is added. """ view = context.get('view', None) request = context['request'] if object is not None: # Cannot reliable determine whether the current page is being translated, # or the template code provides a custom object to translate. # Hence, not passing the querystring of the current page qs = '' else: # Try a few common object variables, the SingleObjectMixin object, # The Django CMS "current_page" variable, or the "page" from django-fluent-pages and Mezzanine. # This makes this tag work with most CMSes out of the box. object = context.get('object', None) \ or context.get('current_page', None) \ or context.get('page', None) # Assuming current page, preserve query string filters. qs = request.META.get('QUERY_STRING', '') try: if view is not None: # Allow a view to specify what the URL should be. # This handles situations where the slug might be translated, # and gives you complete control over the results of this template tag. get_view_url = getattr(view, 'get_view_url', None) if get_view_url: with smart_override(lang_code): return _url_qs(view.get_view_url(), qs) # Now, the "best effort" part starts. # See if it's a DetailView that exposes the object. if object is None: object = getattr(view, 'object', None) if object is not None and hasattr(object, 'get_absolute_url'): # There is an object, get the URL in the different language. # NOTE: this *assumes* that there is a detail view, not some edit view. # In such case, a language menu would redirect a user from the edit page # to a detail page; which is still way better a 404 or homepage. if isinstance(object, TranslatableModel): # Need to handle object URL translations. # Just using smart_override() should be enough, as a translated object # should use `switch_language(self)` internally before returning an URL. # However, it doesn't hurt to help a bit here. with switch_language(object, lang_code): return _url_qs(object.get_absolute_url(), qs) else: # Always switch the language before resolving, so i18n_patterns() are supported. with smart_override(lang_code): return _url_qs(object.get_absolute_url(), qs) except TranslationDoesNotExist: # Typically projects have a fallback language, so even unknown languages will return something. # This either means fallbacks are disabled, or the fallback language is not found! return '' # Just reverse the current URL again in a new language, and see where we end up. # This doesn't handle translated slugs, but will resolve to the proper view name. resolver_match = request.resolver_match if resolver_match is None: # Can't resolve the page itself, the page is apparently a 404. # This can also happen for the homepage in an i18n_patterns situation. return '' with smart_override(lang_code): clean_kwargs = _cleanup_urlpattern_kwargs(resolver_match.kwargs) return _url_qs(reverse(resolver_match.view_name, args=resolver_match.args, kwargs=clean_kwargs, current_app=resolver_match.app_name), qs)
[ "def", "get_translated_url", "(", "context", ",", "lang_code", ",", "object", "=", "None", ")", ":", "view", "=", "context", ".", "get", "(", "'view'", ",", "None", ")", "request", "=", "context", "[", "'request'", "]", "if", "object", "is", "not", "No...
Get the proper URL for this page in a different language. Note that this algorithm performs a "best effect" approach to give a proper URL. To make sure the proper view URL is returned, add the :class:`~parler.views.ViewUrlMixin` to your view. Example, to build a language menu:: <ul> {% for lang_code, title in LANGUAGES %} {% get_language_info for lang_code as lang %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<li{% if lang_code == LANGUAGE_CODE %} class="is-selected"{% endif %}><a href="{{ tr_url }}" hreflang="{{ lang_code }}">{{ lang.name_local|capfirst }}</a></li>{% endif %} {% endfor %} </ul> Or to inform search engines about the translated pages:: {% for lang_code, title in LANGUAGES %} {% get_translated_url lang_code as tr_url %} {% if tr_url %}<link rel="alternate" hreflang="{{ lang_code }}" href="{{ tr_url }}" />{% endif %} {% endfor %} Note that using this tag is not thread-safe if the object is shared between threads. It temporary changes the current language of the view object. The query string of the current page is preserved in the translated URL. When the ``object`` variable is explicitly provided however, the query string will not be added. In such situation, *django-parler* assumes that the object may point to a completely different page, hence to query string is added.
[ "Get", "the", "proper", "URL", "for", "this", "page", "in", "a", "different", "language", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/templatetags/parler_tags.py#L67-L164
train
211,664
django-parler/django-parler
parler/cache.py
get_translation_cache_key
def get_translation_cache_key(translated_model, master_id, language_code): """ The low-level function to get the cache key for a translation. """ # Always cache the entire object, as this already produces # a lot of queries. Don't go for caching individual fields. return 'parler.{0}.{1}.{2}.{3}'.format(translated_model._meta.app_label, translated_model.__name__, master_id, language_code)
python
def get_translation_cache_key(translated_model, master_id, language_code): """ The low-level function to get the cache key for a translation. """ # Always cache the entire object, as this already produces # a lot of queries. Don't go for caching individual fields. return 'parler.{0}.{1}.{2}.{3}'.format(translated_model._meta.app_label, translated_model.__name__, master_id, language_code)
[ "def", "get_translation_cache_key", "(", "translated_model", ",", "master_id", ",", "language_code", ")", ":", "# Always cache the entire object, as this already produces", "# a lot of queries. Don't go for caching individual fields.", "return", "'parler.{0}.{1}.{2}.{3}'", ".", "format...
The low-level function to get the cache key for a translation.
[ "The", "low", "-", "level", "function", "to", "get", "the", "cache", "key", "for", "a", "translation", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/cache.py#L58-L64
train
211,665
django-parler/django-parler
parler/cache.py
get_cached_translation
def get_cached_translation(instance, language_code=None, related_name=None, use_fallback=False): """ Fetch an cached translation. .. versionadded 1.2 Added the ``related_name`` parameter. """ if language_code is None: language_code = instance.get_current_language() translated_model = instance._parler_meta.get_model_by_related_name(related_name) values = _get_cached_values(instance, translated_model, language_code, use_fallback) if not values: return None try: translation = translated_model(**values) except TypeError: # Some model field was removed, cache entry is no longer working. return None translation._state.adding = False return translation
python
def get_cached_translation(instance, language_code=None, related_name=None, use_fallback=False): """ Fetch an cached translation. .. versionadded 1.2 Added the ``related_name`` parameter. """ if language_code is None: language_code = instance.get_current_language() translated_model = instance._parler_meta.get_model_by_related_name(related_name) values = _get_cached_values(instance, translated_model, language_code, use_fallback) if not values: return None try: translation = translated_model(**values) except TypeError: # Some model field was removed, cache entry is no longer working. return None translation._state.adding = False return translation
[ "def", "get_cached_translation", "(", "instance", ",", "language_code", "=", "None", ",", "related_name", "=", "None", ",", "use_fallback", "=", "False", ")", ":", "if", "language_code", "is", "None", ":", "language_code", "=", "instance", ".", "get_current_lang...
Fetch an cached translation. .. versionadded 1.2 Added the ``related_name`` parameter.
[ "Fetch", "an", "cached", "translation", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/cache.py#L67-L88
train
211,666
django-parler/django-parler
parler/cache.py
_cache_translation
def _cache_translation(translation, timeout=cache.default_timeout): """ Store a new translation in the cache. """ if not appsettings.PARLER_ENABLE_CACHING: return if translation.master_id is None: raise ValueError("Can't cache unsaved translation") # Cache a translation object. # For internal usage, object parameters are not suited for outside usage. fields = translation.get_translated_fields() values = {'id': translation.id} for name in fields: values[name] = getattr(translation, name) key = get_translation_cache_key(translation.__class__, translation.master_id, translation.language_code) cache.set(key, values, timeout=timeout)
python
def _cache_translation(translation, timeout=cache.default_timeout): """ Store a new translation in the cache. """ if not appsettings.PARLER_ENABLE_CACHING: return if translation.master_id is None: raise ValueError("Can't cache unsaved translation") # Cache a translation object. # For internal usage, object parameters are not suited for outside usage. fields = translation.get_translated_fields() values = {'id': translation.id} for name in fields: values[name] = getattr(translation, name) key = get_translation_cache_key(translation.__class__, translation.master_id, translation.language_code) cache.set(key, values, timeout=timeout)
[ "def", "_cache_translation", "(", "translation", ",", "timeout", "=", "cache", ".", "default_timeout", ")", ":", "if", "not", "appsettings", ".", "PARLER_ENABLE_CACHING", ":", "return", "if", "translation", ".", "master_id", "is", "None", ":", "raise", "ValueErr...
Store a new translation in the cache.
[ "Store", "a", "new", "translation", "in", "the", "cache", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/cache.py#L147-L165
train
211,667
django-parler/django-parler
parler/cache.py
_cache_translation_needs_fallback
def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=cache.default_timeout): """ Store the fact that a translation doesn't exist, and the fallback should be used. """ if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding: return tr_model = instance._parler_meta.get_model_by_related_name(related_name) key = get_translation_cache_key(tr_model, instance.pk, language_code) cache.set(key, {'__FALLBACK__': True}, timeout=timeout)
python
def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=cache.default_timeout): """ Store the fact that a translation doesn't exist, and the fallback should be used. """ if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding: return tr_model = instance._parler_meta.get_model_by_related_name(related_name) key = get_translation_cache_key(tr_model, instance.pk, language_code) cache.set(key, {'__FALLBACK__': True}, timeout=timeout)
[ "def", "_cache_translation_needs_fallback", "(", "instance", ",", "language_code", ",", "related_name", ",", "timeout", "=", "cache", ".", "default_timeout", ")", ":", "if", "not", "appsettings", ".", "PARLER_ENABLE_CACHING", "or", "not", "instance", ".", "pk", "o...
Store the fact that a translation doesn't exist, and the fallback should be used.
[ "Store", "the", "fact", "that", "a", "translation", "doesn", "t", "exist", "and", "the", "fallback", "should", "be", "used", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/cache.py#L168-L177
train
211,668
django-parler/django-parler
parler/utils/template.py
select_template_name
def select_template_name(template_name_list, using=None): """ Given a list of template names, find the first one that exists. """ if not isinstance(template_name_list, tuple): template_name_list = tuple(template_name_list) try: return _cached_name_lookups[template_name_list] except KeyError: # Find which template of the template_names is selected by the Django loader. for template_name in template_name_list: try: get_template(template_name, using=using) except TemplateDoesNotExist: continue else: template_name = six.text_type(template_name) # consistent value for lazy() function. _cached_name_lookups[template_name_list] = template_name return template_name return None
python
def select_template_name(template_name_list, using=None): """ Given a list of template names, find the first one that exists. """ if not isinstance(template_name_list, tuple): template_name_list = tuple(template_name_list) try: return _cached_name_lookups[template_name_list] except KeyError: # Find which template of the template_names is selected by the Django loader. for template_name in template_name_list: try: get_template(template_name, using=using) except TemplateDoesNotExist: continue else: template_name = six.text_type(template_name) # consistent value for lazy() function. _cached_name_lookups[template_name_list] = template_name return template_name return None
[ "def", "select_template_name", "(", "template_name_list", ",", "using", "=", "None", ")", ":", "if", "not", "isinstance", "(", "template_name_list", ",", "tuple", ")", ":", "template_name_list", "=", "tuple", "(", "template_name_list", ")", "try", ":", "return",...
Given a list of template names, find the first one that exists.
[ "Given", "a", "list", "of", "template", "names", "find", "the", "first", "one", "that", "exists", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/utils/template.py#L8-L29
train
211,669
django-parler/django-parler
parler/views.py
ViewUrlMixin.get_view_url
def get_view_url(self): """ This method is used by the ``get_translated_url`` template tag. By default, it uses the :attr:`view_url_name` to generate an URL. When the URL ``args`` and ``kwargs`` are translatable, override this function instead to generate the proper URL. """ if not self.view_url_name: # Sadly, class based views can't work with reverse(func_pointer) as that's unknown. # Neither is it possible to use resolve(self.request.path).view_name in this function as auto-detection. # This function can be called in the context of a different language. # When i18n_patterns() is applied, that resolve() will fail. # # Hence, you need to provide a "view_url_name" as static configuration option. raise ImproperlyConfigured("Missing `view_url_name` attribute on {0}".format(self.__class__.__name__)) return reverse(self.view_url_name, args=self.args, kwargs=self.kwargs)
python
def get_view_url(self): """ This method is used by the ``get_translated_url`` template tag. By default, it uses the :attr:`view_url_name` to generate an URL. When the URL ``args`` and ``kwargs`` are translatable, override this function instead to generate the proper URL. """ if not self.view_url_name: # Sadly, class based views can't work with reverse(func_pointer) as that's unknown. # Neither is it possible to use resolve(self.request.path).view_name in this function as auto-detection. # This function can be called in the context of a different language. # When i18n_patterns() is applied, that resolve() will fail. # # Hence, you need to provide a "view_url_name" as static configuration option. raise ImproperlyConfigured("Missing `view_url_name` attribute on {0}".format(self.__class__.__name__)) return reverse(self.view_url_name, args=self.args, kwargs=self.kwargs)
[ "def", "get_view_url", "(", "self", ")", ":", "if", "not", "self", ".", "view_url_name", ":", "# Sadly, class based views can't work with reverse(func_pointer) as that's unknown.", "# Neither is it possible to use resolve(self.request.path).view_name in this function as auto-detection.", ...
This method is used by the ``get_translated_url`` template tag. By default, it uses the :attr:`view_url_name` to generate an URL. When the URL ``args`` and ``kwargs`` are translatable, override this function instead to generate the proper URL.
[ "This", "method", "is", "used", "by", "the", "get_translated_url", "template", "tag", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L73-L90
train
211,670
django-parler/django-parler
parler/views.py
TranslatableSlugMixin.get_object
def get_object(self, queryset=None): """ Fetch the object using a translated slug. """ if queryset is None: queryset = self.get_queryset() slug = self.kwargs[self.slug_url_kwarg] choices = self.get_language_choices() obj = None using_fallback = False prev_choices = [] for lang_choice in choices: try: # Get the single item from the filtered queryset # NOTE. Explicitly set language to the state the object was fetched in. filters = self.get_translated_filters(slug=slug) obj = queryset.translated(lang_choice, **filters).language(lang_choice).get() except ObjectDoesNotExist: # Translated object not found, next object is marked as fallback. using_fallback = True prev_choices.append(lang_choice) else: break if obj is None: tried_msg = ", tried languages: {0}".format(", ".join(choices)) error_message = translation.ugettext("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name} raise Http404(error_message + tried_msg) # Object found! if using_fallback: # It could happen that objects are resolved using their fallback language, # but the actual translation also exists. Either that means this URL should # raise a 404, or a redirect could be made as service to the users. # It's possible that the old URL was active before in the language domain/subpath # when there was no translation yet. for prev_choice in prev_choices: if obj.has_translation(prev_choice): # Only dispatch() and render_to_response() can return a valid response, # By breaking out here, this functionality can't be broken by users overriding render_to_response() raise FallbackLanguageResolved(obj, prev_choice) return obj
python
def get_object(self, queryset=None): """ Fetch the object using a translated slug. """ if queryset is None: queryset = self.get_queryset() slug = self.kwargs[self.slug_url_kwarg] choices = self.get_language_choices() obj = None using_fallback = False prev_choices = [] for lang_choice in choices: try: # Get the single item from the filtered queryset # NOTE. Explicitly set language to the state the object was fetched in. filters = self.get_translated_filters(slug=slug) obj = queryset.translated(lang_choice, **filters).language(lang_choice).get() except ObjectDoesNotExist: # Translated object not found, next object is marked as fallback. using_fallback = True prev_choices.append(lang_choice) else: break if obj is None: tried_msg = ", tried languages: {0}".format(", ".join(choices)) error_message = translation.ugettext("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name} raise Http404(error_message + tried_msg) # Object found! if using_fallback: # It could happen that objects are resolved using their fallback language, # but the actual translation also exists. Either that means this URL should # raise a 404, or a redirect could be made as service to the users. # It's possible that the old URL was active before in the language domain/subpath # when there was no translation yet. for prev_choice in prev_choices: if obj.has_translation(prev_choice): # Only dispatch() and render_to_response() can return a valid response, # By breaking out here, this functionality can't be broken by users overriding render_to_response() raise FallbackLanguageResolved(obj, prev_choice) return obj
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "if", "queryset", "is", "None", ":", "queryset", "=", "self", ".", "get_queryset", "(", ")", "slug", "=", "self", ".", "kwargs", "[", "self", ".", "slug_url_kwarg", "]", "choices...
Fetch the object using a translated slug.
[ "Fetch", "the", "object", "using", "a", "translated", "slug", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L140-L184
train
211,671
django-parler/django-parler
parler/views.py
LanguageChoiceMixin.get_object
def get_object(self, queryset=None): """ Assign the language for the retrieved object. """ object = super(LanguageChoiceMixin, self).get_object(queryset) if isinstance(object, TranslatableModelMixin): object.set_current_language(self.get_language(), initialize=True) return object
python
def get_object(self, queryset=None): """ Assign the language for the retrieved object. """ object = super(LanguageChoiceMixin, self).get_object(queryset) if isinstance(object, TranslatableModelMixin): object.set_current_language(self.get_language(), initialize=True) return object
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "object", "=", "super", "(", "LanguageChoiceMixin", ",", "self", ")", ".", "get_object", "(", "queryset", ")", "if", "isinstance", "(", "object", ",", "TranslatableModelMixin", ")", ...
Assign the language for the retrieved object.
[ "Assign", "the", "language", "for", "the", "retrieved", "object", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L205-L212
train
211,672
django-parler/django-parler
parler/views.py
TranslatableModelFormMixin.get_form_class
def get_form_class(self): """ Return a ``TranslatableModelForm`` by default if no form_class is set. """ super_method = super(TranslatableModelFormMixin, self).get_form_class # no "__func__" on the class level function in python 3 default_method = getattr(ModelFormMixin.get_form_class, '__func__', ModelFormMixin.get_form_class) if not (super_method.__func__ is default_method): # Don't get in your way, if you've overwritten stuff. return super_method() else: # Same logic as ModelFormMixin.get_form_class, but using the right form base class. if self.form_class: return self.form_class else: model = _get_view_model(self) if self.fields: fields = self.fields return modelform_factory(model, form=TranslatableModelForm, fields=fields) else: return modelform_factory(model, form=TranslatableModelForm)
python
def get_form_class(self): """ Return a ``TranslatableModelForm`` by default if no form_class is set. """ super_method = super(TranslatableModelFormMixin, self).get_form_class # no "__func__" on the class level function in python 3 default_method = getattr(ModelFormMixin.get_form_class, '__func__', ModelFormMixin.get_form_class) if not (super_method.__func__ is default_method): # Don't get in your way, if you've overwritten stuff. return super_method() else: # Same logic as ModelFormMixin.get_form_class, but using the right form base class. if self.form_class: return self.form_class else: model = _get_view_model(self) if self.fields: fields = self.fields return modelform_factory(model, form=TranslatableModelForm, fields=fields) else: return modelform_factory(model, form=TranslatableModelForm)
[ "def", "get_form_class", "(", "self", ")", ":", "super_method", "=", "super", "(", "TranslatableModelFormMixin", ",", "self", ")", ".", "get_form_class", "# no \"__func__\" on the class level function in python 3", "default_method", "=", "getattr", "(", "ModelFormMixin", ...
Return a ``TranslatableModelForm`` by default if no form_class is set.
[ "Return", "a", "TranslatableModelForm", "by", "default", "if", "no", "form_class", "is", "set", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/views.py#L269-L289
train
211,673
django-parler/django-parler
parler/utils/conf.py
get_parler_languages_from_django_cms
def get_parler_languages_from_django_cms(cms_languages=None): """ Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of cleansing to remove irrelevant items. """ valid_keys = ['code', 'fallbacks', 'hide_untranslated', 'redirect_on_fallback'] if cms_languages: if sys.version_info < (3, 0, 0): int_types = (int, long) else: int_types = int parler_languages = copy.deepcopy(cms_languages) for site_id, site_config in cms_languages.items(): if site_id and ( not isinstance(site_id, int_types) and site_id != 'default' ): del parler_languages[site_id] continue if site_id == 'default': for key, value in site_config.items(): if key not in valid_keys: del parler_languages['default'][key] else: for i, lang_config in enumerate(site_config): for key, value in lang_config.items(): if key not in valid_keys: del parler_languages[site_id][i][key] return parler_languages return None
python
def get_parler_languages_from_django_cms(cms_languages=None): """ Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of cleansing to remove irrelevant items. """ valid_keys = ['code', 'fallbacks', 'hide_untranslated', 'redirect_on_fallback'] if cms_languages: if sys.version_info < (3, 0, 0): int_types = (int, long) else: int_types = int parler_languages = copy.deepcopy(cms_languages) for site_id, site_config in cms_languages.items(): if site_id and ( not isinstance(site_id, int_types) and site_id != 'default' ): del parler_languages[site_id] continue if site_id == 'default': for key, value in site_config.items(): if key not in valid_keys: del parler_languages['default'][key] else: for i, lang_config in enumerate(site_config): for key, value in lang_config.items(): if key not in valid_keys: del parler_languages[site_id][i][key] return parler_languages return None
[ "def", "get_parler_languages_from_django_cms", "(", "cms_languages", "=", "None", ")", ":", "valid_keys", "=", "[", "'code'", ",", "'fallbacks'", ",", "'hide_untranslated'", ",", "'redirect_on_fallback'", "]", "if", "cms_languages", ":", "if", "sys", ".", "version_i...
Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of cleansing to remove irrelevant items.
[ "Converts", "django", "CMS", "setting", "CMS_LANGUAGES", "into", "PARLER_LANGUAGES", ".", "Since", "CMS_LANGUAGES", "is", "a", "strict", "superset", "of", "PARLER_LANGUAGES", "we", "do", "a", "bit", "of", "cleansing", "to", "remove", "irrelevant", "items", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/utils/conf.py#L184-L217
train
211,674
django-parler/django-parler
parler/utils/conf.py
LanguagesSetting.get_first_language
def get_first_language(self, site_id=None): """ Return the first language for the current site. This can be used for user interfaces, where the languages are displayed in tabs. """ if site_id is None: site_id = getattr(settings, 'SITE_ID', None) try: return self[site_id][0]['code'] except (KeyError, IndexError): # No configuration, always fallback to default language. # This is essentially a non-multilingual configuration. return self['default']['code']
python
def get_first_language(self, site_id=None): """ Return the first language for the current site. This can be used for user interfaces, where the languages are displayed in tabs. """ if site_id is None: site_id = getattr(settings, 'SITE_ID', None) try: return self[site_id][0]['code'] except (KeyError, IndexError): # No configuration, always fallback to default language. # This is essentially a non-multilingual configuration. return self['default']['code']
[ "def", "get_first_language", "(", "self", ",", "site_id", "=", "None", ")", ":", "if", "site_id", "is", "None", ":", "site_id", "=", "getattr", "(", "settings", ",", "'SITE_ID'", ",", "None", ")", "try", ":", "return", "self", "[", "site_id", "]", "[",...
Return the first language for the current site. This can be used for user interfaces, where the languages are displayed in tabs.
[ "Return", "the", "first", "language", "for", "the", "current", "site", ".", "This", "can", "be", "used", "for", "user", "interfaces", "where", "the", "languages", "are", "displayed", "in", "tabs", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/utils/conf.py#L168-L181
train
211,675
django-parler/django-parler
parler/forms.py
_get_model_form_field
def _get_model_form_field(model, name, formfield_callback=None, **kwargs): """ Utility to create the formfield from a model field. When a field is not editable, a ``None`` will be returned. """ field = model._meta.get_field(name) if not field.editable: # see fields_for_model() logic in Django. return None # Apply admin formfield_overrides if formfield_callback is None: formfield = field.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError('formfield_callback must be a function or callable') else: formfield = formfield_callback(field, **kwargs) return formfield
python
def _get_model_form_field(model, name, formfield_callback=None, **kwargs): """ Utility to create the formfield from a model field. When a field is not editable, a ``None`` will be returned. """ field = model._meta.get_field(name) if not field.editable: # see fields_for_model() logic in Django. return None # Apply admin formfield_overrides if formfield_callback is None: formfield = field.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError('formfield_callback must be a function or callable') else: formfield = formfield_callback(field, **kwargs) return formfield
[ "def", "_get_model_form_field", "(", "model", ",", "name", ",", "formfield_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "name", ")", "if", "not", "field", ".", "editable", ":", "...
Utility to create the formfield from a model field. When a field is not editable, a ``None`` will be returned.
[ "Utility", "to", "create", "the", "formfield", "from", "a", "model", "field", ".", "When", "a", "field", "is", "not", "editable", "a", "None", "will", "be", "returned", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/forms.py#L307-L324
train
211,676
django-parler/django-parler
parler/forms.py
BaseTranslatableModelForm.save_translated_fields
def save_translated_fields(self): """ Save all translated fields. """ fields = {} # Collect all translated fields {'name': 'value'} for field in self._translated_fields: try: value = self.cleaned_data[field] except KeyError: # Field has a ValidationError continue fields[field] = value # Set the field values on their relevant models translations = self.instance._set_translated_fields(**fields) # Perform full clean on models non_translated_fields = set(('id', 'master_id', 'language_code')) for translation in translations: self._post_clean_translation(translation) # Assign translated fields to the model (using the TranslatedAttribute descriptor) for field in translation._get_field_names(): if field in non_translated_fields: continue setattr(self.instance, field, getattr(translation, field))
python
def save_translated_fields(self): """ Save all translated fields. """ fields = {} # Collect all translated fields {'name': 'value'} for field in self._translated_fields: try: value = self.cleaned_data[field] except KeyError: # Field has a ValidationError continue fields[field] = value # Set the field values on their relevant models translations = self.instance._set_translated_fields(**fields) # Perform full clean on models non_translated_fields = set(('id', 'master_id', 'language_code')) for translation in translations: self._post_clean_translation(translation) # Assign translated fields to the model (using the TranslatedAttribute descriptor) for field in translation._get_field_names(): if field in non_translated_fields: continue setattr(self.instance, field, getattr(translation, field))
[ "def", "save_translated_fields", "(", "self", ")", ":", "fields", "=", "{", "}", "# Collect all translated fields {'name': 'value'}", "for", "field", "in", "self", ".", "_translated_fields", ":", "try", ":", "value", "=", "self", ".", "cleaned_data", "[", "field",...
Save all translated fields.
[ "Save", "all", "translated", "fields", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/forms.py#L130-L156
train
211,677
django-parler/django-parler
parler/models.py
create_translations_model
def create_translations_model(shared_model, related_name, meta, **fields): """ Dynamically create the translations model. Create the translations model for the shared model 'model'. :param related_name: The related name for the reverse FK from the translations model. :param meta: A (optional) dictionary of attributes for the translations model's inner Meta class. :param fields: A dictionary of fields to put on the translations model. Two fields are enforced on the translations model: language_code: A 15 char, db indexed field. master: A ForeignKey back to the shared model. Those two fields are unique together. """ if not meta: meta = {} if shared_model._meta.abstract: # This can't be done, because `master = ForeignKey(shared_model)` would fail. raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) # Define inner Meta class meta['app_label'] = shared_model._meta.app_label meta['db_tablespace'] = shared_model._meta.db_tablespace meta['managed'] = shared_model._meta.managed meta['unique_together'] = list(meta.get('unique_together', [])) + [('language_code', 'master')] meta.setdefault('db_table', '{0}_translation'.format(shared_model._meta.db_table)) meta.setdefault('verbose_name', _lazy_verbose_name(shared_model)) # Avoid creating permissions for the translated model, these are not used at all. # This also avoids creating lengthy permission names above 50 chars. meta.setdefault('default_permissions', ()) # Define attributes for translation table name = str('{0}Translation'.format(shared_model.__name__)) # makes it bytes, for type() attrs = {} attrs.update(fields) attrs['Meta'] = type(str('Meta'), (object,), meta) attrs['__module__'] = shared_model.__module__ attrs['objects'] = models.Manager() attrs['master'] = TranslationsForeignKey(shared_model, related_name=related_name, editable=False, null=True, on_delete=models.CASCADE) # Create and return the new model translations_model = TranslatedFieldsModelBase(name, (TranslatedFieldsModel,), attrs) # Register it as a global in the shared model's module. # This is needed so that Translation model instances, and objects which refer to them, can be properly pickled and unpickled. # The Django session and caching frameworks, in particular, depend on this behaviour. mod = sys.modules[shared_model.__module__] setattr(mod, name, translations_model) return translations_model
python
def create_translations_model(shared_model, related_name, meta, **fields): """ Dynamically create the translations model. Create the translations model for the shared model 'model'. :param related_name: The related name for the reverse FK from the translations model. :param meta: A (optional) dictionary of attributes for the translations model's inner Meta class. :param fields: A dictionary of fields to put on the translations model. Two fields are enforced on the translations model: language_code: A 15 char, db indexed field. master: A ForeignKey back to the shared model. Those two fields are unique together. """ if not meta: meta = {} if shared_model._meta.abstract: # This can't be done, because `master = ForeignKey(shared_model)` would fail. raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) # Define inner Meta class meta['app_label'] = shared_model._meta.app_label meta['db_tablespace'] = shared_model._meta.db_tablespace meta['managed'] = shared_model._meta.managed meta['unique_together'] = list(meta.get('unique_together', [])) + [('language_code', 'master')] meta.setdefault('db_table', '{0}_translation'.format(shared_model._meta.db_table)) meta.setdefault('verbose_name', _lazy_verbose_name(shared_model)) # Avoid creating permissions for the translated model, these are not used at all. # This also avoids creating lengthy permission names above 50 chars. meta.setdefault('default_permissions', ()) # Define attributes for translation table name = str('{0}Translation'.format(shared_model.__name__)) # makes it bytes, for type() attrs = {} attrs.update(fields) attrs['Meta'] = type(str('Meta'), (object,), meta) attrs['__module__'] = shared_model.__module__ attrs['objects'] = models.Manager() attrs['master'] = TranslationsForeignKey(shared_model, related_name=related_name, editable=False, null=True, on_delete=models.CASCADE) # Create and return the new model translations_model = TranslatedFieldsModelBase(name, (TranslatedFieldsModel,), attrs) # Register it as a global in the shared model's module. # This is needed so that Translation model instances, and objects which refer to them, can be properly pickled and unpickled. # The Django session and caching frameworks, in particular, depend on this behaviour. mod = sys.modules[shared_model.__module__] setattr(mod, name, translations_model) return translations_model
[ "def", "create_translations_model", "(", "shared_model", ",", "related_name", ",", "meta", ",", "*", "*", "fields", ")", ":", "if", "not", "meta", ":", "meta", "=", "{", "}", "if", "shared_model", ".", "_meta", ".", "abstract", ":", "# This can't be done, be...
Dynamically create the translations model. Create the translations model for the shared model 'model'. :param related_name: The related name for the reverse FK from the translations model. :param meta: A (optional) dictionary of attributes for the translations model's inner Meta class. :param fields: A dictionary of fields to put on the translations model. Two fields are enforced on the translations model: language_code: A 15 char, db indexed field. master: A ForeignKey back to the shared model. Those two fields are unique together.
[ "Dynamically", "create", "the", "translations", "model", ".", "Create", "the", "translations", "model", "for", "the", "shared", "model", "model", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L113-L168
train
211,678
django-parler/django-parler
parler/models.py
TranslatableModelMixin._set_translated_fields
def _set_translated_fields(self, language_code=None, **fields): """ Assign fields to the translated models. """ objects = [] # no generator, make sure objects are all filled first for parler_meta, model_fields in self._parler_meta._split_fields(**fields): translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta) for field, value in six.iteritems(model_fields): setattr(translation, field, value) objects.append(translation) return objects
python
def _set_translated_fields(self, language_code=None, **fields): """ Assign fields to the translated models. """ objects = [] # no generator, make sure objects are all filled first for parler_meta, model_fields in self._parler_meta._split_fields(**fields): translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta) for field, value in six.iteritems(model_fields): setattr(translation, field, value) objects.append(translation) return objects
[ "def", "_set_translated_fields", "(", "self", ",", "language_code", "=", "None", ",", "*", "*", "fields", ")", ":", "objects", "=", "[", "]", "# no generator, make sure objects are all filled first", "for", "parler_meta", ",", "model_fields", "in", "self", ".", "_...
Assign fields to the translated models.
[ "Assign", "fields", "to", "the", "translated", "models", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L266-L277
train
211,679
django-parler/django-parler
parler/models.py
TranslatableModelMixin.create_translation
def create_translation(self, language_code, **fields): """ Add a translation to the model. The :func:`save_translations` function is called afterwards. The object will be saved immediately, similar to calling :func:`~django.db.models.manager.Manager.create` or :func:`~django.db.models.fields.related.RelatedManager.create` on related fields. """ if language_code is None: raise ValueError(get_null_language_error()) meta = self._parler_meta if self._translations_cache[meta.root_model].get(language_code, None): # MISSING evaluates to False too raise ValueError("Translation already exists: {0}".format(language_code)) # Save all fields in the proper translated model. for translation in self._set_translated_fields(language_code, **fields): self.save_translation(translation)
python
def create_translation(self, language_code, **fields): """ Add a translation to the model. The :func:`save_translations` function is called afterwards. The object will be saved immediately, similar to calling :func:`~django.db.models.manager.Manager.create` or :func:`~django.db.models.fields.related.RelatedManager.create` on related fields. """ if language_code is None: raise ValueError(get_null_language_error()) meta = self._parler_meta if self._translations_cache[meta.root_model].get(language_code, None): # MISSING evaluates to False too raise ValueError("Translation already exists: {0}".format(language_code)) # Save all fields in the proper translated model. for translation in self._set_translated_fields(language_code, **fields): self.save_translation(translation)
[ "def", "create_translation", "(", "self", ",", "language_code", ",", "*", "*", "fields", ")", ":", "if", "language_code", "is", "None", ":", "raise", "ValueError", "(", "get_null_language_error", "(", ")", ")", "meta", "=", "self", ".", "_parler_meta", "if",...
Add a translation to the model. The :func:`save_translations` function is called afterwards. The object will be saved immediately, similar to calling :func:`~django.db.models.manager.Manager.create` or :func:`~django.db.models.fields.related.RelatedManager.create` on related fields.
[ "Add", "a", "translation", "to", "the", "model", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L279-L298
train
211,680
django-parler/django-parler
parler/models.py
TranslatableModelMixin.delete_translation
def delete_translation(self, language_code, related_name=None): """ Delete a translation from a model. :param language_code: The language to remove. :param related_name: If given, only the model matching that related_name is removed. """ if language_code is None: raise ValueError(get_null_language_error()) if related_name is None: metas = self._parler_meta else: metas = [self._parler_meta[related_name]] num_deleted = 0 for meta in metas: try: translation = self._get_translated_model(language_code, meta=meta) except meta.model.DoesNotExist: continue # By using the regular model delete, the cache is properly cleared # (via _delete_cached_translation) and signals are emitted. translation.delete() num_deleted += 1 # Clear other local caches try: del self._translations_cache[meta.model][language_code] except KeyError: pass try: del self._prefetched_objects_cache[meta.rel_name] except (AttributeError, KeyError): pass if not num_deleted: raise ValueError("Translation does not exist: {0}".format(language_code)) return num_deleted
python
def delete_translation(self, language_code, related_name=None): """ Delete a translation from a model. :param language_code: The language to remove. :param related_name: If given, only the model matching that related_name is removed. """ if language_code is None: raise ValueError(get_null_language_error()) if related_name is None: metas = self._parler_meta else: metas = [self._parler_meta[related_name]] num_deleted = 0 for meta in metas: try: translation = self._get_translated_model(language_code, meta=meta) except meta.model.DoesNotExist: continue # By using the regular model delete, the cache is properly cleared # (via _delete_cached_translation) and signals are emitted. translation.delete() num_deleted += 1 # Clear other local caches try: del self._translations_cache[meta.model][language_code] except KeyError: pass try: del self._prefetched_objects_cache[meta.rel_name] except (AttributeError, KeyError): pass if not num_deleted: raise ValueError("Translation does not exist: {0}".format(language_code)) return num_deleted
[ "def", "delete_translation", "(", "self", ",", "language_code", ",", "related_name", "=", "None", ")", ":", "if", "language_code", "is", "None", ":", "raise", "ValueError", "(", "get_null_language_error", "(", ")", ")", "if", "related_name", "is", "None", ":",...
Delete a translation from a model. :param language_code: The language to remove. :param related_name: If given, only the model matching that related_name is removed.
[ "Delete", "a", "translation", "from", "a", "model", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L300-L340
train
211,681
django-parler/django-parler
parler/models.py
TranslatableModelMixin.set_current_language
def set_current_language(self, language_code, initialize=False): """ Switch the currently activate language of the object. """ self._current_language = normalize_language_code(language_code or get_language()) # Ensure the translation is present for __get__ queries. if initialize: self._get_translated_model(use_fallback=False, auto_create=True)
python
def set_current_language(self, language_code, initialize=False): """ Switch the currently activate language of the object. """ self._current_language = normalize_language_code(language_code or get_language()) # Ensure the translation is present for __get__ queries. if initialize: self._get_translated_model(use_fallback=False, auto_create=True)
[ "def", "set_current_language", "(", "self", ",", "language_code", ",", "initialize", "=", "False", ")", ":", "self", ".", "_current_language", "=", "normalize_language_code", "(", "language_code", "or", "get_language", "(", ")", ")", "# Ensure the translation is prese...
Switch the currently activate language of the object.
[ "Switch", "the", "currently", "activate", "language", "of", "the", "object", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L349-L357
train
211,682
django-parler/django-parler
parler/models.py
TranslatableModelMixin.get_fallback_languages
def get_fallback_languages(self): """ Return the fallback language codes, which are used in case there is no translation for the currently active language. """ lang_dict = get_language_settings(self._current_language) fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language] return fallbacks or []
python
def get_fallback_languages(self): """ Return the fallback language codes, which are used in case there is no translation for the currently active language. """ lang_dict = get_language_settings(self._current_language) fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language] return fallbacks or []
[ "def", "get_fallback_languages", "(", "self", ")", ":", "lang_dict", "=", "get_language_settings", "(", "self", ".", "_current_language", ")", "fallbacks", "=", "[", "lang", "for", "lang", "in", "lang_dict", "[", "'fallbacks'", "]", "if", "lang", "!=", "self",...
Return the fallback language codes, which are used in case there is no translation for the currently active language.
[ "Return", "the", "fallback", "language", "codes", "which", "are", "used", "in", "case", "there", "is", "no", "translation", "for", "the", "currently", "active", "language", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L367-L374
train
211,683
django-parler/django-parler
parler/models.py
TranslatableModelMixin.has_translation
def has_translation(self, language_code=None, related_name=None): """ Return whether a translation for the given language exists. Defaults to the current language code. .. versionadded 1.2 Added the ``related_name`` parameter. """ if language_code is None: language_code = self._current_language if language_code is None: raise ValueError(get_null_language_error()) meta = self._parler_meta._get_extension_by_related_name(related_name) try: # Check the local cache directly, and the answer is known. # NOTE this may also return newly auto created translations which are not saved yet. return not is_missing(self._translations_cache[meta.model][language_code]) except KeyError: # If there is a prefetch, will be using that. # However, don't assume the prefetch contains all possible languages. # With Django 1.8, there are custom Prefetch objects. # TODO: improve this, detect whether this is the case. if language_code in self._read_prefetched_translations(meta=meta): return True # Try to fetch from the cache first. # If the cache returns the fallback, it means the original does not exist. object = get_cached_translation(self, language_code, related_name=related_name, use_fallback=True) if object is not None: return object.language_code == language_code try: # Fetch from DB, fill the cache. self._get_translated_model(language_code, use_fallback=False, auto_create=False, meta=meta) except meta.model.DoesNotExist: return False else: return True
python
def has_translation(self, language_code=None, related_name=None): """ Return whether a translation for the given language exists. Defaults to the current language code. .. versionadded 1.2 Added the ``related_name`` parameter. """ if language_code is None: language_code = self._current_language if language_code is None: raise ValueError(get_null_language_error()) meta = self._parler_meta._get_extension_by_related_name(related_name) try: # Check the local cache directly, and the answer is known. # NOTE this may also return newly auto created translations which are not saved yet. return not is_missing(self._translations_cache[meta.model][language_code]) except KeyError: # If there is a prefetch, will be using that. # However, don't assume the prefetch contains all possible languages. # With Django 1.8, there are custom Prefetch objects. # TODO: improve this, detect whether this is the case. if language_code in self._read_prefetched_translations(meta=meta): return True # Try to fetch from the cache first. # If the cache returns the fallback, it means the original does not exist. object = get_cached_translation(self, language_code, related_name=related_name, use_fallback=True) if object is not None: return object.language_code == language_code try: # Fetch from DB, fill the cache. self._get_translated_model(language_code, use_fallback=False, auto_create=False, meta=meta) except meta.model.DoesNotExist: return False else: return True
[ "def", "has_translation", "(", "self", ",", "language_code", "=", "None", ",", "related_name", "=", "None", ")", ":", "if", "language_code", "is", "None", ":", "language_code", "=", "self", ".", "_current_language", "if", "language_code", "is", "None", ":", ...
Return whether a translation for the given language exists. Defaults to the current language code. .. versionadded 1.2 Added the ``related_name`` parameter.
[ "Return", "whether", "a", "translation", "for", "the", "given", "language", "exists", ".", "Defaults", "to", "the", "current", "language", "code", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L376-L414
train
211,684
django-parler/django-parler
parler/models.py
TranslatableModelMixin.get_available_languages
def get_available_languages(self, related_name=None, include_unsaved=False): """ Return the language codes of all translated variations. .. versionadded 1.2 Added the ``include_unsaved`` and ``related_name`` parameters. """ meta = self._parler_meta._get_extension_by_related_name(related_name) prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: # TODO: this will break when using custom Django 1.8 Prefetch objects? db_languages = sorted(obj.language_code for obj in prefetch) else: qs = self._get_translated_queryset(meta=meta) db_languages = qs.values_list('language_code', flat=True).order_by('language_code') if include_unsaved: local_languages = (k for k, v in six.iteritems(self._translations_cache[meta.model]) if not is_missing(v)) return list(set(db_languages) | set(local_languages)) else: return db_languages
python
def get_available_languages(self, related_name=None, include_unsaved=False): """ Return the language codes of all translated variations. .. versionadded 1.2 Added the ``include_unsaved`` and ``related_name`` parameters. """ meta = self._parler_meta._get_extension_by_related_name(related_name) prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: # TODO: this will break when using custom Django 1.8 Prefetch objects? db_languages = sorted(obj.language_code for obj in prefetch) else: qs = self._get_translated_queryset(meta=meta) db_languages = qs.values_list('language_code', flat=True).order_by('language_code') if include_unsaved: local_languages = (k for k, v in six.iteritems(self._translations_cache[meta.model]) if not is_missing(v)) return list(set(db_languages) | set(local_languages)) else: return db_languages
[ "def", "get_available_languages", "(", "self", ",", "related_name", "=", "None", ",", "include_unsaved", "=", "False", ")", ":", "meta", "=", "self", ".", "_parler_meta", ".", "_get_extension_by_related_name", "(", "related_name", ")", "prefetch", "=", "self", "...
Return the language codes of all translated variations. .. versionadded 1.2 Added the ``include_unsaved`` and ``related_name`` parameters.
[ "Return", "the", "language", "codes", "of", "all", "translated", "variations", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L416-L436
train
211,685
django-parler/django-parler
parler/models.py
TranslatableModelMixin.get_translation
def get_translation(self, language_code, related_name=None): """ Fetch the translated model """ meta = self._parler_meta._get_extension_by_related_name(related_name) return self._get_translated_model(language_code, meta=meta)
python
def get_translation(self, language_code, related_name=None): """ Fetch the translated model """ meta = self._parler_meta._get_extension_by_related_name(related_name) return self._get_translated_model(language_code, meta=meta)
[ "def", "get_translation", "(", "self", ",", "language_code", ",", "related_name", "=", "None", ")", ":", "meta", "=", "self", ".", "_parler_meta", ".", "_get_extension_by_related_name", "(", "related_name", ")", "return", "self", ".", "_get_translated_model", "(",...
Fetch the translated model
[ "Fetch", "the", "translated", "model" ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L438-L443
train
211,686
django-parler/django-parler
parler/models.py
TranslatableModelMixin._get_translated_model
def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None): """ Fetch the translated fields model. """ if self._parler_meta is None: raise ImproperlyConfigured("No translation is assigned to the current model!") if self._translations_cache is None: raise RuntimeError("Accessing translated fields before super.__init__() is not possible.") if not language_code: language_code = self._current_language if language_code is None: raise ValueError(get_null_language_error()) if meta is None: meta = self._parler_meta.root # work on base model by default local_cache = self._translations_cache[meta.model] # 1. fetch the object from the local cache try: object = local_cache[language_code] # If cached object indicates the language doesn't exist, need to query the fallback. if not is_missing(object): return object except KeyError: # 2. No cache, need to query # Check that this object already exists, would be pointless otherwise to check for a translation. if not self._state.adding and self.pk is not None: prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: # 2.1, use prefetched data # If the object is not found in the prefetched data (which contains all translations), # it's pointless to check for memcached (2.2) or perform a single query (2.3) for object in prefetch: if object.language_code == language_code: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object else: # 2.2, fetch from memcached object = get_cached_translation(self, language_code, related_name=meta.rel_name, use_fallback=use_fallback) if object is not None: # Track in local cache if object.language_code != language_code: local_cache[language_code] = MISSING # Set fallback marker local_cache[object.language_code] = object return object elif is_missing(local_cache.get(language_code, None)): # If get_cached_translation() explicitly set the "does not exist" marker, # there is no need to try a database query. pass else: # 2.3, fetch from database try: object = self._get_translated_queryset(meta).get(language_code=language_code) except meta.model.DoesNotExist: pass else: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object # Not in cache, or default. # Not fetched from DB # 3. Auto create? if auto_create: # Auto create policy first (e.g. a __set__ call) kwargs = { 'language_code': language_code, } if self.pk: # ID might be None at this point, and Django does not allow that. kwargs['master'] = self object = meta.model(**kwargs) local_cache[language_code] = object # Not stored in memcached here yet, first fill + save it. return object # 4. Fallback? fallback_msg = None lang_dict = get_language_settings(language_code) if language_code not in local_cache: # Explicitly set a marker for the fact that this translation uses the fallback instead. # Avoid making that query again. local_cache[language_code] = MISSING # None value is the marker. if not self._state.adding or self.pk is not None: _cache_translation_needs_fallback(self, language_code, related_name=meta.rel_name) fallback_choices = [lang_dict['code']] + list(lang_dict['fallbacks']) if use_fallback and fallback_choices: # Jump to fallback language, return directly. # Don't cache under this language_code for fallback_lang in fallback_choices: if fallback_lang == language_code: # Skip the current language, could also be fallback 1 of 2 choices continue try: return self._get_translated_model(fallback_lang, use_fallback=False, auto_create=auto_create, meta=meta) except meta.model.DoesNotExist: pass fallback_msg = " (tried fallbacks {0})".format(', '.join(lang_dict['fallbacks'])) # None of the above, bail out! raise meta.model.DoesNotExist( "{0} does not have a translation for the current language!\n" "{0} ID #{1}, language={2}{3}".format(self._meta.verbose_name, self.pk, language_code, fallback_msg or '' ))
python
def _get_translated_model(self, language_code=None, use_fallback=False, auto_create=False, meta=None): """ Fetch the translated fields model. """ if self._parler_meta is None: raise ImproperlyConfigured("No translation is assigned to the current model!") if self._translations_cache is None: raise RuntimeError("Accessing translated fields before super.__init__() is not possible.") if not language_code: language_code = self._current_language if language_code is None: raise ValueError(get_null_language_error()) if meta is None: meta = self._parler_meta.root # work on base model by default local_cache = self._translations_cache[meta.model] # 1. fetch the object from the local cache try: object = local_cache[language_code] # If cached object indicates the language doesn't exist, need to query the fallback. if not is_missing(object): return object except KeyError: # 2. No cache, need to query # Check that this object already exists, would be pointless otherwise to check for a translation. if not self._state.adding and self.pk is not None: prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: # 2.1, use prefetched data # If the object is not found in the prefetched data (which contains all translations), # it's pointless to check for memcached (2.2) or perform a single query (2.3) for object in prefetch: if object.language_code == language_code: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object else: # 2.2, fetch from memcached object = get_cached_translation(self, language_code, related_name=meta.rel_name, use_fallback=use_fallback) if object is not None: # Track in local cache if object.language_code != language_code: local_cache[language_code] = MISSING # Set fallback marker local_cache[object.language_code] = object return object elif is_missing(local_cache.get(language_code, None)): # If get_cached_translation() explicitly set the "does not exist" marker, # there is no need to try a database query. pass else: # 2.3, fetch from database try: object = self._get_translated_queryset(meta).get(language_code=language_code) except meta.model.DoesNotExist: pass else: local_cache[language_code] = object _cache_translation(object) # Store in memcached return object # Not in cache, or default. # Not fetched from DB # 3. Auto create? if auto_create: # Auto create policy first (e.g. a __set__ call) kwargs = { 'language_code': language_code, } if self.pk: # ID might be None at this point, and Django does not allow that. kwargs['master'] = self object = meta.model(**kwargs) local_cache[language_code] = object # Not stored in memcached here yet, first fill + save it. return object # 4. Fallback? fallback_msg = None lang_dict = get_language_settings(language_code) if language_code not in local_cache: # Explicitly set a marker for the fact that this translation uses the fallback instead. # Avoid making that query again. local_cache[language_code] = MISSING # None value is the marker. if not self._state.adding or self.pk is not None: _cache_translation_needs_fallback(self, language_code, related_name=meta.rel_name) fallback_choices = [lang_dict['code']] + list(lang_dict['fallbacks']) if use_fallback and fallback_choices: # Jump to fallback language, return directly. # Don't cache under this language_code for fallback_lang in fallback_choices: if fallback_lang == language_code: # Skip the current language, could also be fallback 1 of 2 choices continue try: return self._get_translated_model(fallback_lang, use_fallback=False, auto_create=auto_create, meta=meta) except meta.model.DoesNotExist: pass fallback_msg = " (tried fallbacks {0})".format(', '.join(lang_dict['fallbacks'])) # None of the above, bail out! raise meta.model.DoesNotExist( "{0} does not have a translation for the current language!\n" "{0} ID #{1}, language={2}{3}".format(self._meta.verbose_name, self.pk, language_code, fallback_msg or '' ))
[ "def", "_get_translated_model", "(", "self", ",", "language_code", "=", "None", ",", "use_fallback", "=", "False", ",", "auto_create", "=", "False", ",", "meta", "=", "None", ")", ":", "if", "self", ".", "_parler_meta", "is", "None", ":", "raise", "Imprope...
Fetch the translated fields model.
[ "Fetch", "the", "translated", "fields", "model", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L445-L557
train
211,687
django-parler/django-parler
parler/models.py
TranslatableModelMixin._get_any_translated_model
def _get_any_translated_model(self, meta=None): """ Return any available translation. Returns None if there are no translations at all. """ if meta is None: meta = self._parler_meta.root tr_model = meta.model local_cache = self._translations_cache[tr_model] if local_cache: # There is already a language available in the case. No need for queries. # Give consistent answers if they exist. check_languages = [self._current_language] + self.get_fallback_languages() try: for fallback_lang in check_languages: trans = local_cache.get(fallback_lang, None) if trans and not is_missing(trans): return trans return next(t for t in six.itervalues(local_cache) if not is_missing(t)) except StopIteration: pass try: # Use prefetch if available, otherwise perform separate query. prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: translation = prefetch[0] # Already a list else: translation = self._get_translated_queryset(meta=meta)[0] except IndexError: return None else: local_cache[translation.language_code] = translation _cache_translation(translation) return translation
python
def _get_any_translated_model(self, meta=None): """ Return any available translation. Returns None if there are no translations at all. """ if meta is None: meta = self._parler_meta.root tr_model = meta.model local_cache = self._translations_cache[tr_model] if local_cache: # There is already a language available in the case. No need for queries. # Give consistent answers if they exist. check_languages = [self._current_language] + self.get_fallback_languages() try: for fallback_lang in check_languages: trans = local_cache.get(fallback_lang, None) if trans and not is_missing(trans): return trans return next(t for t in six.itervalues(local_cache) if not is_missing(t)) except StopIteration: pass try: # Use prefetch if available, otherwise perform separate query. prefetch = self._get_prefetched_translations(meta=meta) if prefetch is not None: translation = prefetch[0] # Already a list else: translation = self._get_translated_queryset(meta=meta)[0] except IndexError: return None else: local_cache[translation.language_code] = translation _cache_translation(translation) return translation
[ "def", "_get_any_translated_model", "(", "self", ",", "meta", "=", "None", ")", ":", "if", "meta", "is", "None", ":", "meta", "=", "self", ".", "_parler_meta", ".", "root", "tr_model", "=", "meta", ".", "model", "local_cache", "=", "self", ".", "_transla...
Return any available translation. Returns None if there are no translations at all.
[ "Return", "any", "available", "translation", ".", "Returns", "None", "if", "there", "are", "no", "translations", "at", "all", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L559-L594
train
211,688
django-parler/django-parler
parler/models.py
TranslatableModelMixin._get_translated_queryset
def _get_translated_queryset(self, meta=None): """ Return the queryset that points to the translated model. If there is a prefetch, it can be read from this queryset. """ # Get via self.TRANSLATIONS_FIELD.get(..) so it also uses the prefetch/select_related cache. if meta is None: meta = self._parler_meta.root accessor = getattr(self, meta.rel_name) # RelatedManager return accessor.get_queryset()
python
def _get_translated_queryset(self, meta=None): """ Return the queryset that points to the translated model. If there is a prefetch, it can be read from this queryset. """ # Get via self.TRANSLATIONS_FIELD.get(..) so it also uses the prefetch/select_related cache. if meta is None: meta = self._parler_meta.root accessor = getattr(self, meta.rel_name) # RelatedManager return accessor.get_queryset()
[ "def", "_get_translated_queryset", "(", "self", ",", "meta", "=", "None", ")", ":", "# Get via self.TRANSLATIONS_FIELD.get(..) so it also uses the prefetch/select_related cache.", "if", "meta", "is", "None", ":", "meta", "=", "self", ".", "_parler_meta", ".", "root", "a...
Return the queryset that points to the translated model. If there is a prefetch, it can be read from this queryset.
[ "Return", "the", "queryset", "that", "points", "to", "the", "translated", "model", ".", "If", "there", "is", "a", "prefetch", "it", "can", "be", "read", "from", "this", "queryset", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L596-L606
train
211,689
django-parler/django-parler
parler/models.py
TranslatableModelMixin._get_prefetched_translations
def _get_prefetched_translations(self, meta=None): """ Return the queryset with prefetch results. """ if meta is None: meta = self._parler_meta.root related_name = meta.rel_name try: # Read the list directly, avoid QuerySet construction. # Accessing self._get_translated_queryset(parler_meta)._prefetch_done is more expensive. return self._prefetched_objects_cache[related_name] except (AttributeError, KeyError): return None
python
def _get_prefetched_translations(self, meta=None): """ Return the queryset with prefetch results. """ if meta is None: meta = self._parler_meta.root related_name = meta.rel_name try: # Read the list directly, avoid QuerySet construction. # Accessing self._get_translated_queryset(parler_meta)._prefetch_done is more expensive. return self._prefetched_objects_cache[related_name] except (AttributeError, KeyError): return None
[ "def", "_get_prefetched_translations", "(", "self", ",", "meta", "=", "None", ")", ":", "if", "meta", "is", "None", ":", "meta", "=", "self", ".", "_parler_meta", ".", "root", "related_name", "=", "meta", ".", "rel_name", "try", ":", "# Read the list directl...
Return the queryset with prefetch results.
[ "Return", "the", "queryset", "with", "prefetch", "results", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L608-L621
train
211,690
django-parler/django-parler
parler/models.py
TranslatableModelMixin.validate_unique
def validate_unique(self, exclude=None): """ Also validate the unique_together of the translated model. """ # This is called from ModelForm._post_clean() or Model.full_clean() errors = {} try: super(TranslatableModelMixin, self).validate_unique(exclude=exclude) except ValidationError as e: errors = e.message_dict for local_cache in six.itervalues(self._translations_cache): for translation in six.itervalues(local_cache): if is_missing(translation): # Skip fallback markers continue try: translation.validate_unique(exclude=exclude) except ValidationError as e: errors.update(e.message_dict) if errors: raise ValidationError(errors)
python
def validate_unique(self, exclude=None): """ Also validate the unique_together of the translated model. """ # This is called from ModelForm._post_clean() or Model.full_clean() errors = {} try: super(TranslatableModelMixin, self).validate_unique(exclude=exclude) except ValidationError as e: errors = e.message_dict for local_cache in six.itervalues(self._translations_cache): for translation in six.itervalues(local_cache): if is_missing(translation): # Skip fallback markers continue try: translation.validate_unique(exclude=exclude) except ValidationError as e: errors.update(e.message_dict) if errors: raise ValidationError(errors)
[ "def", "validate_unique", "(", "self", ",", "exclude", "=", "None", ")", ":", "# This is called from ModelForm._post_clean() or Model.full_clean()", "errors", "=", "{", "}", "try", ":", "super", "(", "TranslatableModelMixin", ",", "self", ")", ".", "validate_unique", ...
Also validate the unique_together of the translated model.
[ "Also", "validate", "the", "unique_together", "of", "the", "translated", "model", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L654-L676
train
211,691
django-parler/django-parler
parler/models.py
TranslatableModelMixin.save_translation
def save_translation(self, translation, *args, **kwargs): """ Save the translation when it's modified, or unsaved. .. note:: When a derived model provides additional translated fields, this method receives both the original and extended translation. To distinguish between both objects, check for ``translation.related_name``. :param translation: The translation :type translation: TranslatedFieldsModel :param args: Any custom arguments to pass to :func:`save`. :param kwargs: Any custom arguments to pass to :func:`save`. """ if self.pk is None or self._state.adding: raise RuntimeError("Can't save translations when the master object is not yet saved.") # Translation models without any fields are also supported. # This is useful for parent objects that have inlines; # the parent object defines how many translations there are. if translation.pk is None or translation.is_modified: if not translation.master_id: # Might not exist during first construction translation._state.db = self._state.db translation.master = self translation.save(*args, **kwargs)
python
def save_translation(self, translation, *args, **kwargs): """ Save the translation when it's modified, or unsaved. .. note:: When a derived model provides additional translated fields, this method receives both the original and extended translation. To distinguish between both objects, check for ``translation.related_name``. :param translation: The translation :type translation: TranslatedFieldsModel :param args: Any custom arguments to pass to :func:`save`. :param kwargs: Any custom arguments to pass to :func:`save`. """ if self.pk is None or self._state.adding: raise RuntimeError("Can't save translations when the master object is not yet saved.") # Translation models without any fields are also supported. # This is useful for parent objects that have inlines; # the parent object defines how many translations there are. if translation.pk is None or translation.is_modified: if not translation.master_id: # Might not exist during first construction translation._state.db = self._state.db translation.master = self translation.save(*args, **kwargs)
[ "def", "save_translation", "(", "self", ",", "translation", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "pk", "is", "None", "or", "self", ".", "_state", ".", "adding", ":", "raise", "RuntimeError", "(", "\"Can't save translati...
Save the translation when it's modified, or unsaved. .. note:: When a derived model provides additional translated fields, this method receives both the original and extended translation. To distinguish between both objects, check for ``translation.related_name``. :param translation: The translation :type translation: TranslatedFieldsModel :param args: Any custom arguments to pass to :func:`save`. :param kwargs: Any custom arguments to pass to :func:`save`.
[ "Save", "the", "translation", "when", "it", "s", "modified", "or", "unsaved", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L702-L727
train
211,692
django-parler/django-parler
parler/models.py
TranslatableModelMixin.safe_translation_getter
def safe_translation_getter(self, field, default=None, language_code=None, any_language=False): """ Fetch a translated property, and return a default value when both the translation and fallback language are missing. When ``any_language=True`` is used, the function also looks into other languages to find a suitable value. This feature can be useful for "title" attributes for example, to make sure there is at least something being displayed. Also consider using ``field = TranslatedField(any_language=True)`` in the model itself, to make this behavior the default for the given field. .. versionchanged 1.5:: The *default* parameter may also be a callable. """ meta = self._parler_meta._get_extension_by_field(field) # Extra feature: query a single field from a other translation. if language_code and language_code != self._current_language: try: tr_model = self._get_translated_model(language_code, meta=meta, use_fallback=True) return getattr(tr_model, field) except TranslationDoesNotExist: pass else: # By default, query via descriptor (TranslatedFieldDescriptor) # which also attempts the fallback language if configured to do so. try: return getattr(self, field) except TranslationDoesNotExist: pass if any_language: translation = self._get_any_translated_model(meta=meta) if translation is not None: try: return getattr(translation, field) except KeyError: pass if callable(default): return default() else: return default
python
def safe_translation_getter(self, field, default=None, language_code=None, any_language=False): """ Fetch a translated property, and return a default value when both the translation and fallback language are missing. When ``any_language=True`` is used, the function also looks into other languages to find a suitable value. This feature can be useful for "title" attributes for example, to make sure there is at least something being displayed. Also consider using ``field = TranslatedField(any_language=True)`` in the model itself, to make this behavior the default for the given field. .. versionchanged 1.5:: The *default* parameter may also be a callable. """ meta = self._parler_meta._get_extension_by_field(field) # Extra feature: query a single field from a other translation. if language_code and language_code != self._current_language: try: tr_model = self._get_translated_model(language_code, meta=meta, use_fallback=True) return getattr(tr_model, field) except TranslationDoesNotExist: pass else: # By default, query via descriptor (TranslatedFieldDescriptor) # which also attempts the fallback language if configured to do so. try: return getattr(self, field) except TranslationDoesNotExist: pass if any_language: translation = self._get_any_translated_model(meta=meta) if translation is not None: try: return getattr(translation, field) except KeyError: pass if callable(default): return default() else: return default
[ "def", "safe_translation_getter", "(", "self", ",", "field", ",", "default", "=", "None", ",", "language_code", "=", "None", ",", "any_language", "=", "False", ")", ":", "meta", "=", "self", ".", "_parler_meta", ".", "_get_extension_by_field", "(", "field", ...
Fetch a translated property, and return a default value when both the translation and fallback language are missing. When ``any_language=True`` is used, the function also looks into other languages to find a suitable value. This feature can be useful for "title" attributes for example, to make sure there is at least something being displayed. Also consider using ``field = TranslatedField(any_language=True)`` in the model itself, to make this behavior the default for the given field. .. versionchanged 1.5:: The *default* parameter may also be a callable.
[ "Fetch", "a", "translated", "property", "and", "return", "a", "default", "value", "when", "both", "the", "translation", "and", "fallback", "language", "are", "missing", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L729-L770
train
211,693
django-parler/django-parler
parler/models.py
ParlerOptions._get_extension_by_field
def _get_extension_by_field(self, name): """ Find the ParlerOptions object that corresponds with the given translated field. """ if name is None: raise TypeError("Expected field name") # Reuse existing lookups. tr_model = self.get_model_by_field(name) for meta in self._extensions: if meta.model == tr_model: return meta
python
def _get_extension_by_field(self, name): """ Find the ParlerOptions object that corresponds with the given translated field. """ if name is None: raise TypeError("Expected field name") # Reuse existing lookups. tr_model = self.get_model_by_field(name) for meta in self._extensions: if meta.model == tr_model: return meta
[ "def", "_get_extension_by_field", "(", "self", ",", "name", ")", ":", "if", "name", "is", "None", ":", "raise", "TypeError", "(", "\"Expected field name\"", ")", "# Reuse existing lookups.", "tr_model", "=", "self", ".", "get_model_by_field", "(", "name", ")", "...
Find the ParlerOptions object that corresponds with the given translated field.
[ "Find", "the", "ParlerOptions", "object", "that", "corresponds", "with", "the", "given", "translated", "field", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/models.py#L1158-L1169
train
211,694
django-parler/django-parler
parler/fields.py
_validate_master
def _validate_master(new_class): """ Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. """ if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor): raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__)) remote_field = new_class.master.field.remote_field shared_model = remote_field.model meta = shared_model._parler_meta if meta is not None: if meta._has_translations_model(new_class): raise ImproperlyConfigured("The model '{0}' already has an associated translation table!".format(shared_model.__name__)) if meta._has_translations_field(remote_field.related_name): raise ImproperlyConfigured("The model '{0}' already has an associated translation field named '{1}'!".format(shared_model.__name__, remote_field.related_name)) return shared_model
python
def _validate_master(new_class): """ Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. """ if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor): raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__)) remote_field = new_class.master.field.remote_field shared_model = remote_field.model meta = shared_model._parler_meta if meta is not None: if meta._has_translations_model(new_class): raise ImproperlyConfigured("The model '{0}' already has an associated translation table!".format(shared_model.__name__)) if meta._has_translations_field(remote_field.related_name): raise ImproperlyConfigured("The model '{0}' already has an associated translation field named '{1}'!".format(shared_model.__name__, remote_field.related_name)) return shared_model
[ "def", "_validate_master", "(", "new_class", ")", ":", "if", "not", "new_class", ".", "master", "or", "not", "isinstance", "(", "new_class", ".", "master", ",", "ForwardManyToOneDescriptor", ")", ":", "raise", "ImproperlyConfigured", "(", "\"{0}.master should be a F...
Check whether the 'master' field on a TranslatedFieldsModel is correctly configured.
[ "Check", "whether", "the", "master", "field", "on", "a", "TranslatedFieldsModel", "is", "correctly", "configured", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/fields.py#L20-L37
train
211,695
django-parler/django-parler
parler/fields.py
TranslatedFieldDescriptor.short_description
def short_description(self): """ Ensure that the admin ``list_display`` renders the correct verbose name for translated fields. The :func:`~django.contrib.admin.utils.label_for_field` function uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``. However, for translated fields, this option does not exist, hence it falls back to reading the attribute and trying ``short_description``. Ideally, translated fields should also appear in this list, to be treated like regular fields. """ translations_model = self.field.meta.model if translations_model is None: # This only happens with abstract models. The code is accessing the descriptor at the base model directly, # not the upgraded descriptor version that contribute_translations() installed. # Fallback to what the admin label_for_field() would have done otherwise. return pretty_name(self.field.name) field = translations_model._meta.get_field(self.field.name) return field.verbose_name
python
def short_description(self): """ Ensure that the admin ``list_display`` renders the correct verbose name for translated fields. The :func:`~django.contrib.admin.utils.label_for_field` function uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``. However, for translated fields, this option does not exist, hence it falls back to reading the attribute and trying ``short_description``. Ideally, translated fields should also appear in this list, to be treated like regular fields. """ translations_model = self.field.meta.model if translations_model is None: # This only happens with abstract models. The code is accessing the descriptor at the base model directly, # not the upgraded descriptor version that contribute_translations() installed. # Fallback to what the admin label_for_field() would have done otherwise. return pretty_name(self.field.name) field = translations_model._meta.get_field(self.field.name) return field.verbose_name
[ "def", "short_description", "(", "self", ")", ":", "translations_model", "=", "self", ".", "field", ".", "meta", ".", "model", "if", "translations_model", "is", "None", ":", "# This only happens with abstract models. The code is accessing the descriptor at the base model dire...
Ensure that the admin ``list_display`` renders the correct verbose name for translated fields. The :func:`~django.contrib.admin.utils.label_for_field` function uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``. However, for translated fields, this option does not exist, hence it falls back to reading the attribute and trying ``short_description``. Ideally, translated fields should also appear in this list, to be treated like regular fields.
[ "Ensure", "that", "the", "admin", "list_display", "renders", "the", "correct", "verbose", "name", "for", "translated", "fields", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/fields.py#L159-L177
train
211,696
django-parler/django-parler
parler/admin.py
BaseTranslatableAdmin.get_queryset
def get_queryset(self, request): """ Make sure the current language is selected. """ qs = super(BaseTranslatableAdmin, self).get_queryset(request) if self._has_translatable_model(): if not isinstance(qs, TranslatableQuerySet): raise ImproperlyConfigured("{0} class does not inherit from TranslatableQuerySet".format(qs.__class__.__name__)) # Apply a consistent language to all objects. qs_language = self.get_queryset_language(request) if qs_language: qs = qs.language(qs_language) return qs
python
def get_queryset(self, request): """ Make sure the current language is selected. """ qs = super(BaseTranslatableAdmin, self).get_queryset(request) if self._has_translatable_model(): if not isinstance(qs, TranslatableQuerySet): raise ImproperlyConfigured("{0} class does not inherit from TranslatableQuerySet".format(qs.__class__.__name__)) # Apply a consistent language to all objects. qs_language = self.get_queryset_language(request) if qs_language: qs = qs.language(qs_language) return qs
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "BaseTranslatableAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "if", "self", ".", "_has_translatable_model", "(", ")", ":", "if", "not", "isinstanc...
Make sure the current language is selected.
[ "Make", "sure", "the", "current", "language", "is", "selected", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L146-L161
train
211,697
django-parler/django-parler
parler/admin.py
TranslatableAdmin.all_languages_column
def all_languages_column(self, object): """ The language column which can be included in the ``list_display``. It also shows untranslated languages """ all_languages = [code for code, __ in settings.LANGUAGES] return mark_safe( self._languages_column( object, all_languages, span_classes='all-languages' ) )
python
def all_languages_column(self, object): """ The language column which can be included in the ``list_display``. It also shows untranslated languages """ all_languages = [code for code, __ in settings.LANGUAGES] return mark_safe( self._languages_column( object, all_languages, span_classes='all-languages' ) )
[ "def", "all_languages_column", "(", "self", ",", "object", ")", ":", "all_languages", "=", "[", "code", "for", "code", ",", "__", "in", "settings", ".", "LANGUAGES", "]", "return", "mark_safe", "(", "self", ".", "_languages_column", "(", "object", ",", "al...
The language column which can be included in the ``list_display``. It also shows untranslated languages
[ "The", "language", "column", "which", "can", "be", "included", "in", "the", "list_display", ".", "It", "also", "shows", "untranslated", "languages" ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L210-L220
train
211,698
django-parler/django-parler
parler/admin.py
TranslatableAdmin.get_available_languages
def get_available_languages(self, obj): """ Fetching the available languages as queryset. """ if obj: return obj.get_available_languages() else: return self.model._parler_meta.root_model.objects.none()
python
def get_available_languages(self, obj): """ Fetching the available languages as queryset. """ if obj: return obj.get_available_languages() else: return self.model._parler_meta.root_model.objects.none()
[ "def", "get_available_languages", "(", "self", ",", "obj", ")", ":", "if", "obj", ":", "return", "obj", ".", "get_available_languages", "(", ")", "else", ":", "return", "self", ".", "model", ".", "_parler_meta", ".", "root_model", ".", "objects", ".", "non...
Fetching the available languages as queryset.
[ "Fetching", "the", "available", "languages", "as", "queryset", "." ]
11ae4af5e8faddb74c69c848870122df4006a54e
https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/admin.py#L263-L270
train
211,699