Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ExitStack.close
(self)
Immediately unwind the context stack
Immediately unwind the context stack
def close(self): """Immediately unwind the context stack""" self.__exit__(None, None, None)
[ "def", "close", "(", "self", ")", ":", "self", ".", "__exit__", "(", "None", ",", "None", ",", "None", ")" ]
[ 445, 4 ]
[ 447, 39 ]
python
en
['en', 'en', 'en']
True
authenticate_with_password
(request, restriction_id)
Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction
Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction
def authenticate_with_password(request, restriction_id): """ Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction """ restriction = get_object_or_404(CollectionViewRestriction, id=restriction_id) if request.method == '...
[ "def", "authenticate_with_password", "(", "request", ",", "restriction_id", ")", ":", "restriction", "=", "get_object_or_404", "(", "CollectionViewRestriction", ",", "id", "=", "restriction_id", ")", "if", "request", ".", "method", "==", "'POST'", ":", "form", "="...
[ 113, 0 ]
[ 141, 73 ]
python
en
['en', 'error', 'th']
False
sew_messages_and_reactions
( messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]] )
Given a iterable of messages and reactions stitch reactions into messages.
Given a iterable of messages and reactions stitch reactions into messages.
def sew_messages_and_reactions( messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Given a iterable of messages and reactions stitch reactions into messages. """ # Add all messages with empty reaction item for message in messages: message["react...
[ "def", "sew_messages_and_reactions", "(", "messages", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "reactions", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", ...
[ 180, 0 ]
[ 196, 44 ]
python
en
['en', 'en', 'en']
True
access_message
( user_profile: UserProfile, message_id: int, lock_message: bool = False, )
You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream in your realm. We produce consistent, boring error messages to avoid leaking any information from a security perspe...
You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream in your realm.
def access_message( user_profile: UserProfile, message_id: int, lock_message: bool = False, ) -> Tuple[Message, Optional[UserMessage]]: """You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (...
[ "def", "access_message", "(", "user_profile", ":", "UserProfile", ",", "message_id", ":", "int", ",", "lock_message", ":", "bool", "=", "False", ",", ")", "->", "Tuple", "[", "Message", ",", "Optional", "[", "UserMessage", "]", "]", ":", "try", ":", "bas...
[ 658, 0 ]
[ 692, 48 ]
python
en
['en', 'en', 'en']
True
has_message_access
( user_profile: UserProfile, message: Message, *, has_user_message: bool, stream: Optional[Stream] = None, is_subscribed: Optional[bool] = None, )
Returns whether a user has access to a given message. * The user_message parameter must be provided if the user has a UserMessage row for the target message. * The optional stream parameter is validated; is_subscribed is not.
Returns whether a user has access to a given message.
def has_message_access( user_profile: UserProfile, message: Message, *, has_user_message: bool, stream: Optional[Stream] = None, is_subscribed: Optional[bool] = None, ) -> bool: """ Returns whether a user has access to a given message. * The user_message parameter must be provided i...
[ "def", "has_message_access", "(", "user_profile", ":", "UserProfile", ",", "message", ":", "Message", ",", "*", ",", "has_user_message", ":", "bool", ",", "stream", ":", "Optional", "[", "Stream", "]", "=", "None", ",", "is_subscribed", ":", "Optional", "[",...
[ 695, 0 ]
[ 742, 14 ]
python
en
['en', 'error', 'th']
False
bulk_access_messages
( user_profile: UserProfile, messages: Sequence[Message], *, stream: Optional[Stream] = None )
This function does the full has_message_access check for each message. If stream is provided, it is used to avoid unnecessary database queries, and will use exactly 2 bulk queries instead. Throws AssertionError if stream is passed and any of the messages were not sent to that stream.
This function does the full has_message_access check for each message. If stream is provided, it is used to avoid unnecessary database queries, and will use exactly 2 bulk queries instead.
def bulk_access_messages( user_profile: UserProfile, messages: Sequence[Message], *, stream: Optional[Stream] = None ) -> List[Message]: """This function does the full has_message_access check for each message. If stream is provided, it is used to avoid unnecessary database queries, and will use exactl...
[ "def", "bulk_access_messages", "(", "user_profile", ":", "UserProfile", ",", "messages", ":", "Sequence", "[", "Message", "]", ",", "*", ",", "stream", ":", "Optional", "[", "Stream", "]", "=", "None", ")", "->", "List", "[", "Message", "]", ":", "filter...
[ 745, 0 ]
[ 780, 28 ]
python
en
['en', 'en', 'en']
True
bulk_access_messages_expect_usermessage
( user_profile_id: int, message_ids: Sequence[int] )
Like bulk_access_messages, but faster and potentially stricter. Returns a subset of `message_ids` containing only messages the user can access. Makes O(1) database queries. Use this function only when the user is expected to have a UserMessage row for every message in `message_ids`. If a Us...
Like bulk_access_messages, but faster and potentially stricter.
def bulk_access_messages_expect_usermessage( user_profile_id: int, message_ids: Sequence[int] ) -> List[int]: """ Like bulk_access_messages, but faster and potentially stricter. Returns a subset of `message_ids` containing only messages the user can access. Makes O(1) database queries. Use th...
[ "def", "bulk_access_messages_expect_usermessage", "(", "user_profile_id", ":", "int", ",", "message_ids", ":", "Sequence", "[", "int", "]", ")", "->", "List", "[", "int", "]", ":", "return", "UserMessage", ".", "objects", ".", "filter", "(", "user_profile_id", ...
[ 783, 0 ]
[ 802, 42 ]
python
en
['en', 'error', 'th']
False
render_markdown
( message: Message, content: str, realm: Optional[Realm] = None, realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None, mention_data: Optional[MentionData] = None, email_gateway: bool = False, )
This is basically just a wrapper for do_render_markdown.
This is basically just a wrapper for do_render_markdown.
def render_markdown( message: Message, content: str, realm: Optional[Realm] = None, realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None, mention_data: Optional[MentionData] = None, email_gateway: bool = False, ) -> str: """ This is basically just a wrapper for do_render_m...
[ "def", "render_markdown", "(", "message", ":", "Message", ",", "content", ":", "str", ",", "realm", ":", "Optional", "[", "Realm", "]", "=", "None", ",", "realm_alert_words_automaton", ":", "Optional", "[", "ahocorasick", ".", "Automaton", "]", "=", "None", ...
[ 805, 0 ]
[ 835, 27 ]
python
en
['en', 'error', 'th']
False
do_render_markdown
( message: Message, content: str, realm: Realm, sent_by_bot: bool, translate_emoticons: bool, realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None, mention_data: Optional[MentionData] = None, email_gateway: bool = False, )
Return HTML for given Markdown. Markdown may add properties to the message object such as `mentions_user_ids`, `mentions_user_group_ids`, and `mentions_wildcard`. These are only on this Django object and are not saved in the database.
Return HTML for given Markdown. Markdown may add properties to the message object such as `mentions_user_ids`, `mentions_user_group_ids`, and `mentions_wildcard`. These are only on this Django object and are not saved in the database.
def do_render_markdown( message: Message, content: str, realm: Realm, sent_by_bot: bool, translate_emoticons: bool, realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None, mention_data: Optional[MentionData] = None, email_gateway: bool = False, ) -> str: """Return HTML f...
[ "def", "do_render_markdown", "(", "message", ":", "Message", ",", "content", ":", "str", ",", "realm", ":", "Realm", ",", "sent_by_bot", ":", "bool", ",", "translate_emoticons", ":", "bool", ",", "realm_alert_words_automaton", ":", "Optional", "[", "ahocorasick"...
[ 838, 0 ]
[ 872, 27 ]
python
en
['en', 'en', 'en']
True
aggregate_message_dict
( input_dict: Dict[int, Dict[str, Any]], lookup_fields: List[str], collect_senders: bool )
A concrete example might help explain the inputs here: input_dict = { 1002: dict(stream_id=5, topic='foo', sender_id=40), 1003: dict(stream_id=5, topic='foo', sender_id=41), 1004: dict(stream_id=6, topic='baz', sender_id=99), } lookup_fields = ['stream_id', 'topic'] The f...
A concrete example might help explain the inputs here:
def aggregate_message_dict( input_dict: Dict[int, Dict[str, Any]], lookup_fields: List[str], collect_senders: bool ) -> List[Dict[str, Any]]: lookup_dict: Dict[Tuple[Any, ...], Dict[str, Any]] = {} """ A concrete example might help explain the inputs here: input_dict = { 1002: dict(stream_...
[ "def", "aggregate_message_dict", "(", "input_dict", ":", "Dict", "[", "int", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "lookup_fields", ":", "List", "[", "str", "]", ",", "collect_senders", ":", "bool", ")", "->", "List", "[", "Dict", "[", ...
[ 890, 0 ]
[ 950, 48 ]
python
en
['en', 'error', 'th']
False
get_recent_conversations_recipient_id
( user_profile: UserProfile, recipient_id: int, sender_id: int )
Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure.
Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure.
def get_recent_conversations_recipient_id( user_profile: UserProfile, recipient_id: int, sender_id: int ) -> int: """Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure. """ my_recipient_id = user_profile...
[ "def", "get_recent_conversations_recipient_id", "(", "user_profile", ":", "UserProfile", ",", "recipient_id", ":", "int", ",", "sender_id", ":", "int", ")", "->", "int", ":", "my_recipient_id", "=", "user_profile", ".", "recipient_id", "if", "recipient_id", "==", ...
[ 1313, 0 ]
[ 1323, 23 ]
python
en
['en', 'en', 'en']
True
get_recent_private_conversations
(user_profile: UserProfile)
This function uses some carefully optimized SQL queries, designed to use the UserMessage index on private_messages. It is significantly complicated by the fact that for 1:1 private messages, we store the message against a recipient_id of whichever user was the recipient, and thus for 1:1 private messag...
This function uses some carefully optimized SQL queries, designed to use the UserMessage index on private_messages. It is significantly complicated by the fact that for 1:1 private messages, we store the message against a recipient_id of whichever user was the recipient, and thus for 1:1 private messag...
def get_recent_private_conversations(user_profile: UserProfile) -> Dict[int, Dict[str, Any]]: """This function uses some carefully optimized SQL queries, designed to use the UserMessage index on private_messages. It is significantly complicated by the fact that for 1:1 private messages, we store the me...
[ "def", "get_recent_private_conversations", "(", "user_profile", ":", "UserProfile", ")", "->", "Dict", "[", "int", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "RECENT_CONVERSATIONS_LIMIT", "=", "1000", "recipient_map", "=", "{", "}", "my_recipient_id", ...
[ 1326, 0 ]
[ 1431, 24 ]
python
en
['en', 'en', 'en']
True
MessageDict.wide_dict
(message: Message, realm_id: Optional[int] = None)
The next two lines get the cacheable field related to our message object, with the side effect of populating the cache.
The next two lines get the cacheable field related to our message object, with the side effect of populating the cache.
def wide_dict(message: Message, realm_id: Optional[int] = None) -> Dict[str, Any]: """ The next two lines get the cacheable field related to our message object, with the side effect of populating the cache. """ json = message_to_dict_json(message, realm_id) obj = ...
[ "def", "wide_dict", "(", "message", ":", "Message", ",", "realm_id", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "json", "=", "message_to_dict_json", "(", "message", ",", "realm_id", ")", "obj", ...
[ 259, 4 ]
[ 277, 18 ]
python
en
['en', 'error', 'th']
False
MessageDict.post_process_dicts
( objs: List[Dict[str, Any]], apply_markdown: bool, client_gravatar: bool )
NOTE: This function mutates the objects in the `objs` list, rather than making shallow copies. It might be safer to make shallow copies here, but performance is somewhat important here, as we are often fetching hundreds of messages. ...
NOTE: This function mutates the objects in the `objs` list, rather than making shallow copies. It might be safer to make shallow copies here, but performance is somewhat important here, as we are often fetching hundreds of messages. ...
def post_process_dicts( objs: List[Dict[str, Any]], apply_markdown: bool, client_gravatar: bool ) -> None: """ NOTE: This function mutates the objects in the `objs` list, rather than making shallow copies. It might be safer to make shallow copies he...
[ "def", "post_process_dicts", "(", "objs", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "apply_markdown", ":", "bool", ",", "client_gravatar", ":", "bool", ")", "->", "None", ":", "MessageDict", ".", "bulk_hydrate_sender_info", "(", "obj...
[ 280, 4 ]
[ 295, 94 ]
python
en
['en', 'error', 'th']
False
MessageDict.finalize_payload
( obj: Dict[str, Any], apply_markdown: bool, client_gravatar: bool, keep_rendered_content: bool = False, skip_copy: bool = False, )
By default, we make a shallow copy of the incoming dict to avoid mutation-related bugs. Code paths that are passing a unique object can pass skip_copy=True to avoid this extra work.
By default, we make a shallow copy of the incoming dict to avoid mutation-related bugs. Code paths that are passing a unique object can pass skip_copy=True to avoid this extra work.
def finalize_payload( obj: Dict[str, Any], apply_markdown: bool, client_gravatar: bool, keep_rendered_content: bool = False, skip_copy: bool = False, ) -> Dict[str, Any]: """ By default, we make a shallow copy of the incoming dict to avoid mutation-rel...
[ "def", "finalize_payload", "(", "obj", ":", "Dict", "[", "str", ",", "Any", "]", ",", "apply_markdown", ":", "bool", ",", "client_gravatar", ":", "bool", ",", "keep_rendered_content", ":", "bool", "=", "False", ",", "skip_copy", ":", "bool", "=", "False", ...
[ 298, 4 ]
[ 330, 18 ]
python
en
['en', 'error', 'th']
False
MessageDict.build_dict_from_raw_db_row
(row: Dict[str, Any])
row is a row from a .values() call, and it needs to have all the relevant fields populated
row is a row from a .values() call, and it needs to have all the relevant fields populated
def build_dict_from_raw_db_row(row: Dict[str, Any]) -> Dict[str, Any]: """ row is a row from a .values() call, and it needs to have all the relevant fields populated """ return MessageDict.build_message_dict( message_id=row["id"], last_edit_time=row["last_...
[ "def", "build_dict_from_raw_db_row", "(", "row", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "MessageDict", ".", "build_message_dict", "(", "message_id", "=", "row", "[", "\"id\"", "]", ",", ...
[ 416, 4 ]
[ 439, 9 ]
python
en
['en', 'error', 'th']
False
MessageDict.hydrate_recipient_info
(obj: Dict[str, Any], display_recipient: DisplayRecipientT)
This method hyrdrates recipient info with things like full names and emails of senders. Eventually our clients should be able to hyrdrate these fields themselves with info they already have on users.
This method hyrdrates recipient info with things like full names and emails of senders. Eventually our clients should be able to hyrdrate these fields themselves with info they already have on users.
def hydrate_recipient_info(obj: Dict[str, Any], display_recipient: DisplayRecipientT) -> None: """ This method hyrdrates recipient info with things like full names and emails of senders. Eventually our clients should be able to hyrdrate these fields themselves with info they alr...
[ "def", "hydrate_recipient_info", "(", "obj", ":", "Dict", "[", "str", ",", "Any", "]", ",", "display_recipient", ":", "DisplayRecipientT", ")", "->", "None", ":", "recipient_type", "=", "obj", "[", "\"recipient_type\"", "]", "recipient_type_id", "=", "obj", "[...
[ 560, 4 ]
[ 599, 48 ]
python
en
['en', 'error', 'th']
False
get_flatpages
(parser, token)
Retrieves all flatpage objects available for the current site and visible to the specific user (or visible to all users if no user is specified). Populates the template context with them in a variable whose name is defined by the ``as`` clause. An optional ``for`` clause can be used to control the...
Retrieves all flatpage objects available for the current site and visible to the specific user (or visible to all users if no user is specified). Populates the template context with them in a variable whose name is defined by the ``as`` clause.
def get_flatpages(parser, token): """ Retrieves all flatpage objects available for the current site and visible to the specific user (or visible to all users if no user is specified). Populates the template context with them in a variable whose name is defined by the ``as`` clause. An optional ...
[ "def", "get_flatpages", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "syntax_message", "=", "(", "\"%(tag_name)s expects a syntax of %(tag_name)s \"", "\"['url_starts_with'] [for user] as context_name\"", "%", "dict", "(", ...
[ 45, 0 ]
[ 100, 58 ]
python
en
['en', 'error', 'th']
False
modify_WORKSPACE
(wksp, distro_path)
Update the WORKSPACE file in the example to point to our locally-built tar.gz This allows users to clone rules_python, cd into the example/dir, and run the example directly, while our integration tests use the locally-built copy. Args: wksp: filesystem absolute path of the bazel WORKSPACE file unde...
Update the WORKSPACE file in the example to point to our locally-built tar.gz This allows users to clone rules_python, cd into the example/dir, and run the example directly, while our integration tests use the locally-built copy.
def modify_WORKSPACE(wksp, distro_path): """Update the WORKSPACE file in the example to point to our locally-built tar.gz This allows users to clone rules_python, cd into the example/dir, and run the example directly, while our integration tests use the locally-built copy. Args: wksp: filesyste...
[ "def", "modify_WORKSPACE", "(", "wksp", ",", "distro_path", ")", ":", "with", "open", "(", "wksp", ",", "'r'", ")", "as", "wksp_file", ":", "content", "=", "wksp_file", ".", "read", "(", ")", "# Replace the url for rules_python with our locally built one", "conten...
[ 13, 0 ]
[ 31, 32 ]
python
en
['en', 'en', 'en']
True
urlsafe_b64encode
(data)
urlsafe_b64encode without padding
urlsafe_b64encode without padding
def urlsafe_b64encode(data): """urlsafe_b64encode without padding""" return base64.urlsafe_b64encode(data).rstrip(b'=')
[ "def", "urlsafe_b64encode", "(", "data", ")", ":", "return", "base64", ".", "urlsafe_b64encode", "(", "data", ")", ".", "rstrip", "(", "b'='", ")" ]
[ 25, 0 ]
[ 27, 54 ]
python
en
['en', 'zu', 'en']
True
urlsafe_b64decode
(data)
urlsafe_b64decode without padding
urlsafe_b64decode without padding
def urlsafe_b64decode(data): """urlsafe_b64decode without padding""" pad = b'=' * (4 - (len(data) & 3)) return base64.urlsafe_b64decode(data + pad)
[ "def", "urlsafe_b64decode", "(", "data", ")", ":", "pad", "=", "b'='", "*", "(", "4", "-", "(", "len", "(", "data", ")", "&", "3", ")", ")", "return", "base64", ".", "urlsafe_b64decode", "(", "data", "+", "pad", ")" ]
[ 30, 0 ]
[ 33, 47 ]
python
en
['en', 'jv', 'en']
True
squash_data
(squashed)
Returns a tuple of the squashed_keys and the key position to begin processing replace and operation lists
Returns a tuple of the squashed_keys and the key position to begin processing replace and operation lists
def squash_data(squashed): """Returns a tuple of the squashed_keys and the key position to begin processing replace and operation lists""" cm = current_migration() squashed_keys = sorted(squashed.keys()) if cm is None: return squashed_keys, 0 try: key_index = squashed_keys.inde...
[ "def", "squash_data", "(", "squashed", ")", ":", "cm", "=", "current_migration", "(", ")", "squashed_keys", "=", "sorted", "(", "squashed", ".", "keys", "(", ")", ")", "if", "cm", "is", "None", ":", "return", "squashed_keys", ",", "0", "try", ":", "key...
[ 9, 0 ]
[ 22, 35 ]
python
en
['en', 'en', 'en']
True
current_migration
(exclude_squashed=True)
Get the latest migration non-squashed migration
Get the latest migration non-squashed migration
def current_migration(exclude_squashed=True): '''Get the latest migration non-squashed migration''' try: recorder = migrations.recorder.MigrationRecorder(connection) migration_qs = recorder.migration_qs.filter(app='main') if exclude_squashed: migration_qs = migration_qs.exclu...
[ "def", "current_migration", "(", "exclude_squashed", "=", "True", ")", ":", "try", ":", "recorder", "=", "migrations", ".", "recorder", ".", "MigrationRecorder", "(", "connection", ")", "migration_qs", "=", "recorder", ".", "migration_qs", ".", "filter", "(", ...
[ 25, 0 ]
[ 34, 19 ]
python
en
['en', 'en', 'en']
True
replaces
(squashed, applied=False)
Build a list of replacement migrations based on the most recent non-squashed migration and the provided list of SQUASHED migrations. If the most recent non-squashed migration is not present anywhere in the SQUASHED dictionary, assume they have all been applied. If applied is True, this will return a list o...
Build a list of replacement migrations based on the most recent non-squashed migration and the provided list of SQUASHED migrations. If the most recent non-squashed migration is not present anywhere in the SQUASHED dictionary, assume they have all been applied.
def replaces(squashed, applied=False): """Build a list of replacement migrations based on the most recent non-squashed migration and the provided list of SQUASHED migrations. If the most recent non-squashed migration is not present anywhere in the SQUASHED dictionary, assume they have all been applied. ...
[ "def", "replaces", "(", "squashed", ",", "applied", "=", "False", ")", ":", "squashed_keys", ",", "key_index", "=", "squash_data", "(", "squashed", ")", "if", "applied", ":", "return", "[", "(", "'main'", ",", "key", ")", "for", "key", "in", "squashed_ke...
[ 37, 0 ]
[ 48, 63 ]
python
en
['en', 'en', 'en']
True
operations
(squashed, applied=False)
Build a list of migration operations based on the most recent non-squashed migration and the provided list of squashed migrations. If the most recent non-squashed migration is not present anywhere in the `squashed` dictionary, assume they have all been applied. If applied is True, this will return a list o...
Build a list of migration operations based on the most recent non-squashed migration and the provided list of squashed migrations. If the most recent non-squashed migration is not present anywhere in the `squashed` dictionary, assume they have all been applied.
def operations(squashed, applied=False): """Build a list of migration operations based on the most recent non-squashed migration and the provided list of squashed migrations. If the most recent non-squashed migration is not present anywhere in the `squashed` dictionary, assume they have all been applied. ...
[ "def", "operations", "(", "squashed", ",", "applied", "=", "False", ")", ":", "squashed_keys", ",", "key_index", "=", "squash_data", "(", "squashed", ")", "op_keys", "=", "squashed_keys", "[", ":", "key_index", "]", "if", "applied", "else", "squashed_keys", ...
[ 51, 0 ]
[ 62, 50 ]
python
en
['en', 'en', 'en']
True
AbstractFormSubmission.get_data
(self)
Returns dict with form data. You can override this method to add additional data.
Returns dict with form data.
def get_data(self): """ Returns dict with form data. You can override this method to add additional data. """ form_data = json.loads(self.form_data) form_data.update({ 'submit_time': self.submit_time, }) return form_data
[ "def", "get_data", "(", "self", ")", ":", "form_data", "=", "json", ".", "loads", "(", "self", ".", "form_data", ")", "form_data", ".", "update", "(", "{", "'submit_time'", ":", "self", ".", "submit_time", ",", "}", ")", "return", "form_data" ]
[ 52, 4 ]
[ 63, 24 ]
python
en
['en', 'error', 'th']
False
AbstractFormField.save
(self, *args, **kwargs)
When new fields are created, generate a template safe ascii name to use as the JSON storage reference for this field. Previously created fields will be updated to use the legacy unidecode method via checks & _migrate_legacy_clean_name.
When new fields are created, generate a template safe ascii name to use as the JSON storage reference for this field. Previously created fields will be updated to use the legacy unidecode method via checks & _migrate_legacy_clean_name.
def save(self, *args, **kwargs): """ When new fields are created, generate a template safe ascii name to use as the JSON storage reference for this field. Previously created fields will be updated to use the legacy unidecode method via checks & _migrate_legacy_clean_name. """ ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "is_new", "=", "self", ".", "pk", "is", "None", "if", "is_new", ":", "clean_name", "=", "get_field_clean_name", "(", "self", ".", "label", ")", "self", ".", "clean_name"...
[ 119, 4 ]
[ 131, 37 ]
python
en
['en', 'error', 'th']
False
AbstractFormField._migrate_legacy_clean_name
(cls)
Ensure that existing data stored will be accessible via the legacy clean_name. When checks run, replace any blank clean_name values with the unidecode conversion.
Ensure that existing data stored will be accessible via the legacy clean_name. When checks run, replace any blank clean_name values with the unidecode conversion.
def _migrate_legacy_clean_name(cls): """ Ensure that existing data stored will be accessible via the legacy clean_name. When checks run, replace any blank clean_name values with the unidecode conversion. """ try: objects = cls.objects.filter(clean_name__exact='') ...
[ "def", "_migrate_legacy_clean_name", "(", "cls", ")", ":", "try", ":", "objects", "=", "cls", ".", "objects", ".", "filter", "(", "clean_name__exact", "=", "''", ")", "if", "objects", ".", "count", "(", ")", "==", "0", ":", "return", "None", "except", ...
[ 134, 4 ]
[ 163, 9 ]
python
en
['en', 'error', 'th']
False
AbstractForm.get_form_fields
(self)
Form page expects `form_fields` to be declared. If you want to change backwards relation name, you need to override this method.
Form page expects `form_fields` to be declared. If you want to change backwards relation name, you need to override this method.
def get_form_fields(self): """ Form page expects `form_fields` to be declared. If you want to change backwards relation name, you need to override this method. """ return self.form_fields.all()
[ "def", "get_form_fields", "(", "self", ")", ":", "return", "self", ".", "form_fields", ".", "all", "(", ")" ]
[ 200, 4 ]
[ 207, 37 ]
python
en
['en', 'error', 'th']
False
AbstractForm.get_data_fields
(self)
Returns a list of tuples with (field_name, field_label).
Returns a list of tuples with (field_name, field_label).
def get_data_fields(self): """ Returns a list of tuples with (field_name, field_label). """ data_fields = [ ('submit_time', _('Submission date')), ] data_fields += [ (field.clean_name, field.label) for field in self.get_form_fields() ...
[ "def", "get_data_fields", "(", "self", ")", ":", "data_fields", "=", "[", "(", "'submit_time'", ",", "_", "(", "'Submission date'", ")", ")", ",", "]", "data_fields", "+=", "[", "(", "field", ".", "clean_name", ",", "field", ".", "label", ")", "for", "...
[ 209, 4 ]
[ 222, 26 ]
python
en
['en', 'error', 'th']
False
AbstractForm.get_submission_class
(self)
Returns submission class. You can override this method to provide custom submission class. Your class must be inherited from AbstractFormSubmission.
Returns submission class.
def get_submission_class(self): """ Returns submission class. You can override this method to provide custom submission class. Your class must be inherited from AbstractFormSubmission. """ return FormSubmission
[ "def", "get_submission_class", "(", "self", ")", ":", "return", "FormSubmission" ]
[ 241, 4 ]
[ 249, 29 ]
python
en
['en', 'error', 'th']
False
AbstractForm.process_form_submission
(self, form)
Accepts form instance with submitted data, user and page. Creates submission instance. You can override this method if you want to have custom creation logic. For example, if you want to save reference to a user.
Accepts form instance with submitted data, user and page. Creates submission instance.
def process_form_submission(self, form): """ Accepts form instance with submitted data, user and page. Creates submission instance. You can override this method if you want to have custom creation logic. For example, if you want to save reference to a user. """ ...
[ "def", "process_form_submission", "(", "self", ",", "form", ")", ":", "return", "self", ".", "get_submission_class", "(", ")", ".", "objects", ".", "create", "(", "form_data", "=", "json", ".", "dumps", "(", "form", ".", "cleaned_data", ",", "cls", "=", ...
[ 255, 4 ]
[ 267, 9 ]
python
en
['en', 'error', 'th']
False
AbstractForm.render_landing_page
(self, request, form_submission=None, *args, **kwargs)
Renders the landing page. You can override this method to return a different HttpResponse as landing page. E.g. you could return a redirect to a separate page.
Renders the landing page.
def render_landing_page(self, request, form_submission=None, *args, **kwargs): """ Renders the landing page. You can override this method to return a different HttpResponse as landing page. E.g. you could return a redirect to a separate page. """ context = self.get_conte...
[ "def", "render_landing_page", "(", "self", ",", "request", ",", "form_submission", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", "=", "self", ".", "get_context", "(", "request", ")", "context", "[", "'form_submission'", "]", ...
[ 269, 4 ]
[ 282, 9 ]
python
en
['en', 'error', 'th']
False
AbstractForm.serve_submissions_list_view
(self, request, *args, **kwargs)
Returns list submissions view for admin. `list_submissions_view_class` can bse set to provide custom view class. Your class must be inherited from SubmissionsListView.
Returns list submissions view for admin.
def serve_submissions_list_view(self, request, *args, **kwargs): """ Returns list submissions view for admin. `list_submissions_view_class` can bse set to provide custom view class. Your class must be inherited from SubmissionsListView. """ view = self.get_submissions_li...
[ "def", "serve_submissions_list_view", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "view", "=", "self", ".", "get_submissions_list_view_class", "(", ")", ".", "as_view", "(", ")", "return", "view", "(", "request", ",", ...
[ 284, 4 ]
[ 292, 61 ]
python
en
['en', 'error', 'th']
False
path_from_root
(root: Path, path_str: Union[str, Path])
If path is relative, prepend root If path is absolute, return it directly.
If path is relative, prepend root If path is absolute, return it directly.
def path_from_root(root: Path, path_str: Union[str, Path]) -> Path: """ If path is relative, prepend root If path is absolute, return it directly. """ root = Path(os.path.expanduser(str(root))) path = Path(path_str) if not path.is_absolute(): path = root / path return path.resolv...
[ "def", "path_from_root", "(", "root", ":", "Path", ",", "path_str", ":", "Union", "[", "str", ",", "Path", "]", ")", "->", "Path", ":", "root", "=", "Path", "(", "os", ".", "path", ".", "expanduser", "(", "str", "(", "root", ")", ")", ")", "path"...
[ 5, 0 ]
[ 14, 25 ]
python
en
['en', 'error', 'th']
False
mkdir
(path_str: Union[str, Path])
Create the existing directory (and its parents) if necessary.
Create the existing directory (and its parents) if necessary.
def mkdir(path_str: Union[str, Path]) -> None: """ Create the existing directory (and its parents) if necessary. """ path = Path(path_str) path.mkdir(parents=True, exist_ok=True)
[ "def", "mkdir", "(", "path_str", ":", "Union", "[", "str", ",", "Path", "]", ")", "->", "None", ":", "path", "=", "Path", "(", "path_str", ")", "path", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")" ]
[ 17, 0 ]
[ 22, 43 ]
python
en
['en', 'error', 'th']
False
make_path_relative
(path_str: Union[str, Path], root: Path)
Try to make the given path relative, given the default root.
Try to make the given path relative, given the default root.
def make_path_relative(path_str: Union[str, Path], root: Path) -> Path: """ Try to make the given path relative, given the default root. """ path = Path(path_str) try: path = path.relative_to(root) except ValueError: pass return path
[ "def", "make_path_relative", "(", "path_str", ":", "Union", "[", "str", ",", "Path", "]", ",", "root", ":", "Path", ")", "->", "Path", ":", "path", "=", "Path", "(", "path_str", ")", "try", ":", "path", "=", "path", ".", "relative_to", "(", "root", ...
[ 25, 0 ]
[ 34, 15 ]
python
en
['en', 'error', 'th']
False
Serializer.prepare_response
(self, request, cached)
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
def prepare_response(self, request, cached): """Verify our vary headers match and construct a real urllib3 HTTPResponse object. """ # Special case the '*' Vary value as it means we cannot actually # determine if the cached response is suitable for this request. # This cas...
[ "def", "prepare_response", "(", "self", ",", "request", ",", "cached", ")", ":", "# Special case the '*' Vary value as it means we cannot actually", "# determine if the cached response is suitable for this request.", "# This case is also handled in the controller code when creating", "# a ...
[ 103, 4 ]
[ 139, 83 ]
python
en
['en', 'en', 'en']
True
_Enhance.enhance
(self, factor)
Returns an enhanced image. :param factor: A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, etc), and higher values more. ...
Returns an enhanced image.
def enhance(self, factor): """ Returns an enhanced image. :param factor: A floating point value controlling the enhancement. Factor 1.0 always returns a copy of the original image, lower factors mean less color (brightness, contrast, ...
[ "def", "enhance", "(", "self", ",", "factor", ")", ":", "return", "Image", ".", "blend", "(", "self", ".", "degenerate", ",", "self", ".", "image", ",", "factor", ")" ]
[ 24, 4 ]
[ 35, 63 ]
python
en
['en', 'error', 'th']
False
empty_cache
()
Empty oggm's cache directory.
Empty oggm's cache directory.
def empty_cache(): """Empty oggm's cache directory.""" if os.path.exists(cfg.CACHE_DIR): shutil.rmtree(cfg.CACHE_DIR) os.makedirs(cfg.CACHE_DIR)
[ "def", "empty_cache", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "cfg", ".", "CACHE_DIR", ")", ":", "shutil", ".", "rmtree", "(", "cfg", ".", "CACHE_DIR", ")", "os", ".", "makedirs", "(", "cfg", ".", "CACHE_DIR", ")" ]
[ 94, 0 ]
[ 99, 30 ]
python
en
['en', 'en', 'en']
True
expand_path
(p)
Helper function for os.path.expanduser and os.path.expandvars
Helper function for os.path.expanduser and os.path.expandvars
def expand_path(p): """Helper function for os.path.expanduser and os.path.expandvars""" return os.path.expandvars(os.path.expanduser(p))
[ "def", "expand_path", "(", "p", ")", ":", "return", "os", ".", "path", ".", "expandvars", "(", "os", ".", "path", ".", "expanduser", "(", "p", ")", ")" ]
[ 102, 0 ]
[ 105, 52 ]
python
en
['en', 'en', 'en']
True
gettempdir
(dirname='', reset=False, home=False)
Get a temporary directory. The default is to locate it in the system's temporary directory as given by python's `tempfile.gettempdir()/OGGM'. You can set `home=True` for a directory in the user's `home/tmp` folder instead (this isn't really a temporary folder but well...) Parameters ----------...
Get a temporary directory.
def gettempdir(dirname='', reset=False, home=False): """Get a temporary directory. The default is to locate it in the system's temporary directory as given by python's `tempfile.gettempdir()/OGGM'. You can set `home=True` for a directory in the user's `home/tmp` folder instead (this isn't really a ...
[ "def", "gettempdir", "(", "dirname", "=", "''", ",", "reset", "=", "False", ",", "home", "=", "False", ")", ":", "basedir", "=", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'tmp'", ")", ...
[ 108, 0 ]
[ 132, 69 ]
python
en
['en', 'en', 'en']
True
get_sys_info
()
Returns system information as a list of tuples
Returns system information as a list of tuples
def get_sys_info(): """Returns system information as a list of tuples""" blob = [] try: (sysname, nodename, release, version, machine, processor) = platform.uname() blob.extend([ ("python", "%d.%d.%d.%s.%s" % sys.version_info[:]), ("python-bits", struct.calc...
[ "def", "get_sys_info", "(", ")", ":", "blob", "=", "[", "]", "try", ":", "(", "sysname", ",", "nodename", ",", "release", ",", "version", ",", "machine", ",", "processor", ")", "=", "platform", ".", "uname", "(", ")", "blob", ".", "extend", "(", "[...
[ 139, 0 ]
[ 157, 15 ]
python
en
['en', 'en', 'en']
True
get_env_info
()
Returns env information as a list of tuples
Returns env information as a list of tuples
def get_env_info(): """Returns env information as a list of tuples""" deps = [ # (MODULE_NAME, f(mod) -> mod version) ("oggm", lambda mod: mod.__version__), ("numpy", lambda mod: mod.__version__), ("scipy", lambda mod: mod.__version__), ("pandas", lambda mod: mod.__versi...
[ "def", "get_env_info", "(", ")", ":", "deps", "=", "[", "# (MODULE_NAME, f(mod) -> mod version)", "(", "\"oggm\"", ",", "lambda", "mod", ":", "mod", ".", "__version__", ")", ",", "(", "\"numpy\"", ",", "lambda", "mod", ":", "mod", ".", "__version__", ")", ...
[ 160, 0 ]
[ 193, 20 ]
python
en
['en', 'en', 'en']
True
show_versions
(logger=None)
Prints the OGGM version and other system information. Parameters ---------- logger : optional the logger you want to send the printouts to. If None, will use stdout Returns ------- the output string
Prints the OGGM version and other system information.
def show_versions(logger=None): """Prints the OGGM version and other system information. Parameters ---------- logger : optional the logger you want to send the printouts to. If None, will use stdout Returns ------- the output string """ sys_info = get_sys_info() deps_...
[ "def", "show_versions", "(", "logger", "=", "None", ")", ":", "sys_info", "=", "get_sys_info", "(", ")", "deps_blob", "=", "get_env_info", "(", ")", "out", "=", "[", "'# OGGM environment: '", "]", "out", ".", "append", "(", "\"## System info:\"", ")", "for",...
[ 203, 0 ]
[ 231, 25 ]
python
en
['en', 'en', 'en']
True
lazy_property
(fn)
Decorator that makes a property lazy-evaluated.
Decorator that makes a property lazy-evaluated.
def lazy_property(fn): """Decorator that makes a property lazy-evaluated.""" attr_name = '_lazy_' + fn.__name__ @property @wraps(fn) def _lazy_property(self): if not hasattr(self, attr_name): setattr(self, attr_name, fn(self)) return getattr(self, attr_name) return...
[ "def", "lazy_property", "(", "fn", ")", ":", "attr_name", "=", "'_lazy_'", "+", "fn", ".", "__name__", "@", "property", "@", "wraps", "(", "fn", ")", "def", "_lazy_property", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "attr_name",...
[ 287, 0 ]
[ 299, 25 ]
python
en
['en', 'en', 'en']
True
mkdir
(path, reset=False)
Checks if directory exists and if not, create one. Parameters ---------- reset: erase the content of the directory if exists Returns ------- the path
Checks if directory exists and if not, create one.
def mkdir(path, reset=False): """Checks if directory exists and if not, create one. Parameters ---------- reset: erase the content of the directory if exists Returns ------- the path """ if reset and os.path.exists(path): shutil.rmtree(path) # deleting stuff takes ...
[ "def", "mkdir", "(", "path", ",", "reset", "=", "False", ")", ":", "if", "reset", "and", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "# deleting stuff takes time", "while", "os", ".", "path", "....
[ 302, 0 ]
[ 323, 15 ]
python
en
['en', 'en', 'en']
True
include_patterns
(*patterns)
Factory function that can be used with copytree() ignore parameter. Arguments define a sequence of glob-style patterns that are used to specify what files to NOT ignore. Creates and returns a function that determines this for each directory in the file hierarchy rooted at the source directory when used...
Factory function that can be used with copytree() ignore parameter.
def include_patterns(*patterns): """Factory function that can be used with copytree() ignore parameter. Arguments define a sequence of glob-style patterns that are used to specify what files to NOT ignore. Creates and returns a function that determines this for each directory in the file hierarchy ...
[ "def", "include_patterns", "(", "*", "patterns", ")", ":", "def", "_ignore_patterns", "(", "path", ",", "names", ")", ":", "# This is our cuisine", "bname", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "'divide'", "in", "bname", "or", ...
[ 326, 0 ]
[ 352, 27 ]
python
en
['en', 'en', 'en']
True
pipe_log
(gdir, task_func_name, err=None)
Log the error in a specific directory.
Log the error in a specific directory.
def pipe_log(gdir, task_func_name, err=None): """Log the error in a specific directory.""" time_str = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') # Defaults to working directory: it must be set! if not cfg.PATHS['working_dir']: warnings.warn("Cannot log to file without a valid " ...
[ "def", "pipe_log", "(", "gdir", ",", "task_func_name", ",", "err", "=", "None", ")", ":", "time_str", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "# Defaults to working directory: it must be set!", "i...
[ 363, 0 ]
[ 392, 31 ]
python
en
['en', 'en', 'en']
True
get_ref_mb_glaciers_candidates
(rgi_version=None)
Reads in the WGMS list of glaciers with available MB data. Can be found afterwards (and extended) in cdf.DATA['RGIXX_ref_ids'].
Reads in the WGMS list of glaciers with available MB data.
def get_ref_mb_glaciers_candidates(rgi_version=None): """Reads in the WGMS list of glaciers with available MB data. Can be found afterwards (and extended) in cdf.DATA['RGIXX_ref_ids']. """ if rgi_version is None: rgi_version = cfg.PARAMS['rgi_version'] if len(rgi_version) == 2: # ...
[ "def", "get_ref_mb_glaciers_candidates", "(", "rgi_version", "=", "None", ")", ":", "if", "rgi_version", "is", "None", ":", "rgi_version", "=", "cfg", ".", "PARAMS", "[", "'rgi_version'", "]", "if", "len", "(", "rgi_version", ")", "==", "2", ":", "# We might...
[ 553, 0 ]
[ 572, 24 ]
python
en
['en', 'en', 'en']
True
get_ref_mb_glaciers
(gdirs, y0=None, y1=None)
Get the list of glaciers we have valid mass balance measurements for. To be valid glaciers must have more than 5 years of measurements and be land terminating. Therefore, the list depends on the time period of the baseline climate data and this method selects them out of a list of potential candidates ...
Get the list of glaciers we have valid mass balance measurements for.
def get_ref_mb_glaciers(gdirs, y0=None, y1=None): """Get the list of glaciers we have valid mass balance measurements for. To be valid glaciers must have more than 5 years of measurements and be land terminating. Therefore, the list depends on the time period of the baseline climate data and this metho...
[ "def", "get_ref_mb_glaciers", "(", "gdirs", ",", "y0", "=", "None", ",", "y1", "=", "None", ")", ":", "# Get the links", "ref_ids", "=", "get_ref_mb_glaciers_candidates", "(", "gdirs", "[", "0", "]", ".", "rgi_version", ")", "# We remove tidewater glaciers and gla...
[ 576, 0 ]
[ 620, 20 ]
python
en
['en', 'en', 'en']
True
get_centerline_lonlat
(gdir, flowlines_output=False, geometrical_widths_output=False, corrected_widths_output=False)
Helper task to convert the centerlines to a shapefile Parameters ---------- gdir : the glacier directory flowlines_output : create a shapefile for the flowlines geometrical_widths_output : for the geometrical witdths corrected_widths_output : for the corrected widths Returns ------- ...
Helper task to convert the centerlines to a shapefile
def get_centerline_lonlat(gdir, flowlines_output=False, geometrical_widths_output=False, corrected_widths_output=False): """Helper task to convert the centerlines to a shapefile Parameters ---------- gdir : the glacier direct...
[ "def", "get_centerline_lonlat", "(", "gdir", ",", "flowlines_output", "=", "False", ",", "geometrical_widths_output", "=", "False", ",", "corrected_widths_output", "=", "False", ")", ":", "if", "flowlines_output", "or", "geometrical_widths_output", "or", "corrected_widt...
[ 624, 0 ]
[ 686, 16 ]
python
en
['en', 'en', 'en']
True
_write_shape_to_disk
(gdf, fpath, to_tar=False)
Write a shapefile to disk with optional compression Parameters ---------- gdf : gpd.GeoDataFrame the data to write fpath : str where to writ the file - should be ending in shp to_tar : bool put the files in a .tar file. If cfg.PARAMS['use_compression'], also compress...
Write a shapefile to disk with optional compression
def _write_shape_to_disk(gdf, fpath, to_tar=False): """Write a shapefile to disk with optional compression Parameters ---------- gdf : gpd.GeoDataFrame the data to write fpath : str where to writ the file - should be ending in shp to_tar : bool put the files in a .tar fi...
[ "def", "_write_shape_to_disk", "(", "gdf", ",", "fpath", ",", "to_tar", "=", "False", ")", ":", "if", "'.shp'", "not", "in", "fpath", ":", "raise", "ValueError", "(", "'File ending should be .shp'", ")", "gdf", ".", "to_file", "(", "fpath", ")", "if", "not...
[ 689, 0 ]
[ 730, 21 ]
python
en
['en', 'en', 'en']
True
write_centerlines_to_shape
(gdirs, *, path=True, to_tar=False, filesuffix='', flowlines_output=False, geometrical_widths_output=False, corrected_widths_output=False)
Write the centerlines in a shapefile. Parameters ---------- gdirs: the list of GlacierDir to process. path: Set to "True" in order to store the info in the working directory Set to a path to store the file to your chosen location to_tar : bool put the files in a .tar file. ...
Write the centerlines in a shapefile.
def write_centerlines_to_shape(gdirs, *, path=True, to_tar=False, filesuffix='', flowlines_output=False, geometrical_widths_output=False, corrected_widths_output=False): """Write the centerlines in a shapefile. Paramet...
[ "def", "write_centerlines_to_shape", "(", "gdirs", ",", "*", ",", "path", "=", "True", ",", "to_tar", "=", "False", ",", "filesuffix", "=", "''", ",", "flowlines_output", "=", "False", ",", "geometrical_widths_output", "=", "False", ",", "corrected_widths_output...
[ 734, 0 ]
[ 775, 50 ]
python
en
['en', 'en', 'en']
True
demo_glacier_id
(key)
Get the RGI id of a glacier by name or key: None if not found.
Get the RGI id of a glacier by name or key: None if not found.
def demo_glacier_id(key): """Get the RGI id of a glacier by name or key: None if not found.""" df = cfg.DATA['demo_glaciers'] # Is the name in key? s = df.loc[df.Key.str.lower() == key.lower()] if len(s) == 1: return s.index[0] # Is the name in name? s = df.loc[df.Name.str.lower()...
[ "def", "demo_glacier_id", "(", "key", ")", ":", "df", "=", "cfg", ".", "DATA", "[", "'demo_glaciers'", "]", "# Is the name in key?", "s", "=", "df", ".", "loc", "[", "df", ".", "Key", ".", "str", ".", "lower", "(", ")", "==", "key", ".", "lower", "...
[ 778, 0 ]
[ 801, 15 ]
python
en
['en', 'en', 'en']
True
compile_run_output
(gdirs, path=True, input_filesuffix='', use_compression=True)
Merge the output of the model runs of several gdirs into one file. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process path : str where to store (default is on the working dir). Set to `False` to disable disk storage...
Merge the output of the model runs of several gdirs into one file.
def compile_run_output(gdirs, path=True, input_filesuffix='', use_compression=True): """Merge the output of the model runs of several gdirs into one file. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process ...
[ "def", "compile_run_output", "(", "gdirs", ",", "path", "=", "True", ",", "input_filesuffix", "=", "''", ",", "use_compression", "=", "True", ")", ":", "# Get the dimensions of all this", "rgi_ids", "=", "[", "gd", ".", "rgi_id", "for", "gd", "in", "gdirs", ...
[ 929, 0 ]
[ 1082, 13 ]
python
en
['en', 'en', 'en']
True
compile_climate_input
(gdirs, path=True, filename='climate_historical', input_filesuffix='', use_compression=True)
Merge the climate input files in the glacier directories into one file. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process path : str where to store (default is on the working dir). Set to `False` to disable disk st...
Merge the climate input files in the glacier directories into one file.
def compile_climate_input(gdirs, path=True, filename='climate_historical', input_filesuffix='', use_compression=True): """Merge the climate input files in the glacier directories into one file. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects ...
[ "def", "compile_climate_input", "(", "gdirs", ",", "path", "=", "True", ",", "filename", "=", "'climate_historical'", ",", "input_filesuffix", "=", "''", ",", "use_compression", "=", "True", ")", ":", "# Get the dimensions of all this", "rgi_ids", "=", "[", "gd", ...
[ 1087, 0 ]
[ 1214, 13 ]
python
en
['en', 'en', 'en']
True
compile_task_log
(gdirs, task_names=[], filesuffix='', path=True, append=True)
Gathers the log output for the selected task(s) Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process task_names : list of str The tasks to check for filesuffix : str add suffix to output file path: Set...
Gathers the log output for the selected task(s)
def compile_task_log(gdirs, task_names=[], filesuffix='', path=True, append=True): """Gathers the log output for the selected task(s) Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process task_names : list of ...
[ "def", "compile_task_log", "(", "gdirs", ",", "task_names", "=", "[", "]", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "append", "=", "True", ")", ":", "out_df", "=", "[", "]", "for", "gdir", "in", "gdirs", ":", "d", "=", "OrderedD...
[ 1218, 0 ]
[ 1264, 14 ]
python
en
['en', 'en', 'en']
True
compile_task_time
(gdirs, task_names=[], filesuffix='', path=True, append=True)
Gathers the time needed for the selected task(s) to run Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process task_names : list of str The tasks to check for filesuffix : str add suffix to output file path: ...
Gathers the time needed for the selected task(s) to run
def compile_task_time(gdirs, task_names=[], filesuffix='', path=True, append=True): """Gathers the time needed for the selected task(s) to run Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process task_names ...
[ "def", "compile_task_time", "(", "gdirs", ",", "task_names", "=", "[", "]", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "append", "=", "True", ")", ":", "out_df", "=", "[", "]", "for", "gdir", "in", "gdirs", ":", "d", "=", "Ordered...
[ 1268, 0 ]
[ 1311, 14 ]
python
en
['en', 'en', 'en']
True
glacier_statistics
(gdir, inversion_only=False, apply_func=None)
Gather as much statistics as possible about this glacier. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Parameters ---------- inversion_only : bool if one wants to sum...
Gather as much statistics as possible about this glacier.
def glacier_statistics(gdir, inversion_only=False, apply_func=None): """Gather as much statistics as possible about this glacier. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Par...
[ "def", "glacier_statistics", "(", "gdir", ",", "inversion_only", "=", "False", ",", "apply_func", "=", "None", ")", ":", "d", "=", "OrderedDict", "(", ")", "# Easy stats - this should always be possible", "d", "[", "'rgi_id'", "]", "=", "gdir", ".", "rgi_id", ...
[ 1315, 0 ]
[ 1486, 12 ]
python
en
['en', 'en', 'en']
True
compile_glacier_statistics
(gdirs, filesuffix='', path=True, inversion_only=False, apply_func=None)
Gather as much statistics as possible about a list of glaciers. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDire...
Gather as much statistics as possible about a list of glaciers.
def compile_glacier_statistics(gdirs, filesuffix='', path=True, inversion_only=False, apply_func=None): """Gather as much statistics as possible about a list of glaciers. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not av...
[ "def", "compile_glacier_statistics", "(", "gdirs", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "inversion_only", "=", "False", ",", "apply_func", "=", "None", ")", ":", "from", "oggm", ".", "workflow", "import", "execute_entity_task", "out_df"...
[ 1490, 0 ]
[ 1534, 14 ]
python
en
['en', 'en', 'en']
True
compile_fixed_geometry_mass_balance
(gdirs, filesuffix='', path=True, csv=False, use_inversion_flowlines=True, ys=None, ye=None, years=None)
Compiles a table of specific mass-balance timeseries for all glaciers. The file is stored in a hdf file (not csv) per default. Use pd.read_hdf to open it. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier directories to process filesuffix : str...
Compiles a table of specific mass-balance timeseries for all glaciers.
def compile_fixed_geometry_mass_balance(gdirs, filesuffix='', path=True, csv=False, use_inversion_flowlines=True, ys=None, ye=None, years=None): """Compiles a table of specific mass-balance timese...
[ "def", "compile_fixed_geometry_mass_balance", "(", "gdirs", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "csv", "=", "False", ",", "use_inversion_flowlines", "=", "True", ",", "ys", "=", "None", ",", "ye", "=", "None", ",", "years", "=", ...
[ 1538, 0 ]
[ 1597, 14 ]
python
en
['en', 'en', 'en']
True
compile_ela
(gdirs, filesuffix='', path=True, csv=False, ys=None, ye=None, years=None, climate_filename='climate_historical', temperature_bias=None, precipitation_factor=None, climate_input_filesuffix='')
Compiles a table of ELA timeseries for all glaciers for a given years, using the PastMassBalance model. The file is stored in a hdf file (not csv) per default. Use pd.read_hdf to open it. Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects the glacier direct...
Compiles a table of ELA timeseries for all glaciers for a given years, using the PastMassBalance model.
def compile_ela(gdirs, filesuffix='', path=True, csv=False, ys=None, ye=None, years=None, climate_filename='climate_historical', temperature_bias=None, precipitation_factor=None, climate_input_filesuffix=''): """Compiles a table of ELA timeseries for all glaciers for a given years, ...
[ "def", "compile_ela", "(", "gdirs", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "csv", "=", "False", ",", "ys", "=", "None", ",", "ye", "=", "None", ",", "years", "=", "None", ",", "climate_filename", "=", "'climate_historical'", ",", ...
[ 1601, 0 ]
[ 1670, 14 ]
python
en
['en', 'en', 'en']
True
climate_statistics
(gdir, add_climate_period=1995)
Gather as much statistics as possible about this glacier. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Parameters ---------- add_climate_period : int or list of ints ...
Gather as much statistics as possible about this glacier.
def climate_statistics(gdir, add_climate_period=1995): """Gather as much statistics as possible about this glacier. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Parameters --...
[ "def", "climate_statistics", "(", "gdir", ",", "add_climate_period", "=", "1995", ")", ":", "from", "oggm", ".", "core", ".", "massbalance", "import", "(", "ConstantMassBalance", ",", "MultipleFlowlineMassBalance", ")", "d", "=", "OrderedDict", "(", ")", "# Easy...
[ 1674, 0 ]
[ 1796, 12 ]
python
en
['en', 'en', 'en']
True
compile_climate_statistics
(gdirs, filesuffix='', path=True, add_climate_period=1995)
Gather as much statistics as possible about a list of glaciers. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.: flowlines length) it will simply be ignored. Parameters ---------- gdirs: the list of GlacierDir to process. ...
Gather as much statistics as possible about a list of glaciers.
def compile_climate_statistics(gdirs, filesuffix='', path=True, add_climate_period=1995): """Gather as much statistics as possible about a list of glaciers. It can be used to do result diagnostics and other stuffs. If the data necessary for a statistic is not available (e.g.:...
[ "def", "compile_climate_statistics", "(", "gdirs", ",", "filesuffix", "=", "''", ",", "path", "=", "True", ",", "add_climate_period", "=", "1995", ")", ":", "from", "oggm", ".", "workflow", "import", "execute_entity_task", "out_df", "=", "execute_entity_task", "...
[ 1800, 0 ]
[ 1833, 14 ]
python
en
['en', 'en', 'en']
True
extend_past_climate_run
(past_run_file=None, fixed_geometry_mb_file=None, glacier_statistics_file=None, path=False, use_compression=True)
Utility function to extend past MB runs prior to the RGI date. We use a fixed geometry (and a fixed calving rate) for all dates prior to the RGI date. This is not parallelized, i.e a bit slow. Parameters ---------- past_run_file : str path to the historical run (nc) fixed_geometry...
Utility function to extend past MB runs prior to the RGI date.
def extend_past_climate_run(past_run_file=None, fixed_geometry_mb_file=None, glacier_statistics_file=None, path=False, use_compression=True): """Utility function to extend past MB runs prior to the RGI da...
[ "def", "extend_past_climate_run", "(", "past_run_file", "=", "None", ",", "fixed_geometry_mb_file", "=", "None", ",", "glacier_statistics_file", "=", "None", ",", "path", "=", "False", ",", "use_compression", "=", "True", ")", ":", "log", ".", "workflow", "(", ...
[ 1836, 0 ]
[ 2015, 14 ]
python
en
['en', 'en', 'en']
True
idealized_gdir
(surface_h, widths_m, map_dx, flowline_dx=1, base_dir=None, reset=False)
Creates a glacier directory with flowline input data only. This is useful for testing, or for idealized experiments. Parameters ---------- surface_h : ndarray the surface elevation of the flowline's grid points (in m). widths_m : ndarray the widths of the flowline's grid points (in...
Creates a glacier directory with flowline input data only.
def idealized_gdir(surface_h, widths_m, map_dx, flowline_dx=1, base_dir=None, reset=False): """Creates a glacier directory with flowline input data only. This is useful for testing, or for idealized experiments. Parameters ---------- surface_h : ndarray the surface eleva...
[ "def", "idealized_gdir", "(", "surface_h", ",", "widths_m", ",", "map_dx", ",", "flowline_dx", "=", "1", ",", "base_dir", "=", "None", ",", "reset", "=", "False", ")", ":", "from", "oggm", ".", "core", ".", "centerlines", "import", "Centerline", "# Area fr...
[ 2018, 0 ]
[ 2074, 15 ]
python
en
['en', 'en', 'en']
True
_back_up_retry
(func, exceptions, max_count=5)
Re-Try an action up to max_count times.
Re-Try an action up to max_count times.
def _back_up_retry(func, exceptions, max_count=5): """Re-Try an action up to max_count times. """ count = 0 while count < max_count: try: if count > 0: time.sleep(random.uniform(0.05, 0.1)) return func() except exceptions: count += 1 ...
[ "def", "_back_up_retry", "(", "func", ",", "exceptions", ",", "max_count", "=", "5", ")", ":", "count", "=", "0", "while", "count", "<", "max_count", ":", "try", ":", "if", "count", ">", "0", ":", "time", ".", "sleep", "(", "random", ".", "uniform", ...
[ 2077, 0 ]
[ 2090, 21 ]
python
en
['en', 'en', 'en']
True
_robust_extract
(to_dir, *args, **kwargs)
For some obscure reason this operation randomly fails. Try to make it more robust.
For some obscure reason this operation randomly fails.
def _robust_extract(to_dir, *args, **kwargs): """For some obscure reason this operation randomly fails. Try to make it more robust. """ def func(): with tarfile.open(*args, **kwargs) as tf: if not len(tf.getnames()): raise RuntimeError("Empty tarfile") t...
[ "def", "_robust_extract", "(", "to_dir", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "func", "(", ")", ":", "with", "tarfile", ".", "open", "(", "*", "args", ",", "*", "*", "kwargs", ")", "as", "tf", ":", "if", "not", "len", "("...
[ 2093, 0 ]
[ 2105, 41 ]
python
en
['en', 'en', 'en']
True
robust_tar_extract
(from_tar, to_dir, delete_tar=False)
Extract a tar file - also checks for a "tar in tar" situation
Extract a tar file - also checks for a "tar in tar" situation
def robust_tar_extract(from_tar, to_dir, delete_tar=False): """Extract a tar file - also checks for a "tar in tar" situation""" if os.path.isfile(from_tar): _robust_extract(to_dir, from_tar, 'r') else: # maybe a tar in tar base_tar = os.path.dirname(from_tar) + '.tar' if not...
[ "def", "robust_tar_extract", "(", "from_tar", ",", "to_dir", ",", "delete_tar", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "from_tar", ")", ":", "_robust_extract", "(", "to_dir", ",", "from_tar", ",", "'r'", ")", "else", ":", ...
[ 2108, 0 ]
[ 2134, 27 ]
python
en
['en', 'en', 'en']
True
__init__
(self, rgi_entity, base_dir=None, reset=False, from_tar=False, delete_tar=False)
Creates a new directory or opens an existing one. Parameters ---------- rgi_entity : a ``geopandas.GeoSeries`` or str glacier entity read from the shapefile (or a valid RGI ID if the directory exists) base_dir : str path to the directory where to open...
Creates a new directory or opens an existing one.
def __init__(self, rgi_entity, base_dir=None, reset=False, from_tar=False, delete_tar=False): """Creates a new directory or opens an existing one. Parameters ---------- rgi_entity : a ``geopandas.GeoSeries`` or str glacier entity read from the shapefile (or ...
[ "def", "__init__", "(", "self", ",", "rgi_entity", ",", "base_dir", "=", "None", ",", "reset", "=", "False", ",", "from_tar", "=", "False", ",", "delete_tar", "=", "False", ")", ":", "if", "base_dir", "is", "None", ":", "if", "not", "cfg", ".", "PATH...
[ 2181, 4 ]
[ 2382, 29 ]
python
en
['en', 'en', 'en']
True
grid_from_params
(self)
If the glacier_grid.json file is lost, reconstruct it.
If the glacier_grid.json file is lost, reconstruct it.
def grid_from_params(self): """If the glacier_grid.json file is lost, reconstruct it.""" from oggm.core.gis import glacier_grid_params utm_proj, nx, ny, ulx, uly, dx = glacier_grid_params(self) x0y0 = (ulx+dx/2, uly-dx/2) # To pixel center coordinates return salem.Grid(proj=utm_...
[ "def", "grid_from_params", "(", "self", ")", ":", "from", "oggm", ".", "core", ".", "gis", "import", "glacier_grid_params", "utm_proj", ",", "nx", ",", "ny", ",", "ulx", ",", "uly", ",", "dx", "=", "glacier_grid_params", "(", "self", ")", "x0y0", "=", ...
[ 2464, 4 ]
[ 2470, 36 ]
python
en
['en', 'en', 'en']
True
grid
(self)
A ``salem.Grid`` handling the georeferencing of the local grid
A ``salem.Grid`` handling the georeferencing of the local grid
def grid(self): """A ``salem.Grid`` handling the georeferencing of the local grid""" try: return salem.Grid.from_json(self.get_filepath('glacier_grid')) except FileNotFoundError: raise InvalidWorkflowError('This glacier directory seems to ' ...
[ "def", "grid", "(", "self", ")", ":", "try", ":", "return", "salem", ".", "Grid", ".", "from_json", "(", "self", ".", "get_filepath", "(", "'glacier_grid'", ")", ")", "except", "FileNotFoundError", ":", "raise", "InvalidWorkflowError", "(", "'This glacier dire...
[ 2473, 4 ]
[ 2482, 47 ]
python
en
['en', 'en', 'en']
True
rgi_area_km2
(self)
The glacier's RGI area (km2).
The glacier's RGI area (km2).
def rgi_area_km2(self): """The glacier's RGI area (km2).""" try: _area = self.read_shapefile('outlines')['Area'] return np.round(float(_area), decimals=3) except OSError: raise RuntimeError('No outlines available')
[ "def", "rgi_area_km2", "(", "self", ")", ":", "try", ":", "_area", "=", "self", ".", "read_shapefile", "(", "'outlines'", ")", "[", "'Area'", "]", "return", "np", ".", "round", "(", "float", "(", "_area", ")", ",", "decimals", "=", "3", ")", "except"...
[ 2485, 4 ]
[ 2491, 55 ]
python
en
['en', 'it', 'en']
True
intersects_ids
(self)
The glacier's intersects RGI ids.
The glacier's intersects RGI ids.
def intersects_ids(self): """The glacier's intersects RGI ids.""" try: gdf = self.read_shapefile('intersects') ids = np.append(gdf['RGIId_1'], gdf['RGIId_2']) ids = list(np.unique(np.sort(ids))) ids.remove(self.rgi_id) return ids except...
[ "def", "intersects_ids", "(", "self", ")", ":", "try", ":", "gdf", "=", "self", ".", "read_shapefile", "(", "'intersects'", ")", "ids", "=", "np", ".", "append", "(", "gdf", "[", "'RGIId_1'", "]", ",", "gdf", "[", "'RGIId_2'", "]", ")", "ids", "=", ...
[ 2494, 4 ]
[ 2503, 21 ]
python
en
['en', 'it', 'en']
True
dem_daterange
(self)
Years in which most of the DEM data was acquired
Years in which most of the DEM data was acquired
def dem_daterange(self): """Years in which most of the DEM data was acquired""" source_txt = self.get_filepath('dem_source') if os.path.isfile(source_txt): with open(source_txt, 'r') as f: for line in f.readlines(): if 'Date range:' in line: ...
[ "def", "dem_daterange", "(", "self", ")", ":", "source_txt", "=", "self", ".", "get_filepath", "(", "'dem_source'", ")", "if", "os", ".", "path", ".", "isfile", "(", "source_txt", ")", ":", "with", "open", "(", "source_txt", ",", "'r'", ")", "as", "f",...
[ 2506, 4 ]
[ 2516, 19 ]
python
en
['en', 'en', 'en']
True
dem_info
(self)
More detailed information on the acquisition of the DEM data
More detailed information on the acquisition of the DEM data
def dem_info(self): """More detailed information on the acquisition of the DEM data""" source_file = self.get_filepath('dem_source') source_text = '' if os.path.isfile(source_file): with open(source_file, 'r') as f: for line in f.readlines(): ...
[ "def", "dem_info", "(", "self", ")", ":", "source_file", "=", "self", ".", "get_filepath", "(", "'dem_source'", ")", "source_text", "=", "''", "if", "os", ".", "path", ".", "isfile", "(", "source_file", ")", ":", "with", "open", "(", "source_file", ",", ...
[ 2519, 4 ]
[ 2529, 26 ]
python
en
['en', 'en', 'en']
True
rgi_area_m2
(self)
The glacier's RGI area (m2).
The glacier's RGI area (m2).
def rgi_area_m2(self): """The glacier's RGI area (m2).""" return self.rgi_area_km2 * 10**6
[ "def", "rgi_area_m2", "(", "self", ")", ":", "return", "self", ".", "rgi_area_km2", "*", "10", "**", "6" ]
[ 2532, 4 ]
[ 2534, 40 ]
python
en
['en', 'it', 'en']
True
get_filepath
(self, filename, delete=False, filesuffix='', _deprecation_check=True)
Absolute path to a specific file. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) delete : bool delete the file if exists filesuffix : str append a suffix to the filename (useful for model runs). Note ...
Absolute path to a specific file.
def get_filepath(self, filename, delete=False, filesuffix='', _deprecation_check=True): """Absolute path to a specific file. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) delete : bool delete the file...
[ "def", "get_filepath", "(", "self", ",", "filename", ",", "delete", "=", "False", ",", "filesuffix", "=", "''", ",", "_deprecation_check", "=", "True", ")", ":", "if", "filename", "not", "in", "cfg", ".", "BASENAMES", ":", "raise", "ValueError", "(", "fi...
[ 2536, 4 ]
[ 2590, 18 ]
python
en
['en', 'en', 'en']
True
has_file
(self, filename, filesuffix='', _deprecation_check=True)
Checks if a file exists. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for model runs). Note that the BASENAME remains same.
Checks if a file exists.
def has_file(self, filename, filesuffix='', _deprecation_check=True): """Checks if a file exists. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for model runs). Not...
[ "def", "has_file", "(", "self", ",", "filename", ",", "filesuffix", "=", "''", ",", "_deprecation_check", "=", "True", ")", ":", "fp", "=", "self", ".", "get_filepath", "(", "filename", ",", "filesuffix", "=", "filesuffix", ",", "_deprecation_check", "=", ...
[ 2592, 4 ]
[ 2617, 18 ]
python
en
['en', 'mk', 'en']
True
_read_deprecated_climate_info
(self)
Temporary fix for climate_info file type change.
Temporary fix for climate_info file type change.
def _read_deprecated_climate_info(self): """Temporary fix for climate_info file type change.""" fp = self.get_filepath('climate_info') if not os.path.exists(fp): fp = fp.replace('.json', '.pkl') if not os.path.exists(fp): raise FileNotFoundError('No climat...
[ "def", "_read_deprecated_climate_info", "(", "self", ")", ":", "fp", "=", "self", ".", "get_filepath", "(", "'climate_info'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fp", ")", ":", "fp", "=", "fp", ".", "replace", "(", "'.json'", ",",...
[ 2619, 4 ]
[ 2632, 18 ]
python
en
['en', 'en', 'en']
True
add_to_diagnostics
(self, key, value)
Write a key, value pair to the gdir's runtime diagnostics. Parameters ---------- key : str dict entry key value : str or number dict entry value
Write a key, value pair to the gdir's runtime diagnostics.
def add_to_diagnostics(self, key, value): """Write a key, value pair to the gdir's runtime diagnostics. Parameters ---------- key : str dict entry key value : str or number dict entry value """ d = self.get_diagnostics() d[key] = ...
[ "def", "add_to_diagnostics", "(", "self", ",", "key", ",", "value", ")", ":", "d", "=", "self", ".", "get_diagnostics", "(", ")", "d", "[", "key", "]", "=", "value", "with", "open", "(", "self", ".", "get_filepath", "(", "'diagnostics'", ")", ",", "'...
[ 2634, 4 ]
[ 2648, 27 ]
python
en
['en', 'pt', 'en']
True
get_diagnostics
(self)
Read the gdir's runtime diagnostics. Returns ------- the diagnostics dict
Read the gdir's runtime diagnostics.
def get_diagnostics(self): """Read the gdir's runtime diagnostics. Returns ------- the diagnostics dict """ # If not there, create an empty one if not self.has_file('diagnostics'): with open(self.get_filepath('diagnostics'), 'w') as f: ...
[ "def", "get_diagnostics", "(", "self", ")", ":", "# If not there, create an empty one", "if", "not", "self", ".", "has_file", "(", "'diagnostics'", ")", ":", "with", "open", "(", "self", ".", "get_filepath", "(", "'diagnostics'", ")", ",", "'w'", ")", "as", ...
[ 2650, 4 ]
[ 2665, 18 ]
python
en
['en', 'en', 'en']
True
read_pickle
(self, filename, use_compression=None, filesuffix='')
Reads a pickle located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) use_compression : bool whether or not the file ws compressed. Default is to use cfg.PARAMS['use_compression'] for this (recommende...
Reads a pickle located in the directory.
def read_pickle(self, filename, use_compression=None, filesuffix=''): """Reads a pickle located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) use_compression : bool whether or not the file ws compressed....
[ "def", "read_pickle", "(", "self", ",", "filename", ",", "use_compression", "=", "None", ",", "filesuffix", "=", "''", ")", ":", "# Some deprecations", "if", "filename", "==", "'climate_info'", ":", "return", "self", ".", "_read_deprecated_climate_info", "(", ")...
[ 2667, 4 ]
[ 2710, 18 ]
python
en
['en', 'en', 'en']
True
write_pickle
(self, var, filename, use_compression=None, filesuffix='')
Writes a variable to a pickle on disk. Parameters ---------- var : object the variable to write to disk filename : str file name (must be listed in cfg.BASENAME) use_compression : bool whether or not the file ws compressed. Default is to use ...
Writes a variable to a pickle on disk.
def write_pickle(self, var, filename, use_compression=None, filesuffix=''): """ Writes a variable to a pickle on disk. Parameters ---------- var : object the variable to write to disk filename : str file name (must be listed in cfg.BASENAME) use_c...
[ "def", "write_pickle", "(", "self", ",", "var", ",", "filename", ",", "use_compression", "=", "None", ",", "filesuffix", "=", "''", ")", ":", "use_comp", "=", "(", "use_compression", "if", "use_compression", "is", "not", "None", "else", "cfg", ".", "PARAMS...
[ 2712, 4 ]
[ 2732, 43 ]
python
en
['en', 'en', 'en']
True
read_json
(self, filename, filesuffix='')
Reads a JSON file located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for experiments). Returns ------- A dictionary read from ...
Reads a JSON file located in the directory.
def read_json(self, filename, filesuffix=''): """Reads a JSON file located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for experiments). ...
[ "def", "read_json", "(", "self", ",", "filename", ",", "filesuffix", "=", "''", ")", ":", "# Some deprecations", "if", "filename", "==", "'climate_info'", ":", "return", "self", ".", "_read_deprecated_climate_info", "(", ")", "fp", "=", "self", ".", "get_filep...
[ 2734, 4 ]
[ 2756, 18 ]
python
en
['en', 'en', 'en']
True
write_json
(self, var, filename, filesuffix='')
Writes a variable to a pickle on disk. Parameters ---------- var : object the variable to write to JSON (must be a dictionary) filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful ...
Writes a variable to a pickle on disk.
def write_json(self, var, filename, filesuffix=''): """ Writes a variable to a pickle on disk. Parameters ---------- var : object the variable to write to JSON (must be a dictionary) filename : str file name (must be listed in cfg.BASENAME) filesu...
[ "def", "write_json", "(", "self", ",", "var", ",", "filename", ",", "filesuffix", "=", "''", ")", ":", "def", "np_convert", "(", "o", ")", ":", "if", "isinstance", "(", "o", ",", "np", ".", "int64", ")", ":", "return", "int", "(", "o", ")", "rais...
[ 2758, 4 ]
[ 2778, 49 ]
python
en
['en', 'en', 'en']
True
get_climate_info
(self, input_filesuffix='')
Convenience function handling some backwards compat aspects Parameters ---------- input_filesuffix : str input_filesuffix of the climate_historical that should be used. Default is to take the climate_historical without input_filesuffix
Convenience function handling some backwards compat aspects
def get_climate_info(self, input_filesuffix=''): """Convenience function handling some backwards compat aspects Parameters ---------- input_filesuffix : str input_filesuffix of the climate_historical that should be used. Default is to take the climate_historical ...
[ "def", "get_climate_info", "(", "self", ",", "input_filesuffix", "=", "''", ")", ":", "try", ":", "out", "=", "self", ".", "read_json", "(", "'climate_info'", ")", "except", "FileNotFoundError", ":", "out", "=", "{", "}", "try", ":", "f", "=", "self", ...
[ 2780, 4 ]
[ 2805, 18 ]
python
en
['en', 'en', 'en']
True
read_text
(self, filename, filesuffix='')
Reads a text file located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for experiments). Returns ------- the text
Reads a text file located in the directory.
def read_text(self, filename, filesuffix=''): """Reads a text file located in the directory. Parameters ---------- filename : str file name (must be listed in cfg.BASENAME) filesuffix : str append a suffix to the filename (useful for experiments). ...
[ "def", "read_text", "(", "self", ",", "filename", ",", "filesuffix", "=", "''", ")", ":", "fp", "=", "self", ".", "get_filepath", "(", "filename", ",", "filesuffix", "=", "filesuffix", ")", "with", "open", "(", "fp", ",", "'r'", ")", "as", "f", ":", ...
[ 2807, 4 ]
[ 2825, 18 ]
python
en
['en', 'en', 'en']
True
LRUFileCache.__init__
(self, l0=None, maxsize=None)
Instantiate. Parameters ---------- l0 : list a list of file paths maxsize : int the max number of files to keep
Instantiate.
def __init__(self, l0=None, maxsize=None): """Instantiate. Parameters ---------- l0 : list a list of file paths maxsize : int the max number of files to keep """ self.files = [] if l0 is None else l0 # if no maxsize is specified, u...
[ "def", "__init__", "(", "self", ",", "l0", "=", "None", ",", "maxsize", "=", "None", ")", ":", "self", ".", "files", "=", "[", "]", "if", "l0", "is", "None", "else", "l0", "# if no maxsize is specified, use value from configuration", "maxsize", "=", "cfg", ...
[ 257, 4 ]
[ 271, 20 ]
python
en
['en', 'nl', 'en']
False
LRUFileCache.purge
(self)
Remove expired entries.
Remove expired entries.
def purge(self): """Remove expired entries.""" if len(self.files) > self.maxsize: fpath = self.files.pop(0) if os.path.exists(fpath): os.remove(fpath)
[ "def", "purge", "(", "self", ")", ":", "if", "len", "(", "self", ".", "files", ")", ">", "self", ".", "maxsize", ":", "fpath", "=", "self", ".", "files", ".", "pop", "(", "0", ")", "if", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":...
[ 273, 4 ]
[ 278, 32 ]
python
en
['en', 'en', 'en']
True
LRUFileCache.append
(self, fpath)
Append a file to the list.
Append a file to the list.
def append(self, fpath): """Append a file to the list.""" if fpath not in self.files: self.files.append(fpath) self.purge()
[ "def", "append", "(", "self", ",", "fpath", ")", ":", "if", "fpath", "not", "in", "self", ".", "files", ":", "self", ".", "files", ".", "append", "(", "fpath", ")", "self", ".", "purge", "(", ")" ]
[ 280, 4 ]
[ 284, 20 ]
python
en
['en', 'en', 'en']
True
entity_task.__init__
(self, log, writes=[], fallback=None)
Decorator syntax: ``@entity_task(log, writes=['dem', 'outlines'])`` Parameters ---------- log: logger module logger writes: list list of files that the task will write down to disk (must be available in ``cfg.BASENAMES``) fallback: python func...
Decorator syntax: ``@entity_task(log, writes=['dem', 'outlines'])``
def __init__(self, log, writes=[], fallback=None): """Decorator syntax: ``@entity_task(log, writes=['dem', 'outlines'])`` Parameters ---------- log: logger module logger writes: list list of files that the task will write down to disk (must be ...
[ "def", "__init__", "(", "self", ",", "log", ",", "writes", "=", "[", "]", ",", "fallback", "=", "None", ")", ":", "self", ".", "log", "=", "log", "self", ".", "writes", "=", "writes", "self", ".", "fallback", "=", "fallback", "cnt", "=", "[", "' ...
[ 416, 4 ]
[ 444, 35 ]
python
en
['en', 'cy', 'en']
True
global_task.__init__
(self, log)
Decorator syntax: ``@global_task(log)`` Parameters ---------- log: logger module logger
Decorator syntax: ``@global_task(log)``
def __init__(self, log): """Decorator syntax: ``@global_task(log)`` Parameters ---------- log: logger module logger """ self.log = log
[ "def", "__init__", "(", "self", ",", "log", ")", ":", "self", ".", "log", "=", "log" ]
[ 524, 4 ]
[ 532, 22 ]
python
cy
['en', 'cy', 'ur']
False
compile_to_netcdf.__init__
(self, log)
Decorator syntax: ``@compile_to_netcdf(log, n_tmp_files=1000)`` Parameters ---------- log: logger module logger tmp_file_size: int number of glacier directories per temporary files
Decorator syntax: ``@compile_to_netcdf(log, n_tmp_files=1000)``
def __init__(self, log): """Decorator syntax: ``@compile_to_netcdf(log, n_tmp_files=1000)`` Parameters ---------- log: logger module logger tmp_file_size: int number of glacier directories per temporary files """ self.log = log
[ "def", "__init__", "(", "self", ",", "log", ")", ":", "self", ".", "log", "=", "log" ]
[ 811, 4 ]
[ 821, 22 ]
python
en
['en', 'en', 'ur']
True
_implementation
()
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably...
Return a dict with the Python implementation and version.
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and Py...
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", ...
[ 25, 0 ]
[ 55, 70 ]
python
en
['en', 'en', 'en']
True
info
()
Generate information for a bug report.
Generate information for a bug report.
def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } im...
[ "def", "info", "(", ")", ":", "try", ":", "platform_info", "=", "{", "'system'", ":", "platform", ".", "system", "(", ")", ",", "'release'", ":", "platform", ".", "release", "(", ")", ",", "}", "except", "IOError", ":", "platform_info", "=", "{", "'s...
[ 58, 0 ]
[ 109, 5 ]
python
en
['en', 'en', 'en']
True
main
()
Pretty-print the bug information as JSON.
Pretty-print the bug information as JSON.
def main(): """Pretty-print the bug information as JSON.""" print(json.dumps(info(), sort_keys=True, indent=2))
[ "def", "main", "(", ")", ":", "print", "(", "json", ".", "dumps", "(", "info", "(", ")", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", ")" ]
[ 112, 0 ]
[ 114, 55 ]
python
en
['en', 'en', 'en']
True
get_username
(uid)
get the username for a user id
get the username for a user id
def get_username(uid): """ get the username for a user id""" return pwd.getpwuid(uid).pw_name
[ "def", "get_username", "(", "uid", ")", ":", "return", "pwd", ".", "getpwuid", "(", "uid", ")", ".", "pw_name" ]
[ 123, 0 ]
[ 125, 36 ]
python
en
['en', 'en', 'en']
True
set_owner_process
(uid, gid, initgroups=False)
set user and group of workers processes
set user and group of workers processes
def set_owner_process(uid, gid, initgroups=False): """ set user and group of workers processes """ if gid: if uid: try: username = get_username(uid) except KeyError: initgroups = False # versions of python < 2.6.2 don't manage unsigned in...
[ "def", "set_owner_process", "(", "uid", ",", "gid", ",", "initgroups", "=", "False", ")", ":", "if", "gid", ":", "if", "uid", ":", "try", ":", "username", "=", "get_username", "(", "uid", ")", "except", "KeyError", ":", "initgroups", "=", "False", "# v...
[ 128, 0 ]
[ 148, 22 ]
python
en
['en', 'en', 'en']
True