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
Aula13/poloniex
poloniex/poloniex.py
Poloniex.marginBuy
def marginBuy(self, currencyPair, rate, amount, lendingRate=None): """Places a margin buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter. If successful, the method will return the order number and any trades immediately resulting from your order.""" return self._private('marginBuy', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
python
def marginBuy(self, currencyPair, rate, amount, lendingRate=None): """Places a margin buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter. If successful, the method will return the order number and any trades immediately resulting from your order.""" return self._private('marginBuy', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
[ "def", "marginBuy", "(", "self", ",", "currencyPair", ",", "rate", ",", "amount", ",", "lendingRate", "=", "None", ")", ":", "return", "self", ".", "_private", "(", "'marginBuy'", ",", "currencyPair", "=", "currencyPair", ",", "rate", "=", "rate", ",", "...
Places a margin buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter. If successful, the method will return the order number and any trades immediately resulting from your order.
[ "Places", "a", "margin", "buy", "order", "in", "a", "given", "market", ".", "Required", "POST", "parameters", "are", "currencyPair", "rate", "and", "amount", ".", "You", "may", "optionally", "specify", "a", "maximum", "lending", "rate", "using", "the", "lend...
a5bfc91e766e220bf77f5e3a1b131f095913e714
https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L336-L343
train
38,500
Aula13/poloniex
poloniex/poloniex.py
Poloniex.marginSell
def marginSell(self, currencyPair, rate, amount, lendingRate=None): """Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.""" return self._private('marginSell', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
python
def marginSell(self, currencyPair, rate, amount, lendingRate=None): """Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.""" return self._private('marginSell', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
[ "def", "marginSell", "(", "self", ",", "currencyPair", ",", "rate", ",", "amount", ",", "lendingRate", "=", "None", ")", ":", "return", "self", ".", "_private", "(", "'marginSell'", ",", "currencyPair", "=", "currencyPair", ",", "rate", "=", "rate", ",", ...
Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method.
[ "Places", "a", "margin", "sell", "order", "in", "a", "given", "market", ".", "Parameters", "and", "output", "are", "the", "same", "as", "for", "the", "marginBuy", "method", "." ]
a5bfc91e766e220bf77f5e3a1b131f095913e714
https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L345-L349
train
38,501
Aula13/poloniex
poloniex/poloniex.py
Poloniex.returnLendingHistory
def returnLendingHistory(self, start=0, end=2**32-1, limit=None): """Returns your lending history within a time range specified by the "start" and "end" POST parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned. """ return self._private('returnLendingHistory', start=start, end=end, limit=limit)
python
def returnLendingHistory(self, start=0, end=2**32-1, limit=None): """Returns your lending history within a time range specified by the "start" and "end" POST parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned. """ return self._private('returnLendingHistory', start=start, end=end, limit=limit)
[ "def", "returnLendingHistory", "(", "self", ",", "start", "=", "0", ",", "end", "=", "2", "**", "32", "-", "1", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_private", "(", "'returnLendingHistory'", ",", "start", "=", "start", ",", "e...
Returns your lending history within a time range specified by the "start" and "end" POST parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned.
[ "Returns", "your", "lending", "history", "within", "a", "time", "range", "specified", "by", "the", "start", "and", "end", "POST", "parameters", "as", "UNIX", "timestamps", ".", "limit", "may", "also", "be", "specified", "to", "limit", "the", "number", "of", ...
a5bfc91e766e220bf77f5e3a1b131f095913e714
https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L391-L396
train
38,502
Polyconseil/django-cid
cid/locals.py
generate_new_cid
def generate_new_cid(upstream_cid=None): """Generate a new correlation id, possibly based on the given one.""" if upstream_cid is None: return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None if ( getattr(settings, 'CID_CONCATENATE_IDS', False) and getattr(settings, 'CID_GENERATE', False) ): return '%s, %s' % (upstream_cid, str(uuid.uuid4())) return upstream_cid
python
def generate_new_cid(upstream_cid=None): """Generate a new correlation id, possibly based on the given one.""" if upstream_cid is None: return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None if ( getattr(settings, 'CID_CONCATENATE_IDS', False) and getattr(settings, 'CID_GENERATE', False) ): return '%s, %s' % (upstream_cid, str(uuid.uuid4())) return upstream_cid
[ "def", "generate_new_cid", "(", "upstream_cid", "=", "None", ")", ":", "if", "upstream_cid", "is", "None", ":", "return", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "getattr", "(", "settings", ",", "'CID_GENERATE'", ",", "False", ")", "else",...
Generate a new correlation id, possibly based on the given one.
[ "Generate", "a", "new", "correlation", "id", "possibly", "based", "on", "the", "given", "one", "." ]
43415c8bbc91aa03983384072dbc1d2ecdeb2852
https://github.com/Polyconseil/django-cid/blob/43415c8bbc91aa03983384072dbc1d2ecdeb2852/cid/locals.py#L31-L40
train
38,503
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_ups_estimated_minutes_remaining
def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off, or if it were to be lost and remain off. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom="minutes") the_helper.set_summary("Remaining runtime on battery is {} minutes".format(the_snmp_value))
python
def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off, or if it were to be lost and remain off. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom="minutes") the_helper.set_summary("Remaining runtime on battery is {} minutes".format(the_snmp_value))
[ "def", "check_ups_estimated_minutes_remaining", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options", ".", "type", ",", "value", "=", "the_snmp_value", ",", "uom", ...
OID .1.3.6.1.2.1.33.1.2.3.0 MIB excerpt An estimate of the time to battery charge depletion under the present load conditions if the utility power is off and remains off, or if it were to be lost and remain off.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "2", ".", "1", ".", "33", ".", "1", ".", "2", ".", "3", ".", "0", "MIB", "excerpt", "An", "estimate", "of", "the", "time", "to", "battery", "charge", "depletion", "under", "the", "present", ...
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L61-L75
train
38,504
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_ups_input_frequency
def check_ups_input_frequency(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency. """ a_frequency = calc_frequency_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_frequency, uom='Hz') the_helper.set_summary("Input Frequency is {} Hz".format(a_frequency))
python
def check_ups_input_frequency(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency. """ a_frequency = calc_frequency_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_frequency, uom='Hz') the_helper.set_summary("Input Frequency is {} Hz".format(a_frequency))
[ "def", "check_ups_input_frequency", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "a_frequency", "=", "calc_frequency_from_snmpvalue", "(", "the_snmp_value", ")", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options...
OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "2", ".", "1", ".", "33", ".", "1", ".", "3", ".", "3", ".", "1", ".", "2", ".", "1", "MIB", "excerpt", "The", "present", "input", "frequency", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L78-L90
train
38,505
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_ups_output_current
def check_ups_output_current(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current. """ a_current = calc_output_current_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_current, uom='A') the_helper.set_summary("Output Current is {} A".format(a_current))
python
def check_ups_output_current(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current. """ a_current = calc_output_current_from_snmpvalue(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_current, uom='A') the_helper.set_summary("Output Current is {} A".format(a_current))
[ "def", "check_ups_output_current", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "a_current", "=", "calc_output_current_from_snmpvalue", "(", "the_snmp_value", ")", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "optio...
OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "2", ".", "1", ".", "33", ".", "1", ".", "4", ".", "4", ".", "1", ".", "3", ".", "1", "MIB", "excerpt", "The", "present", "output", "current", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L121-L134
train
38,506
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_ups_alarms_present
def check_ups_alarms_present(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions. """ if the_snmp_value != '0': the_helper.add_status(pynag.Plugins.critical) else: the_helper.add_status(pynag.Plugins.ok) the_helper.set_summary("{} active alarms ".format(the_snmp_value))
python
def check_ups_alarms_present(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions. """ if the_snmp_value != '0': the_helper.add_status(pynag.Plugins.critical) else: the_helper.add_status(pynag.Plugins.ok) the_helper.set_summary("{} active alarms ".format(the_snmp_value))
[ "def", "check_ups_alarms_present", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "if", "the_snmp_value", "!=", "'0'", ":", "the_helper", ".", "add_status", "(", "pynag", ".", "Plugins", ".", "critical", ")", "else", ":", "the_helper", ...
OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "2", ".", "1", ".", "33", ".", "1", ".", "6", ".", "1", ".", "0", "MIB", "excerpt", "The", "present", "number", "of", "active", "alarm", "conditions", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L168-L178
train
38,507
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_xups_bat_capacity
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge. """ the_helper.add_metric( label=the_helper.options.type, value=a_snmp_value, uom='%') the_helper.set_summary("Remaining Battery Capacity {} %".format(the_snmp_value))
python
def check_xups_bat_capacity(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge. """ the_helper.add_metric( label=the_helper.options.type, value=a_snmp_value, uom='%') the_helper.set_summary("Remaining Battery Capacity {} %".format(the_snmp_value))
[ "def", "check_xups_bat_capacity", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options", ".", "type", ",", "value", "=", "a_snmp_value", ",", "uom", "=", "'%'", ...
OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "4", ".", "1", ".", "534", ".", "1", ".", "2", ".", "4", ".", "0", "MIB", "Excerpt", "Battery", "percent", "charge", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L241-L253
train
38,508
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py
check_xups_env_ambient_temp
def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom='degree') the_helper.set_summary("Environment Temperature is {} degree".format(the_snmp_value))
python
def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1): """ OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent. """ the_helper.add_metric( label=the_helper.options.type, value=the_snmp_value, uom='degree') the_helper.set_summary("Environment Temperature is {} degree".format(the_snmp_value))
[ "def", "check_xups_env_ambient_temp", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ",", "the_unit", "=", "1", ")", ":", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options", ".", "type", ",", "value", "=", "the_snmp...
OID .1.3.6.1.4.1.534.1.6.1.0 MIB Excerpt The reading of the ambient temperature in the vicinity of the UPS or SNMP agent.
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "4", ".", "1", ".", "534", ".", "1", ".", "6", ".", "1", ".", "0", "MIB", "Excerpt", "The", "reading", "of", "the", "ambient", "temperature", "in", "the", "vicinity", "of", "the", "UPS", "or...
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L256-L269
train
38,509
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py
check_ressources
def check_ressources(sess): """ check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine. """ # get the data cpu_value = get_data(sess, cpu_oid, helper) memory_value = get_data(sess, memory_oid, helper) filesystem_value = get_data(sess, filesystem_oid, helper) helper.add_summary("Controller Status") helper.add_long_output("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_metric("CPU", cpu_value, "0:90", "0:90", "", "", "%%") if int(cpu_value) > 90: helper.status(critical) helper.add_summary("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_long_output("Memory: %s%%" % memory_value) helper.add_metric("Memory", memory_value, "0:90", "0:90", "", "", "%%") if int(memory_value) > 90: helper.add_summary("Memory: %s%%" % memory_value) helper.status(critical) helper.add_long_output("Filesystem: %s%%" % filesystem_value) helper.add_metric("Filesystem", filesystem_value, "0:90", "0:90", "", "", "%%") if int(filesystem_value) > 90: helper.add_summary("Filesystem: %s%%" % filesystem_value) helper.status(critical)
python
def check_ressources(sess): """ check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine. """ # get the data cpu_value = get_data(sess, cpu_oid, helper) memory_value = get_data(sess, memory_oid, helper) filesystem_value = get_data(sess, filesystem_oid, helper) helper.add_summary("Controller Status") helper.add_long_output("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_metric("CPU", cpu_value, "0:90", "0:90", "", "", "%%") if int(cpu_value) > 90: helper.status(critical) helper.add_summary("Controller Ressources - CPU: %s%%" % cpu_value) helper.add_long_output("Memory: %s%%" % memory_value) helper.add_metric("Memory", memory_value, "0:90", "0:90", "", "", "%%") if int(memory_value) > 90: helper.add_summary("Memory: %s%%" % memory_value) helper.status(critical) helper.add_long_output("Filesystem: %s%%" % filesystem_value) helper.add_metric("Filesystem", filesystem_value, "0:90", "0:90", "", "", "%%") if int(filesystem_value) > 90: helper.add_summary("Filesystem: %s%%" % filesystem_value) helper.status(critical)
[ "def", "check_ressources", "(", "sess", ")", ":", "# get the data", "cpu_value", "=", "get_data", "(", "sess", ",", "cpu_oid", ",", "helper", ")", "memory_value", "=", "get_data", "(", "sess", ",", "memory_oid", ",", "helper", ")", "filesystem_value", "=", "...
check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine.
[ "check", "the", "Ressources", "of", "the", "Fortinet", "Controller", "all", "thresholds", "are", "currently", "hard", "coded", ".", "should", "be", "fine", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py#L88-L115
train
38,510
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py
check_controller
def check_controller(sess): """ check the status of the controller """ controller_operational = get_data(sess, operational_oid, helper) controller_availability = get_data(sess, availability_oid, helper) controller_alarm = get_data(sess, alarm_oid, helper) # Add summary helper.add_summary("Controller Status") # Add all states to the long output helper.add_long_output("Controller Operational State: %s" % operational_states[int(controller_operational)]) helper.add_long_output("Controller Availability State: %s" % availability_states[int(controller_availability)]) helper.add_long_output("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) # Operational State if controller_operational != "1" and controller_operational != "4": helper.status(critical) helper.add_summary("Controller Operational State: %s" % operational_states[int(controller_operational)]) # Avaiability State if controller_availability != "3": helper.status(critical) helper.add_summary("Controller Availability State: %s" % availability_states[int(controller_availability)]) # Alarm State if controller_alarm == "2": helper.status(warning) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) if controller_alarm == "3" or controller_alarm == "4": helper.status(critical) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)])
python
def check_controller(sess): """ check the status of the controller """ controller_operational = get_data(sess, operational_oid, helper) controller_availability = get_data(sess, availability_oid, helper) controller_alarm = get_data(sess, alarm_oid, helper) # Add summary helper.add_summary("Controller Status") # Add all states to the long output helper.add_long_output("Controller Operational State: %s" % operational_states[int(controller_operational)]) helper.add_long_output("Controller Availability State: %s" % availability_states[int(controller_availability)]) helper.add_long_output("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) # Operational State if controller_operational != "1" and controller_operational != "4": helper.status(critical) helper.add_summary("Controller Operational State: %s" % operational_states[int(controller_operational)]) # Avaiability State if controller_availability != "3": helper.status(critical) helper.add_summary("Controller Availability State: %s" % availability_states[int(controller_availability)]) # Alarm State if controller_alarm == "2": helper.status(warning) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) if controller_alarm == "3" or controller_alarm == "4": helper.status(critical) helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)])
[ "def", "check_controller", "(", "sess", ")", ":", "controller_operational", "=", "get_data", "(", "sess", ",", "operational_oid", ",", "helper", ")", "controller_availability", "=", "get_data", "(", "sess", ",", "availability_oid", ",", "helper", ")", "controller_...
check the status of the controller
[ "check", "the", "status", "of", "the", "controller" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py#L118-L150
train
38,511
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py
check_accesspoints
def check_accesspoints(sess): """ check the status of all connected access points """ ap_names = walk_data(sess, name_ap_oid, helper)[0] ap_operationals = walk_data(sess, operational_ap_oid, helper)[0] ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0] ap_alarms = walk_data(sess, alarm_ap_oid, helper)[0] #ap_ip = walk_data(sess, ip_ap_oid, helper) # no result helper.add_summary("Access Points Status") for x in range(len(ap_names)): ap_name = ap_names[x] ap_operational = ap_operationals[x] ap_availability = ap_availabilitys[x] ap_alarm = ap_alarms[x] # Add all states to the long output helper.add_long_output("%s - Operational: %s - Availabilty: %s - Alarm: %s" % (ap_name, operational_states[int(ap_operational)], availability_states[int(ap_availability)], alarm_states[int(ap_alarm)])) # Operational State if ap_operational != "1" and ap_operational != "4": helper.status(critical) helper.add_summary("%s Operational State: %s" % (ap_name, operational_states[int(ap_operational)])) # Avaiability State if ap_availability != "3": helper.status(critical) helper.add_summary("%s Availability State: %s" % (ap_name, availability_states[int(ap_availability)])) # Alarm State if ap_alarm == "2": helper.status(warning) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)])) if ap_alarm == "3" or ap_alarm == "4": helper.status(critical) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)]))
python
def check_accesspoints(sess): """ check the status of all connected access points """ ap_names = walk_data(sess, name_ap_oid, helper)[0] ap_operationals = walk_data(sess, operational_ap_oid, helper)[0] ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0] ap_alarms = walk_data(sess, alarm_ap_oid, helper)[0] #ap_ip = walk_data(sess, ip_ap_oid, helper) # no result helper.add_summary("Access Points Status") for x in range(len(ap_names)): ap_name = ap_names[x] ap_operational = ap_operationals[x] ap_availability = ap_availabilitys[x] ap_alarm = ap_alarms[x] # Add all states to the long output helper.add_long_output("%s - Operational: %s - Availabilty: %s - Alarm: %s" % (ap_name, operational_states[int(ap_operational)], availability_states[int(ap_availability)], alarm_states[int(ap_alarm)])) # Operational State if ap_operational != "1" and ap_operational != "4": helper.status(critical) helper.add_summary("%s Operational State: %s" % (ap_name, operational_states[int(ap_operational)])) # Avaiability State if ap_availability != "3": helper.status(critical) helper.add_summary("%s Availability State: %s" % (ap_name, availability_states[int(ap_availability)])) # Alarm State if ap_alarm == "2": helper.status(warning) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)])) if ap_alarm == "3" or ap_alarm == "4": helper.status(critical) helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)]))
[ "def", "check_accesspoints", "(", "sess", ")", ":", "ap_names", "=", "walk_data", "(", "sess", ",", "name_ap_oid", ",", "helper", ")", "[", "0", "]", "ap_operationals", "=", "walk_data", "(", "sess", ",", "operational_ap_oid", ",", "helper", ")", "[", "0",...
check the status of all connected access points
[ "check", "the", "status", "of", "all", "connected", "access", "points" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_fortinet/check_snmp_fortinet.py#L153-L191
train
38,512
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
normal_check
def normal_check(name, status, device_type): """if the status is "ok" in the NORMAL_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = NORMAL_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) elif status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
python
def normal_check(name, status, device_type): """if the status is "ok" in the NORMAL_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = NORMAL_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) elif status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
[ "def", "normal_check", "(", "name", ",", "status", ",", "device_type", ")", ":", "status_string", "=", "NORMAL_STATE", ".", "get", "(", "int", "(", "status", ")", ",", "\"unknown\"", ")", "if", "status_string", "==", "\"ok\"", ":", "return", "ok", ",", "...
if the status is "ok" in the NORMAL_STATE dict, return ok + string if the status is not "ok", return critical + string
[ "if", "the", "status", "is", "ok", "in", "the", "NORMAL_STATE", "dict", "return", "ok", "+", "string", "if", "the", "status", "is", "not", "ok", "return", "critical", "+", "string" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L163-L174
train
38,513
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
probe_check
def probe_check(name, status, device_type): """if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = PROBE_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) if status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
python
def probe_check(name, status, device_type): """if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string""" status_string = PROBE_STATE.get(int(status), "unknown") if status_string == "ok": return ok, "{} '{}': {}".format(device_type, name, status_string) if status_string == "unknown": return unknown, "{} '{}': {}".format(device_type, name, status_string) return critical, "{} '{}': {}".format(device_type, name, status_string)
[ "def", "probe_check", "(", "name", ",", "status", ",", "device_type", ")", ":", "status_string", "=", "PROBE_STATE", ".", "get", "(", "int", "(", "status", ")", ",", "\"unknown\"", ")", "if", "status_string", "==", "\"ok\"", ":", "return", "ok", ",", "\"...
if the status is "ok" in the PROBE_STATE dict, return ok + string if the status is not "ok", return critical + string
[ "if", "the", "status", "is", "ok", "in", "the", "PROBE_STATE", "dict", "return", "ok", "+", "string", "if", "the", "status", "is", "not", "ok", "return", "critical", "+", "string" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L177-L188
train
38,514
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.add_device_information
def add_device_information(helper, session): """ add general device information to summary """ host_name_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_host_name']) product_type_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_product_type']) service_tag_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_service_tag']) helper.add_summary('Name: {} - Typ: {} - Service tag: {}'.format( host_name_data, product_type_data, service_tag_data))
python
def add_device_information(helper, session): """ add general device information to summary """ host_name_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_host_name']) product_type_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_product_type']) service_tag_data = helper.get_snmp_value(session, helper, DEVICE_INFORMATION_OIDS['oid_service_tag']) helper.add_summary('Name: {} - Typ: {} - Service tag: {}'.format( host_name_data, product_type_data, service_tag_data))
[ "def", "add_device_information", "(", "helper", ",", "session", ")", ":", "host_name_data", "=", "helper", ".", "get_snmp_value", "(", "session", ",", "helper", ",", "DEVICE_INFORMATION_OIDS", "[", "'oid_host_name'", "]", ")", "product_type_data", "=", "helper", "...
add general device information to summary
[ "add", "general", "device", "information", "to", "summary" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L198-L210
train
38,515
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.process_status
def process_status(self, helper, session, check): """"process a single status""" snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check]) if check == "system_lcd": helper.update_status(helper, normal_check("global", snmp_result_status, "LCD status")) elif check == "global_storage": helper.update_status(helper, normal_check("global", snmp_result_status, "Storage status")) elif check == "system_power": helper.update_status(helper, self.check_system_power_status(snmp_result_status)) elif check == "global_system": helper.update_status(helper, normal_check("global", snmp_result_status, "Device status"))
python
def process_status(self, helper, session, check): """"process a single status""" snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check]) if check == "system_lcd": helper.update_status(helper, normal_check("global", snmp_result_status, "LCD status")) elif check == "global_storage": helper.update_status(helper, normal_check("global", snmp_result_status, "Storage status")) elif check == "system_power": helper.update_status(helper, self.check_system_power_status(snmp_result_status)) elif check == "global_system": helper.update_status(helper, normal_check("global", snmp_result_status, "Device status"))
[ "def", "process_status", "(", "self", ",", "helper", ",", "session", ",", "check", ")", ":", "snmp_result_status", "=", "helper", ".", "get_snmp_value", "(", "session", ",", "helper", ",", "DEVICE_GLOBAL_OIDS", "[", "'oid_'", "+", "check", "]", ")", "if", ...
process a single status
[ "process", "a", "single", "status" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L212-L224
train
38,516
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.process_states
def process_states(self, helper, session, check): """process status values from a table""" snmp_result_status = helper.walk_snmp_values(session, helper, DEVICE_STATES_OIDS["oid_" + check], check) snmp_result_names = helper.walk_snmp_values(session, helper, DEVICE_NAMES_OIDS["oid_" + check], check) for i, _result in enumerate(snmp_result_status): if check == "power_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Power unit")) elif check == "drive": helper.update_status( helper, self.check_drives(snmp_result_names[i], snmp_result_status[i])) elif check == "power_unit_redundancy": helper.update_status( helper, self.check_power_unit_redundancy(snmp_result_names[i], snmp_result_status[i])) elif check == "chassis_intrusion": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Chassis intrusion sensor")) elif check == "cooling_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Cooling unit"))
python
def process_states(self, helper, session, check): """process status values from a table""" snmp_result_status = helper.walk_snmp_values(session, helper, DEVICE_STATES_OIDS["oid_" + check], check) snmp_result_names = helper.walk_snmp_values(session, helper, DEVICE_NAMES_OIDS["oid_" + check], check) for i, _result in enumerate(snmp_result_status): if check == "power_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Power unit")) elif check == "drive": helper.update_status( helper, self.check_drives(snmp_result_names[i], snmp_result_status[i])) elif check == "power_unit_redundancy": helper.update_status( helper, self.check_power_unit_redundancy(snmp_result_names[i], snmp_result_status[i])) elif check == "chassis_intrusion": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Chassis intrusion sensor")) elif check == "cooling_unit": helper.update_status( helper, normal_check(snmp_result_names[i], snmp_result_status[i], "Cooling unit"))
[ "def", "process_states", "(", "self", ",", "helper", ",", "session", ",", "check", ")", ":", "snmp_result_status", "=", "helper", ".", "walk_snmp_values", "(", "session", ",", "helper", ",", "DEVICE_STATES_OIDS", "[", "\"oid_\"", "+", "check", "]", ",", "che...
process status values from a table
[ "process", "status", "values", "from", "a", "table" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L226-L257
train
38,517
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.process_temperature_sensors
def process_temperature_sensors(helper, session): """process the temperature sensors""" snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors") snmp_result_temp_sensor_states = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], "temperature sensors") snmp_result_temp_sensor_values = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], "temperature sensors") for i, _result in enumerate(snmp_result_temp_sensor_states): helper.update_status( helper, probe_check(snmp_result_temp_sensor_names[i], snmp_result_temp_sensor_states[i], "Temperature sensor")) if i < len(snmp_result_temp_sensor_values): helper.add_metric(label=snmp_result_temp_sensor_names[i] + " -Celsius-", value=float(snmp_result_temp_sensor_values[i]) / 10)
python
def process_temperature_sensors(helper, session): """process the temperature sensors""" snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors") snmp_result_temp_sensor_states = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], "temperature sensors") snmp_result_temp_sensor_values = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], "temperature sensors") for i, _result in enumerate(snmp_result_temp_sensor_states): helper.update_status( helper, probe_check(snmp_result_temp_sensor_names[i], snmp_result_temp_sensor_states[i], "Temperature sensor")) if i < len(snmp_result_temp_sensor_values): helper.add_metric(label=snmp_result_temp_sensor_names[i] + " -Celsius-", value=float(snmp_result_temp_sensor_values[i]) / 10)
[ "def", "process_temperature_sensors", "(", "helper", ",", "session", ")", ":", "snmp_result_temp_sensor_names", "=", "helper", ".", "walk_snmp_values", "(", "session", ",", "helper", ",", "DEVICE_TEMPERATURE_OIDS", "[", "'oid_temperature_probe_location'", "]", ",", "\"t...
process the temperature sensors
[ "process", "the", "temperature", "sensors" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L260-L279
train
38,518
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.check_drives
def check_drives(drivename, drivestatus): """ check the drive status """ return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format( drivename, DISK_STATES[int(drivestatus)]["result"])
python
def check_drives(drivename, drivestatus): """ check the drive status """ return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format( drivename, DISK_STATES[int(drivestatus)]["result"])
[ "def", "check_drives", "(", "drivename", ",", "drivestatus", ")", ":", "return", "DISK_STATES", "[", "int", "(", "drivestatus", ")", "]", "[", "\"icingastatus\"", "]", ",", "\"Drive '{}': {}\"", ".", "format", "(", "drivename", ",", "DISK_STATES", "[", "int", ...
check the drive status
[ "check", "the", "drive", "status" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L282-L285
train
38,519
rsmuc/health_monitoring_plugins
health_monitoring_plugins/idrac.py
Idrac.check_power_unit_redundancy
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data): """ check the status of the power units """ return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"], "Power unit '{}' redundancy: {}".format(power_unit_name_data, POWER_UNIT_REDUNDANCY_STATE[ int(power_unit_redundancy_data)] ["result"]))
python
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data): """ check the status of the power units """ return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"], "Power unit '{}' redundancy: {}".format(power_unit_name_data, POWER_UNIT_REDUNDANCY_STATE[ int(power_unit_redundancy_data)] ["result"]))
[ "def", "check_power_unit_redundancy", "(", "power_unit_name_data", ",", "power_unit_redundancy_data", ")", ":", "return", "(", "POWER_UNIT_REDUNDANCY_STATE", "[", "int", "(", "power_unit_redundancy_data", ")", "]", "[", "\"icingastatus\"", "]", ",", "\"Power unit '{}' redun...
check the status of the power units
[ "check", "the", "status", "of", "the", "power", "units" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/idrac.py#L294-L300
train
38,520
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_ilo4/check_snmp_ilo4.py
check_temperature_sensors
def check_temperature_sensors(): """ Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored """ # walk all temperature sensor values and thresholds env_temp = walk_data(sess, oid_env_temp, helper)[0] env_temp_thresh = walk_data(sess, oid_env_temp_thres, helper)[0] env_temp_zipped = zip(env_temp, env_temp_thresh) for x, data in enumerate(env_temp_zipped, 1): # skip the check if -99 or 0 is in the value or threshold, because these data we can not use if '-99' not in data and '0' not in data: #check if the value is over the treshold if int(data[0]) > int(data[1]): helper.add_summary('Temperature at sensor %d above threshold (%s / %s)' % (x, data[0], data[1])) helper.status(critical) # always add the sensor to the output helper.add_long_output('Temperature %d: %s Celsius (threshold: %s Celsius)' % (x, data[0], data[1])) # for the first sensor (envirnoment temperature, we add performance data) if x == 1: helper.add_metric("Environment Temperature", data[0], '', ":" + data[1], "", "", "Celsius")
python
def check_temperature_sensors(): """ Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored """ # walk all temperature sensor values and thresholds env_temp = walk_data(sess, oid_env_temp, helper)[0] env_temp_thresh = walk_data(sess, oid_env_temp_thres, helper)[0] env_temp_zipped = zip(env_temp, env_temp_thresh) for x, data in enumerate(env_temp_zipped, 1): # skip the check if -99 or 0 is in the value or threshold, because these data we can not use if '-99' not in data and '0' not in data: #check if the value is over the treshold if int(data[0]) > int(data[1]): helper.add_summary('Temperature at sensor %d above threshold (%s / %s)' % (x, data[0], data[1])) helper.status(critical) # always add the sensor to the output helper.add_long_output('Temperature %d: %s Celsius (threshold: %s Celsius)' % (x, data[0], data[1])) # for the first sensor (envirnoment temperature, we add performance data) if x == 1: helper.add_metric("Environment Temperature", data[0], '', ":" + data[1], "", "", "Celsius")
[ "def", "check_temperature_sensors", "(", ")", ":", "# walk all temperature sensor values and thresholds", "env_temp", "=", "walk_data", "(", "sess", ",", "oid_env_temp", ",", "helper", ")", "[", "0", "]", "env_temp_thresh", "=", "walk_data", "(", "sess", ",", "oid_e...
Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored
[ "Check", "all", "temperature", "sensors", "of", "the", "server", "All", "sensors", "with", "the", "value", "or", "threshold", "is", "-", "99", "or", "0", "are", "ignored" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_ilo4/check_snmp_ilo4.py#L245-L266
train
38,521
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_ilo4/check_snmp_ilo4.py
check_fan
def check_fan(input_fan): """ check the fans """ # get a list of all fans fan_data = walk_data(sess, oid_fan, helper)[0] fan_count = 0 summary_output = '' long_output = '' for x, fan in enumerate(fan_data, 1): fan = int(fan) if normal_state[fan] == 'ok': # if the fan is ok, we increase the fan_count varaible fan_count += 1 # we always want to the the status in the long output long_output += 'Fan %d: %s.\n' % (x, normal_state[fan]) # check we have the correct amount ok fans in OK state, otherwise set status to critical and print the fan in the summary if int(fan_count) != int(input_fan): summary_output += '%s fan(s) expected - %s fan(s) ok. ' % (input_fan, fan_count) helper.status(critical) return (summary_output, long_output)
python
def check_fan(input_fan): """ check the fans """ # get a list of all fans fan_data = walk_data(sess, oid_fan, helper)[0] fan_count = 0 summary_output = '' long_output = '' for x, fan in enumerate(fan_data, 1): fan = int(fan) if normal_state[fan] == 'ok': # if the fan is ok, we increase the fan_count varaible fan_count += 1 # we always want to the the status in the long output long_output += 'Fan %d: %s.\n' % (x, normal_state[fan]) # check we have the correct amount ok fans in OK state, otherwise set status to critical and print the fan in the summary if int(fan_count) != int(input_fan): summary_output += '%s fan(s) expected - %s fan(s) ok. ' % (input_fan, fan_count) helper.status(critical) return (summary_output, long_output)
[ "def", "check_fan", "(", "input_fan", ")", ":", "# get a list of all fans ", "fan_data", "=", "walk_data", "(", "sess", ",", "oid_fan", ",", "helper", ")", "[", "0", "]", "fan_count", "=", "0", "summary_output", "=", "''", "long_output", "=", "''", "for...
check the fans
[ "check", "the", "fans" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_ilo4/check_snmp_ilo4.py#L371-L394
train
38,522
rsmuc/health_monitoring_plugins
health_monitoring_plugins/trustedfilter.py
TrustedFilter.get_snmp_from_host1
def get_snmp_from_host1(self): """ Get SNMP values from 1st host. """ response = self.snmp1.get_oids(ps1_oid, ps2_oid, fan1_oid, fan2_oid, bat_oid, temp_oid, activity_oid, logfill_oid) self.ps1_value = states[int(response[0])] self.ps2_value = states[int(response[1])] self.fan1_value = states[int(response[2])] self.fan2_value = states[int(response[3])] self.bat_value = states[int(response[4])] self.temp_value = states[int(response[5])] self.activity_value1 = activity[int(response[6])] self.logfill_value = str(response[7])
python
def get_snmp_from_host1(self): """ Get SNMP values from 1st host. """ response = self.snmp1.get_oids(ps1_oid, ps2_oid, fan1_oid, fan2_oid, bat_oid, temp_oid, activity_oid, logfill_oid) self.ps1_value = states[int(response[0])] self.ps2_value = states[int(response[1])] self.fan1_value = states[int(response[2])] self.fan2_value = states[int(response[3])] self.bat_value = states[int(response[4])] self.temp_value = states[int(response[5])] self.activity_value1 = activity[int(response[6])] self.logfill_value = str(response[7])
[ "def", "get_snmp_from_host1", "(", "self", ")", ":", "response", "=", "self", ".", "snmp1", ".", "get_oids", "(", "ps1_oid", ",", "ps2_oid", ",", "fan1_oid", ",", "fan2_oid", ",", "bat_oid", ",", "temp_oid", ",", "activity_oid", ",", "logfill_oid", ")", "s...
Get SNMP values from 1st host.
[ "Get", "SNMP", "values", "from", "1st", "host", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/trustedfilter.py#L37-L49
train
38,523
rsmuc/health_monitoring_plugins
health_monitoring_plugins/trustedfilter.py
TrustedFilter.get_snmp_from_host2
def get_snmp_from_host2(self): """ Get SNMP values from 2nd host. """ if not self.snmp2: self.activity_value2 = None else: response = self.snmp2.get_oids(activity_oid) self.activity_value2 = activity[int(response[0])]
python
def get_snmp_from_host2(self): """ Get SNMP values from 2nd host. """ if not self.snmp2: self.activity_value2 = None else: response = self.snmp2.get_oids(activity_oid) self.activity_value2 = activity[int(response[0])]
[ "def", "get_snmp_from_host2", "(", "self", ")", ":", "if", "not", "self", ".", "snmp2", ":", "self", ".", "activity_value2", "=", "None", "else", ":", "response", "=", "self", ".", "snmp2", ".", "get_oids", "(", "activity_oid", ")", "self", ".", "activit...
Get SNMP values from 2nd host.
[ "Get", "SNMP", "values", "from", "2nd", "host", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/trustedfilter.py#L51-L59
train
38,524
rsmuc/health_monitoring_plugins
health_monitoring_plugins/trustedfilter.py
TrustedFilter.check
def check(self): """ Evaluate health status from device parameters. """ try: self.get_snmp_from_host1() self.get_snmp_from_host2() except (health_monitoring_plugins.SnmpException, TypeError, KeyError): self.helper.status(unknown) self.helper.add_summary("SNMP response incomplete or invalid") return self.helper.add_summary("Filter Status") self.helper.add_long_output("Power Supply 1: %s" % self.ps1_value) if self.ps1_value != "ok": self.helper.status(critical) self.helper.add_summary("Power Supply 1: %s" % self.ps1_value) self.helper.add_long_output("Power Supply 2: %s" % self.ps2_value) if self.ps2_value != "ok": self.helper.status(critical) self.helper.add_summary("Power Supply 2: %s" % self.ps2_value) self.helper.add_long_output("Fan 1: %s" % self.fan1_value) if self.fan1_value != "ok": self.helper.status(critical) self.helper.add_summary("Fan 1: %s" % self.fan1_value) self.helper.add_long_output("Fan 2: %s" % self.fan2_value) if self.fan2_value != "ok": self.helper.status(critical) self.helper.add_summary("Fan 2: %s" % self.fan2_value) self.helper.add_long_output("Battery: %s" % self.bat_value) if self.bat_value != "ok": self.helper.status(critical) self.helper.add_summary("Battery: %s" % self.bat_value) self.helper.add_long_output("Temperature: %s" % self.temp_value) if self.temp_value != "ok": self.helper.status(critical) self.helper.add_summary("Temperature: %s" % self.temp_value) self.helper.add_metric(label='logfill',value=self.logfill_value, uom="%%") self.helper.add_long_output("Fill Level internal log: %s%%" % self.logfill_value) self.helper.add_long_output("Activity State: %s" % self.activity_value1) if self.activity_value1 == "error": self.helper.status(critical) self.helper.add_summary("Activity State: %s" % self.activity_value1) if self.activity_value2: self.helper.add_long_output("Activity State 2: %s" % self.activity_value2) if self.activity_value1 == "active" and self.activity_value2 == "active": self.helper.status(critical) self.helper.add_summary("Filter 1 and Filter 2 active!") if self.activity_value1 == "standby" and self.activity_value2 == "standby": self.helper.status(critical) self.helper.add_summary("Filter 1 and Filter 2 standby!") self.helper.check_all_metrics()
python
def check(self): """ Evaluate health status from device parameters. """ try: self.get_snmp_from_host1() self.get_snmp_from_host2() except (health_monitoring_plugins.SnmpException, TypeError, KeyError): self.helper.status(unknown) self.helper.add_summary("SNMP response incomplete or invalid") return self.helper.add_summary("Filter Status") self.helper.add_long_output("Power Supply 1: %s" % self.ps1_value) if self.ps1_value != "ok": self.helper.status(critical) self.helper.add_summary("Power Supply 1: %s" % self.ps1_value) self.helper.add_long_output("Power Supply 2: %s" % self.ps2_value) if self.ps2_value != "ok": self.helper.status(critical) self.helper.add_summary("Power Supply 2: %s" % self.ps2_value) self.helper.add_long_output("Fan 1: %s" % self.fan1_value) if self.fan1_value != "ok": self.helper.status(critical) self.helper.add_summary("Fan 1: %s" % self.fan1_value) self.helper.add_long_output("Fan 2: %s" % self.fan2_value) if self.fan2_value != "ok": self.helper.status(critical) self.helper.add_summary("Fan 2: %s" % self.fan2_value) self.helper.add_long_output("Battery: %s" % self.bat_value) if self.bat_value != "ok": self.helper.status(critical) self.helper.add_summary("Battery: %s" % self.bat_value) self.helper.add_long_output("Temperature: %s" % self.temp_value) if self.temp_value != "ok": self.helper.status(critical) self.helper.add_summary("Temperature: %s" % self.temp_value) self.helper.add_metric(label='logfill',value=self.logfill_value, uom="%%") self.helper.add_long_output("Fill Level internal log: %s%%" % self.logfill_value) self.helper.add_long_output("Activity State: %s" % self.activity_value1) if self.activity_value1 == "error": self.helper.status(critical) self.helper.add_summary("Activity State: %s" % self.activity_value1) if self.activity_value2: self.helper.add_long_output("Activity State 2: %s" % self.activity_value2) if self.activity_value1 == "active" and self.activity_value2 == "active": self.helper.status(critical) self.helper.add_summary("Filter 1 and Filter 2 active!") if self.activity_value1 == "standby" and self.activity_value2 == "standby": self.helper.status(critical) self.helper.add_summary("Filter 1 and Filter 2 standby!") self.helper.check_all_metrics()
[ "def", "check", "(", "self", ")", ":", "try", ":", "self", ".", "get_snmp_from_host1", "(", ")", "self", ".", "get_snmp_from_host2", "(", ")", "except", "(", "health_monitoring_plugins", ".", "SnmpException", ",", "TypeError", ",", "KeyError", ")", ":", "sel...
Evaluate health status from device parameters.
[ "Evaluate", "health", "status", "from", "device", "parameters", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/trustedfilter.py#L61-L122
train
38,525
rsmuc/health_monitoring_plugins
health_monitoring_plugins/__init__.py
HelperExtension.update_status
def update_status(self, helper, status): """ update the helper """ if status: self.status(status[0]) # if the status is ok, add it to the long output if status[0] == 0: self.add_long_output(status[1]) # if the status is not ok, add it to the summary else: self.add_summary(status[1])
python
def update_status(self, helper, status): """ update the helper """ if status: self.status(status[0]) # if the status is ok, add it to the long output if status[0] == 0: self.add_long_output(status[1]) # if the status is not ok, add it to the summary else: self.add_summary(status[1])
[ "def", "update_status", "(", "self", ",", "helper", ",", "status", ")", ":", "if", "status", ":", "self", ".", "status", "(", "status", "[", "0", "]", ")", "# if the status is ok, add it to the long output", "if", "status", "[", "0", "]", "==", "0", ":", ...
update the helper
[ "update", "the", "helper" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/__init__.py#L23-L33
train
38,526
rsmuc/health_monitoring_plugins
health_monitoring_plugins/__init__.py
SnmpSession.walk_oid
def walk_oid(self, oid): """Get a list of SNMP varbinds in response to a walk for oid. Each varbind in response list has a tag, iid, val and type attribute.""" var = netsnmp.Varbind(oid) varlist = netsnmp.VarList(var) data = self.walk(varlist) if len(data) == 0: raise SnmpException("SNMP walk response incomplete") return varlist
python
def walk_oid(self, oid): """Get a list of SNMP varbinds in response to a walk for oid. Each varbind in response list has a tag, iid, val and type attribute.""" var = netsnmp.Varbind(oid) varlist = netsnmp.VarList(var) data = self.walk(varlist) if len(data) == 0: raise SnmpException("SNMP walk response incomplete") return varlist
[ "def", "walk_oid", "(", "self", ",", "oid", ")", ":", "var", "=", "netsnmp", ".", "Varbind", "(", "oid", ")", "varlist", "=", "netsnmp", ".", "VarList", "(", "var", ")", "data", "=", "self", ".", "walk", "(", "varlist", ")", "if", "len", "(", "da...
Get a list of SNMP varbinds in response to a walk for oid. Each varbind in response list has a tag, iid, val and type attribute.
[ "Get", "a", "list", "of", "SNMP", "varbinds", "in", "response", "to", "a", "walk", "for", "oid", ".", "Each", "varbind", "in", "response", "list", "has", "a", "tag", "iid", "val", "and", "type", "attribute", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/__init__.py#L121-L130
train
38,527
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_large_storage/check_snmp_large_storage.py
run_scan
def run_scan(): """ show all available partitions """ all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0] print "All available disks at: " + host for disk in all_disks: print "Disk: \t'" + disk + "'" quit()
python
def run_scan(): """ show all available partitions """ all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0] print "All available disks at: " + host for disk in all_disks: print "Disk: \t'" + disk + "'" quit()
[ "def", "run_scan", "(", ")", ":", "all_disks", "=", "walk_data", "(", "sess", ",", "oid_hrStorageDescr", ",", "helper", ")", "[", "0", "]", "print", "\"All available disks at: \"", "+", "host", "for", "disk", "in", "all_disks", ":", "print", "\"Disk: \\t'\"", ...
show all available partitions
[ "show", "all", "available", "partitions" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_large_storage/check_snmp_large_storage.py#L104-L113
train
38,528
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_large_storage/check_snmp_large_storage.py
check_partition
def check_partition(): """ check the defined partition """ all_index = walk_data(sess, oid_hrStorageIndex, helper)[0] all_descriptions = walk_data(sess, oid_hrStorageDescr, helper)[0] # we need the sucess flag for the error handling (partition found or not found) sucess = False # here we zip all index and descriptions to have a list like # [('Physical memory', '1'), ('Virtual memory', '3'), ('/', '32'), ('/proc/xen', '33')] zipped = zip(all_index, all_descriptions) for partition in zipped: index = partition[0] description = partition[1] if partition_found(disk, description): # we found the partition sucess = True # receive all values we need unit = float(get_data(sess, oid_hrStorageAllocationUnits + "." + index, helper)) size = float(get_data(sess, oid_hrStorageSize + "." + index, helper)) used = float(get_data(sess, oid_hrStorageUsed + "." + index, helper)) if size == 0 or used == 0: # if the host return "0" as used or size, then we have a problem with the calculation (devision by zero) helper.exit(summary="Received value 0 as StorageSize or StorageUsed: calculation error", exit_code=unknown, perfdata='') # calculate the real size (size*unit) and convert the results to the target unit the user wants to see used_result = convert_to_XX(calculate_real_size(used), unit, targetunit) size_result = convert_to_XX(calculate_real_size(size), unit, targetunit) # calculation of the used percentage percent_used = used_result / size_result * 100 # we need a string and want only two decimals used_string = str(float("{0:.2f}".format(used_result))) size_string = str(float("{0:.2f}".format(size_result))) percent_string = str(float("{0:.2f}".format(percent_used))) if percent_used < 0 or percent_used > 100: # just a validation that percent_used is not smaller then 0% or lager then 100% helper.exit(summary="Calculation error - second counter overrun?", exit_code=unknown, perfdata='') # show the summary helper.add_summary("%s%% used (%s%s of %s%s) at '%s'" % (percent_string, used_string, targetunit, size_string, targetunit, description)) # add the metric in percent. helper.add_metric(label='percent used',value=percent_string, min="0", max="100", uom="%") else: if not sucess: # if the partition was not found in the data output, we return an error helper.exit(summary="Partition '%s' not found" % disk, exit_code=unknown, perfdata='')
python
def check_partition(): """ check the defined partition """ all_index = walk_data(sess, oid_hrStorageIndex, helper)[0] all_descriptions = walk_data(sess, oid_hrStorageDescr, helper)[0] # we need the sucess flag for the error handling (partition found or not found) sucess = False # here we zip all index and descriptions to have a list like # [('Physical memory', '1'), ('Virtual memory', '3'), ('/', '32'), ('/proc/xen', '33')] zipped = zip(all_index, all_descriptions) for partition in zipped: index = partition[0] description = partition[1] if partition_found(disk, description): # we found the partition sucess = True # receive all values we need unit = float(get_data(sess, oid_hrStorageAllocationUnits + "." + index, helper)) size = float(get_data(sess, oid_hrStorageSize + "." + index, helper)) used = float(get_data(sess, oid_hrStorageUsed + "." + index, helper)) if size == 0 or used == 0: # if the host return "0" as used or size, then we have a problem with the calculation (devision by zero) helper.exit(summary="Received value 0 as StorageSize or StorageUsed: calculation error", exit_code=unknown, perfdata='') # calculate the real size (size*unit) and convert the results to the target unit the user wants to see used_result = convert_to_XX(calculate_real_size(used), unit, targetunit) size_result = convert_to_XX(calculate_real_size(size), unit, targetunit) # calculation of the used percentage percent_used = used_result / size_result * 100 # we need a string and want only two decimals used_string = str(float("{0:.2f}".format(used_result))) size_string = str(float("{0:.2f}".format(size_result))) percent_string = str(float("{0:.2f}".format(percent_used))) if percent_used < 0 or percent_used > 100: # just a validation that percent_used is not smaller then 0% or lager then 100% helper.exit(summary="Calculation error - second counter overrun?", exit_code=unknown, perfdata='') # show the summary helper.add_summary("%s%% used (%s%s of %s%s) at '%s'" % (percent_string, used_string, targetunit, size_string, targetunit, description)) # add the metric in percent. helper.add_metric(label='percent used',value=percent_string, min="0", max="100", uom="%") else: if not sucess: # if the partition was not found in the data output, we return an error helper.exit(summary="Partition '%s' not found" % disk, exit_code=unknown, perfdata='')
[ "def", "check_partition", "(", ")", ":", "all_index", "=", "walk_data", "(", "sess", ",", "oid_hrStorageIndex", ",", "helper", ")", "[", "0", "]", "all_descriptions", "=", "walk_data", "(", "sess", ",", "oid_hrStorageDescr", ",", "helper", ")", "[", "0", "...
check the defined partition
[ "check", "the", "defined", "partition" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_large_storage/check_snmp_large_storage.py#L135-L190
train
38,529
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_procurve/check_snmp_procurve.py
check_sensors
def check_sensors(): """ collect and check all available sensors """ all_sensors = walk_data(sess, oid_description, helper)[0] all_status = walk_data(sess, oid_status, helper)[0] # here we zip all index and descriptions to have a list like # [('Fan Sensor', '2'), ('Power Supply Sensor', '4')] # we are doomed if the lists do not have the same length ... but that should never happen ... hopefully zipped = zip(all_sensors, all_status) for sensor in zipped: description = sensor[0] status = sensor[1] # translate the value to human readable try: status_string = senor_status_table[status] except KeyError: # if we receive an invalid value, we don't want to crash... helper.exit(summary="received an undefined value from device: " + status, exit_code=unknown, perfdata='') # for each sensor the summary is added like: Fan Sensor: good helper.add_summary("%s: %s" % (description, status_string)) # set the status if status == "2": helper.status(critical) if status == "3": helper.status(warning)
python
def check_sensors(): """ collect and check all available sensors """ all_sensors = walk_data(sess, oid_description, helper)[0] all_status = walk_data(sess, oid_status, helper)[0] # here we zip all index and descriptions to have a list like # [('Fan Sensor', '2'), ('Power Supply Sensor', '4')] # we are doomed if the lists do not have the same length ... but that should never happen ... hopefully zipped = zip(all_sensors, all_status) for sensor in zipped: description = sensor[0] status = sensor[1] # translate the value to human readable try: status_string = senor_status_table[status] except KeyError: # if we receive an invalid value, we don't want to crash... helper.exit(summary="received an undefined value from device: " + status, exit_code=unknown, perfdata='') # for each sensor the summary is added like: Fan Sensor: good helper.add_summary("%s: %s" % (description, status_string)) # set the status if status == "2": helper.status(critical) if status == "3": helper.status(warning)
[ "def", "check_sensors", "(", ")", ":", "all_sensors", "=", "walk_data", "(", "sess", ",", "oid_description", ",", "helper", ")", "[", "0", "]", "all_status", "=", "walk_data", "(", "sess", ",", "oid_status", ",", "helper", ")", "[", "0", "]", "# here we ...
collect and check all available sensors
[ "collect", "and", "check", "all", "available", "sensors" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_procurve/check_snmp_procurve.py#L59-L89
train
38,530
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_apc_ups/check_snmp_apc_ups.py
check_runtime_remaining
def check_runtime_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second """ a_minute_value = calc_minutes_from_ticks(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_minute_value, warn=the_helper.options.warning, crit=the_helper.options.critical, uom="Minutes") the_helper.check_all_metrics() the_helper.set_summary("Remaining runtime on battery is {} minutes".format(a_minute_value))
python
def check_runtime_remaining(the_session, the_helper, the_snmp_value): """ OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second """ a_minute_value = calc_minutes_from_ticks(the_snmp_value) the_helper.add_metric( label=the_helper.options.type, value=a_minute_value, warn=the_helper.options.warning, crit=the_helper.options.critical, uom="Minutes") the_helper.check_all_metrics() the_helper.set_summary("Remaining runtime on battery is {} minutes".format(a_minute_value))
[ "def", "check_runtime_remaining", "(", "the_session", ",", "the_helper", ",", "the_snmp_value", ")", ":", "a_minute_value", "=", "calc_minutes_from_ticks", "(", "the_snmp_value", ")", "the_helper", ".", "add_metric", "(", "label", "=", "the_helper", ".", "options", ...
OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0 MIB excerpt The UPS battery run time remaining before battery exhaustion. SNMP value is in TimeTicks aka hundredths of a second
[ "OID", ".", "1", ".", "3", ".", "6", ".", "1", ".", "4", ".", "1", ".", "318", ".", "1", ".", "1", ".", "1", ".", "2", ".", "2", ".", "3", ".", "0", "MIB", "excerpt", "The", "UPS", "battery", "run", "time", "remaining", "before", "battery",...
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_apc_ups/check_snmp_apc_ups.py#L160-L176
train
38,531
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_port/check_snmp_port.py
check_typ
def check_typ(helper, typ): """ check if typ parameter is TCP or UDP """ if typ != "tcp" and typ != "udp": helper.exit(summary="Type (-t) must be udp or tcp.", exit_code=unknown, perfdata='')
python
def check_typ(helper, typ): """ check if typ parameter is TCP or UDP """ if typ != "tcp" and typ != "udp": helper.exit(summary="Type (-t) must be udp or tcp.", exit_code=unknown, perfdata='')
[ "def", "check_typ", "(", "helper", ",", "typ", ")", ":", "if", "typ", "!=", "\"tcp\"", "and", "typ", "!=", "\"udp\"", ":", "helper", ".", "exit", "(", "summary", "=", "\"Type (-t) must be udp or tcp.\"", ",", "exit_code", "=", "unknown", ",", "perfdata", "...
check if typ parameter is TCP or UDP
[ "check", "if", "typ", "parameter", "is", "TCP", "or", "UDP" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_port/check_snmp_port.py#L56-L61
train
38,532
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_port/check_snmp_port.py
check_port
def check_port(helper, port): """ check if the port parameter is really a port or "scan" """ try: int(port) except ValueError: helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
python
def check_port(helper, port): """ check if the port parameter is really a port or "scan" """ try: int(port) except ValueError: helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
[ "def", "check_port", "(", "helper", ",", "port", ")", ":", "try", ":", "int", "(", "port", ")", "except", "ValueError", ":", "helper", ".", "exit", "(", "summary", "=", "\"Port (-p) must be a integer value.\"", ",", "exit_code", "=", "unknown", ",", "perfdat...
check if the port parameter is really a port or "scan"
[ "check", "if", "the", "port", "parameter", "is", "really", "a", "port", "or", "scan" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_port/check_snmp_port.py#L63-L70
train
38,533
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_port/check_snmp_port.py
check_udp
def check_udp(helper, host, port, session): """ the check logic for UDP ports """ open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated) # here we show all open UDP ports if scan: print "All open UDP ports at host " + host for port in open_ports: print "UDP: \t" + port quit() if port in open_ports: udp_status = "OPEN" else: udp_status = "CLOSED" helper.status(critical) return ("Current status for UDP port " + port + " is: " + udp_status)
python
def check_udp(helper, host, port, session): """ the check logic for UDP ports """ open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated) # here we show all open UDP ports if scan: print "All open UDP ports at host " + host for port in open_ports: print "UDP: \t" + port quit() if port in open_ports: udp_status = "OPEN" else: udp_status = "CLOSED" helper.status(critical) return ("Current status for UDP port " + port + " is: " + udp_status)
[ "def", "check_udp", "(", "helper", ",", "host", ",", "port", ",", "session", ")", ":", "open_ports", "=", "walk_data", "(", "session", ",", "'.1.3.6.1.2.1.7.5.1.2'", ",", "helper", ")", "[", "0", "]", "# the udpLocaLPort from UDP-MIB.mib (deprecated)", "# here we ...
the check logic for UDP ports
[ "the", "check", "logic", "for", "UDP", "ports" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_port/check_snmp_port.py#L72-L90
train
38,534
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_port/check_snmp_port.py
check_tcp
def check_tcp(helper, host, port, warning_param, critical_param, session): """ the check logic for check TCP ports """ # from tcpConnState from TCP-MIB tcp_translate = { "1" : "closed", "2" : "listen", "3" : "synSent", "4" : "synReceived", "5" : "established", "6" : "finWait1", "7" : "finWait2", "8" : "closeWait", "9" : "lastAck", "10": "closing", "11": "timeWait", "12": "deleteTCB" } # collect all open local ports open_ports = walk_data(session, '.1.3.6.1.2.1.6.13.1.3', helper)[0] #tcpConnLocalPort from TCP-MIB (deprecated) # collect all status information about the open ports port_status = walk_data(session, '.1.3.6.1.2.1.6.13.1.1', helper)[0] #tcpConnState from TCP-MIB (deprecated) # make a dict out of the two lists port_and_status = dict(zip(open_ports, port_status)) # here we show all open TCP ports and it's status if scan: print "All open TCP ports: " + host for port in open_ports: tcp_status = port_and_status[port] tcp_status = tcp_translate[tcp_status] print "TCP: \t" + port + "\t Status: \t" + tcp_status quit() #here we have the real check logic for TCP ports if port in open_ports: # if the port is available in the list of open_ports, then extract the status tcp_status = port_and_status[port] # translate the status from the integer value to a human readable string tcp_status = tcp_translate[tcp_status] # now let's set the status according to the warning / critical "threshold" parameter if tcp_status in warning_param: helper.status(warning) elif tcp_status in critical_param: helper.status(critical) else: helper.status(ok) else: # if there is no value in the list => the port is closed for sure tcp_status = "CLOSED" helper.status(critical) return ("Current status for TCP port " + port + " is: " + tcp_status)
python
def check_tcp(helper, host, port, warning_param, critical_param, session): """ the check logic for check TCP ports """ # from tcpConnState from TCP-MIB tcp_translate = { "1" : "closed", "2" : "listen", "3" : "synSent", "4" : "synReceived", "5" : "established", "6" : "finWait1", "7" : "finWait2", "8" : "closeWait", "9" : "lastAck", "10": "closing", "11": "timeWait", "12": "deleteTCB" } # collect all open local ports open_ports = walk_data(session, '.1.3.6.1.2.1.6.13.1.3', helper)[0] #tcpConnLocalPort from TCP-MIB (deprecated) # collect all status information about the open ports port_status = walk_data(session, '.1.3.6.1.2.1.6.13.1.1', helper)[0] #tcpConnState from TCP-MIB (deprecated) # make a dict out of the two lists port_and_status = dict(zip(open_ports, port_status)) # here we show all open TCP ports and it's status if scan: print "All open TCP ports: " + host for port in open_ports: tcp_status = port_and_status[port] tcp_status = tcp_translate[tcp_status] print "TCP: \t" + port + "\t Status: \t" + tcp_status quit() #here we have the real check logic for TCP ports if port in open_ports: # if the port is available in the list of open_ports, then extract the status tcp_status = port_and_status[port] # translate the status from the integer value to a human readable string tcp_status = tcp_translate[tcp_status] # now let's set the status according to the warning / critical "threshold" parameter if tcp_status in warning_param: helper.status(warning) elif tcp_status in critical_param: helper.status(critical) else: helper.status(ok) else: # if there is no value in the list => the port is closed for sure tcp_status = "CLOSED" helper.status(critical) return ("Current status for TCP port " + port + " is: " + tcp_status)
[ "def", "check_tcp", "(", "helper", ",", "host", ",", "port", ",", "warning_param", ",", "critical_param", ",", "session", ")", ":", "# from tcpConnState from TCP-MIB", "tcp_translate", "=", "{", "\"1\"", ":", "\"closed\"", ",", "\"2\"", ":", "\"listen\"", ",", ...
the check logic for check TCP ports
[ "the", "check", "logic", "for", "check", "TCP", "ports" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_port/check_snmp_port.py#L92-L150
train
38,535
niligulmohar/python-symmetric-jsonrpc
symmetricjsonrpc/json.py
to_json
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
python
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
[ "def", "to_json", "(", "obj", ")", ":", "i", "=", "StringIO", ".", "StringIO", "(", ")", "w", "=", "Writer", "(", "i", ",", "encoding", "=", "'UTF-8'", ")", "w", ".", "write_value", "(", "obj", ")", "return", "i", ".", "getvalue", "(", ")" ]
Return a json string representing the python object obj.
[ "Return", "a", "json", "string", "representing", "the", "python", "object", "obj", "." ]
f0730bef5c19a1631d58927c0f13d29f16cd1330
https://github.com/niligulmohar/python-symmetric-jsonrpc/blob/f0730bef5c19a1631d58927c0f13d29f16cd1330/symmetricjsonrpc/json.py#L37-L42
train
38,536
rsmuc/health_monitoring_plugins
health_monitoring_plugins/newtecmodem.py
NewtecModem.get_data
def get_data(self): "Get SNMP values from host" alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids)) return ( response[0:len(alarm_oids)], response[len(alarm_oids):] )
python
def get_data(self): "Get SNMP values from host" alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids)) return ( response[0:len(alarm_oids)], response[len(alarm_oids):] )
[ "def", "get_data", "(", "self", ")", ":", "alarm_oids", "=", "[", "netsnmp", ".", "Varbind", "(", "alarms", "[", "alarm_id", "]", "[", "'oid'", "]", ")", "for", "alarm_id", "in", "self", ".", "models", "[", "self", ".", "modem_type", "]", "[", "'alar...
Get SNMP values from host
[ "Get", "SNMP", "values", "from", "host" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/newtecmodem.py#L64-L72
train
38,537
rsmuc/health_monitoring_plugins
health_monitoring_plugins/check_snmp_service/check_snmp_service.py
convert_in_oid
def convert_in_oid(service_name): """ calculate the correct OID for the service name """ s = service_name # convert the service_name to ascci service_ascii = [ord(c) for c in s] # we need the length of the service name length = str(len(s)) # make the oid oid = base_oid + "." + length + "." + ".".join(str(x) for x in service_ascii) return oid
python
def convert_in_oid(service_name): """ calculate the correct OID for the service name """ s = service_name # convert the service_name to ascci service_ascii = [ord(c) for c in s] # we need the length of the service name length = str(len(s)) # make the oid oid = base_oid + "." + length + "." + ".".join(str(x) for x in service_ascii) return oid
[ "def", "convert_in_oid", "(", "service_name", ")", ":", "s", "=", "service_name", "# convert the service_name to ascci", "service_ascii", "=", "[", "ord", "(", "c", ")", "for", "c", "in", "s", "]", "# we need the length of the service name", "length", "=", "str", ...
calculate the correct OID for the service name
[ "calculate", "the", "correct", "OID", "for", "the", "service", "name" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_service/check_snmp_service.py#L55-L66
train
38,538
rsmuc/health_monitoring_plugins
health_monitoring_plugins/microwavemodem.py
MicrowaveModem.get_data
def get_data(self): "Return one SNMP response list for all status OIDs, and one list for all metric OIDs." alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids)) return ( response[0:len(alarm_oids)], response[len(alarm_oids):] )
python
def get_data(self): "Return one SNMP response list for all status OIDs, and one list for all metric OIDs." alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']] metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']] response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids)) return ( response[0:len(alarm_oids)], response[len(alarm_oids):] )
[ "def", "get_data", "(", "self", ")", ":", "alarm_oids", "=", "[", "netsnmp", ".", "Varbind", "(", "status_mib", "[", "alarm_id", "]", "[", "'oid'", "]", ")", "for", "alarm_id", "in", "self", ".", "models", "[", "self", ".", "modem_type", "]", "[", "'...
Return one SNMP response list for all status OIDs, and one list for all metric OIDs.
[ "Return", "one", "SNMP", "response", "list", "for", "all", "status", "OIDs", "and", "one", "list", "for", "all", "metric", "OIDs", "." ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/microwavemodem.py#L97-L105
train
38,539
rsmuc/health_monitoring_plugins
health_monitoring_plugins/raritan.py
Raritan.check_inlet
def check_inlet(self, helper): """ check the Inlets of Raritan PDUs """ # walk the data try: inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value']) inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit']) inlet_digits = self.sess.walk_oid(self.oids['oid_inlet_digits']) inlet_states = self.sess.walk_oid(self.oids['oid_inlet_state']) inlet_warning_uppers = self.sess.walk_oid(self.oids['oid_inlet_warning_upper']) inlet_critical_uppers = self.sess.walk_oid(self.oids['oid_inlet_critical_upper']) inlet_critical_lowers = self.sess.walk_oid(self.oids['oid_inlet_critical_lower']) inlet_warning_lowers = self.sess.walk_oid(self.oids['oid_inlet_warning_lower']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') # just print the summary, that the inlet sensors are checked helper.add_summary("Inlet") # all list must have the same length, if not something went wrong. that makes it easier and we need less loops # translate the data in human readable units with help of the dicts for x in range(len(inlet_values)): inlet_unit = units[int(inlet_units[x].val)] inlet_digit = inlet_digits[x].val inlet_state = states[int(inlet_states[x].val)] inlet_value = real_value(inlet_values[x].val, inlet_digit) inlet_warning_upper = real_value(inlet_warning_uppers[x].val, inlet_digit) inlet_critical_upper = real_value(inlet_critical_uppers[x].val, inlet_digit) inlet_warning_lower = real_value(inlet_warning_lowers[x].val, inlet_digit) inlet_critical_lower = real_value(inlet_critical_lowers[x].val, inlet_digit) if inlet_state != "normal": # we don't want to use the thresholds. we rely on the state value of the device helper.add_summary("%s %s is %s" % (inlet_value, inlet_unit, inlet_state)) helper.status(critical) # we always want to see the values in the long output and in the perf data helper.add_summary("%s %s" % (inlet_value, inlet_unit)) helper.add_long_output("%s %s: %s" % (inlet_value, inlet_unit, inlet_state)) helper.add_metric("Sensor " + str(x) + " -%s-" % inlet_unit, inlet_value, inlet_warning_lower +\ ":" + inlet_warning_upper, inlet_critical_lower + ":" +\ inlet_critical_upper, "", "", "")
python
def check_inlet(self, helper): """ check the Inlets of Raritan PDUs """ # walk the data try: inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value']) inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit']) inlet_digits = self.sess.walk_oid(self.oids['oid_inlet_digits']) inlet_states = self.sess.walk_oid(self.oids['oid_inlet_state']) inlet_warning_uppers = self.sess.walk_oid(self.oids['oid_inlet_warning_upper']) inlet_critical_uppers = self.sess.walk_oid(self.oids['oid_inlet_critical_upper']) inlet_critical_lowers = self.sess.walk_oid(self.oids['oid_inlet_critical_lower']) inlet_warning_lowers = self.sess.walk_oid(self.oids['oid_inlet_warning_lower']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') # just print the summary, that the inlet sensors are checked helper.add_summary("Inlet") # all list must have the same length, if not something went wrong. that makes it easier and we need less loops # translate the data in human readable units with help of the dicts for x in range(len(inlet_values)): inlet_unit = units[int(inlet_units[x].val)] inlet_digit = inlet_digits[x].val inlet_state = states[int(inlet_states[x].val)] inlet_value = real_value(inlet_values[x].val, inlet_digit) inlet_warning_upper = real_value(inlet_warning_uppers[x].val, inlet_digit) inlet_critical_upper = real_value(inlet_critical_uppers[x].val, inlet_digit) inlet_warning_lower = real_value(inlet_warning_lowers[x].val, inlet_digit) inlet_critical_lower = real_value(inlet_critical_lowers[x].val, inlet_digit) if inlet_state != "normal": # we don't want to use the thresholds. we rely on the state value of the device helper.add_summary("%s %s is %s" % (inlet_value, inlet_unit, inlet_state)) helper.status(critical) # we always want to see the values in the long output and in the perf data helper.add_summary("%s %s" % (inlet_value, inlet_unit)) helper.add_long_output("%s %s: %s" % (inlet_value, inlet_unit, inlet_state)) helper.add_metric("Sensor " + str(x) + " -%s-" % inlet_unit, inlet_value, inlet_warning_lower +\ ":" + inlet_warning_upper, inlet_critical_lower + ":" +\ inlet_critical_upper, "", "", "")
[ "def", "check_inlet", "(", "self", ",", "helper", ")", ":", "# walk the data", "try", ":", "inlet_values", "=", "self", ".", "sess", ".", "walk_oid", "(", "self", ".", "oids", "[", "'oid_inlet_value'", "]", ")", "inlet_units", "=", "self", ".", "sess", "...
check the Inlets of Raritan PDUs
[ "check", "the", "Inlets", "of", "Raritan", "PDUs" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/raritan.py#L112-L155
train
38,540
rsmuc/health_monitoring_plugins
health_monitoring_plugins/raritan.py
Raritan.check_outlet
def check_outlet(self, helper): """ check the status of the specified outlet """ try: outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') outlet_real_state = states[int(outlet_state)] # here we check if the outlet is powered on if outlet_real_state != "on": helper.status(critical) # print the status helper.add_summary("Outlet %s - '%s' is: %s" % (self.number, outlet_name, outlet_real_state.upper()))
python
def check_outlet(self, helper): """ check the status of the specified outlet """ try: outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') outlet_real_state = states[int(outlet_state)] # here we check if the outlet is powered on if outlet_real_state != "on": helper.status(critical) # print the status helper.add_summary("Outlet %s - '%s' is: %s" % (self.number, outlet_name, outlet_real_state.upper()))
[ "def", "check_outlet", "(", "self", ",", "helper", ")", ":", "try", ":", "outlet_name", ",", "outlet_state", "=", "self", ".", "sess", ".", "get_oids", "(", "self", ".", "oids", "[", "'oid_outlet_name'", "]", ",", "self", ".", "oids", "[", "'oid_outlet_s...
check the status of the specified outlet
[ "check", "the", "status", "of", "the", "specified", "outlet" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/raritan.py#L157-L172
train
38,541
rsmuc/health_monitoring_plugins
health_monitoring_plugins/raritan.py
Raritan.check_sensor
def check_sensor(self, helper): """ check the status of the specified sensor """ try: sensor_name, sensor_state, sensor_type = self.sess.get_oids( self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') try: sensor_state_string = states[int(sensor_state)] except KeyError as e: helper.exit(summary="Invalid sensor response " + sensor_state, exit_code=unknown, perfdata='') sensor_unit = "" # if it's a onOff Sensor or something like that, we need an empty string for the summary sensor_unit_string = "" sensor_value = "" sensor_digit = "" real_sensor_value = "" sensor_warning_upper = "" sensor_critical_upper = "" sensor_warning_lower = "" sensor_critical_lower = "" if int(sensor_type) not in [14, 16, 17, 18, 19, 20]: # for all sensors except these, we want to calculate the real value and show the metric. # 14: onOff # 16: vibration # 17: waterDetection # 18: smokeDetection # 19: binary # 20: contact try: sensor_unit, sensor_digit, sensor_warning_upper, sensor_critical_upper, sensor_warning_lower, sensor_critical_lower, sensor_value = self.sess.get_oids( self.oids['oid_sensor_unit'], self.oids['oid_sensor_digit'], self.oids['oid_sensor_warning_upper'], self.oids['oid_sensor_critical_upper'], self.oids['oid_sensor_warning_lower'], self.oids['oid_sensor_critical_lower'], self.oids['oid_sensor_value']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') sensor_unit_string = units[int(sensor_unit)] real_sensor_value = real_value(int(sensor_value), sensor_digit) real_sensor_warning_upper = real_value(sensor_warning_upper, sensor_digit) real_sensor_critical_upper = real_value(sensor_critical_upper, sensor_digit) real_sensor_warning_lower = real_value(sensor_warning_lower, sensor_digit) real_sensor_critical_lower = real_value(sensor_critical_lower, sensor_digit) # metrics are only possible for these sensors helper.add_metric(sensor_name + " -%s- " % sensor_unit_string, real_sensor_value, real_sensor_warning_lower +\ ":" + real_sensor_warning_upper, real_sensor_critical_lower +\ ":" + real_sensor_critical_upper, "", "", "") # "OK" state if sensor_state_string in ["closed", "normal", "on", "notDetected", "ok", "yes", "one", "two", "inSync"]: helper.status(ok) # "WARNING" state elif sensor_state_string in ["open", "belowLowerWarning", "aboveUpperWarning", "marginal", "standby"]: helper.status(warning) # "CRITICAL" state elif sensor_state_string in ["belowLowerCritical", "aboveUpperCritical", "off", "detected", "alarmed", "fail", "no", "outOfSync"]: helper.status(critical) # "UNKOWN" state elif sensor_state_string in ["unavailable"]: helper.status(unknown) # received an undefined state else: helper.exit(summary="Something went wrong - received undefined state", exit_code=unknown, perfdata='') # summary is shown for all sensors helper.add_summary("Sensor %s - '%s' %s%s is: %s" % (self.number, sensor_name, real_sensor_value, sensor_unit_string, sensor_state_string))
python
def check_sensor(self, helper): """ check the status of the specified sensor """ try: sensor_name, sensor_state, sensor_type = self.sess.get_oids( self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') try: sensor_state_string = states[int(sensor_state)] except KeyError as e: helper.exit(summary="Invalid sensor response " + sensor_state, exit_code=unknown, perfdata='') sensor_unit = "" # if it's a onOff Sensor or something like that, we need an empty string for the summary sensor_unit_string = "" sensor_value = "" sensor_digit = "" real_sensor_value = "" sensor_warning_upper = "" sensor_critical_upper = "" sensor_warning_lower = "" sensor_critical_lower = "" if int(sensor_type) not in [14, 16, 17, 18, 19, 20]: # for all sensors except these, we want to calculate the real value and show the metric. # 14: onOff # 16: vibration # 17: waterDetection # 18: smokeDetection # 19: binary # 20: contact try: sensor_unit, sensor_digit, sensor_warning_upper, sensor_critical_upper, sensor_warning_lower, sensor_critical_lower, sensor_value = self.sess.get_oids( self.oids['oid_sensor_unit'], self.oids['oid_sensor_digit'], self.oids['oid_sensor_warning_upper'], self.oids['oid_sensor_critical_upper'], self.oids['oid_sensor_warning_lower'], self.oids['oid_sensor_critical_lower'], self.oids['oid_sensor_value']) except health_monitoring_plugins.SnmpException as e: helper.exit(summary=str(e), exit_code=unknown, perfdata='') sensor_unit_string = units[int(sensor_unit)] real_sensor_value = real_value(int(sensor_value), sensor_digit) real_sensor_warning_upper = real_value(sensor_warning_upper, sensor_digit) real_sensor_critical_upper = real_value(sensor_critical_upper, sensor_digit) real_sensor_warning_lower = real_value(sensor_warning_lower, sensor_digit) real_sensor_critical_lower = real_value(sensor_critical_lower, sensor_digit) # metrics are only possible for these sensors helper.add_metric(sensor_name + " -%s- " % sensor_unit_string, real_sensor_value, real_sensor_warning_lower +\ ":" + real_sensor_warning_upper, real_sensor_critical_lower +\ ":" + real_sensor_critical_upper, "", "", "") # "OK" state if sensor_state_string in ["closed", "normal", "on", "notDetected", "ok", "yes", "one", "two", "inSync"]: helper.status(ok) # "WARNING" state elif sensor_state_string in ["open", "belowLowerWarning", "aboveUpperWarning", "marginal", "standby"]: helper.status(warning) # "CRITICAL" state elif sensor_state_string in ["belowLowerCritical", "aboveUpperCritical", "off", "detected", "alarmed", "fail", "no", "outOfSync"]: helper.status(critical) # "UNKOWN" state elif sensor_state_string in ["unavailable"]: helper.status(unknown) # received an undefined state else: helper.exit(summary="Something went wrong - received undefined state", exit_code=unknown, perfdata='') # summary is shown for all sensors helper.add_summary("Sensor %s - '%s' %s%s is: %s" % (self.number, sensor_name, real_sensor_value, sensor_unit_string, sensor_state_string))
[ "def", "check_sensor", "(", "self", ",", "helper", ")", ":", "try", ":", "sensor_name", ",", "sensor_state", ",", "sensor_type", "=", "self", ".", "sess", ".", "get_oids", "(", "self", ".", "oids", "[", "'oid_sensor_name'", "]", ",", "self", ".", "oids",...
check the status of the specified sensor
[ "check", "the", "status", "of", "the", "specified", "sensor" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/raritan.py#L174-L248
train
38,542
rsmuc/health_monitoring_plugins
health_monitoring_plugins/meinberg.py
Meinberg.process_gps_position
def process_gps_position(self, helper, sess): """ just print the current GPS position """ gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position']) if gps_position: helper.add_summary(gps_position) else: helper.add_summary("Could not retrieve GPS position") helper.status(unknown)
python
def process_gps_position(self, helper, sess): """ just print the current GPS position """ gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position']) if gps_position: helper.add_summary(gps_position) else: helper.add_summary("Could not retrieve GPS position") helper.status(unknown)
[ "def", "process_gps_position", "(", "self", ",", "helper", ",", "sess", ")", ":", "gps_position", "=", "helper", ".", "get_snmp_value", "(", "sess", ",", "helper", ",", "self", ".", "oids", "[", "'oid_gps_position'", "]", ")", "if", "gps_position", ":", "h...
just print the current GPS position
[ "just", "print", "the", "current", "GPS", "position" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/meinberg.py#L108-L119
train
38,543
rsmuc/health_monitoring_plugins
health_monitoring_plugins/meinberg.py
Meinberg.process_status
def process_status(self, helper, sess, check): """ get the snmp value, check the status and update the helper""" if check == 'ntp_current_state': ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int']) result = self.check_ntp_status(ntp_status_int) elif check == 'gps_mode': gps_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_gps_mode_int']) result = self.check_gps_status(gps_status_int) else: return helper.update_status(helper, result)
python
def process_status(self, helper, sess, check): """ get the snmp value, check the status and update the helper""" if check == 'ntp_current_state': ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int']) result = self.check_ntp_status(ntp_status_int) elif check == 'gps_mode': gps_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_gps_mode_int']) result = self.check_gps_status(gps_status_int) else: return helper.update_status(helper, result)
[ "def", "process_status", "(", "self", ",", "helper", ",", "sess", ",", "check", ")", ":", "if", "check", "==", "'ntp_current_state'", ":", "ntp_status_int", "=", "helper", ".", "get_snmp_value", "(", "sess", ",", "helper", ",", "self", ".", "oids", "[", ...
get the snmp value, check the status and update the helper
[ "get", "the", "snmp", "value", "check", "the", "status", "and", "update", "the", "helper" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/meinberg.py#L121-L133
train
38,544
rsmuc/health_monitoring_plugins
health_monitoring_plugins/meinberg.py
Meinberg.check_ntp_status
def check_ntp_status(self, ntp_status_int): """ check the NTP status """ # convert the ntp_status integer value in a human readable value ntp_status_string = self.ntp_status.get(ntp_status_int, "unknown") if ntp_status_string == "unknown": return unknown, ("NTP status: " + ntp_status_string) # the ntp status should be synchronized (new MIB) or normalOperation (old mib) elif ntp_status_string != "synchronized" and ntp_status_string != "normalOperationPPS": # that is a critical condition, because the time reference will not be reliable anymore return critical, ("NTP status: " + ntp_status_string) return None
python
def check_ntp_status(self, ntp_status_int): """ check the NTP status """ # convert the ntp_status integer value in a human readable value ntp_status_string = self.ntp_status.get(ntp_status_int, "unknown") if ntp_status_string == "unknown": return unknown, ("NTP status: " + ntp_status_string) # the ntp status should be synchronized (new MIB) or normalOperation (old mib) elif ntp_status_string != "synchronized" and ntp_status_string != "normalOperationPPS": # that is a critical condition, because the time reference will not be reliable anymore return critical, ("NTP status: " + ntp_status_string) return None
[ "def", "check_ntp_status", "(", "self", ",", "ntp_status_int", ")", ":", "# convert the ntp_status integer value in a human readable value", "ntp_status_string", "=", "self", ".", "ntp_status", ".", "get", "(", "ntp_status_int", ",", "\"unknown\"", ")", "if", "ntp_status_...
check the NTP status
[ "check", "the", "NTP", "status" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/meinberg.py#L135-L150
train
38,545
rsmuc/health_monitoring_plugins
health_monitoring_plugins/meinberg.py
Meinberg.check_gps_status
def check_gps_status(self, gps_status_int): """ check the GPS status """ gps_mode_string = self.gps_mode.get(gps_status_int, "unknown") if gps_mode_string == "unknown": return unknown, ("GPS status: " + gps_mode_string) elif gps_mode_string != "normalOperation" \ and gps_mode_string != "gpsSync": # that is a warning condition, NTP could still work without the GPS antenna return warning, ("GPS status: " + gps_mode_string) return None
python
def check_gps_status(self, gps_status_int): """ check the GPS status """ gps_mode_string = self.gps_mode.get(gps_status_int, "unknown") if gps_mode_string == "unknown": return unknown, ("GPS status: " + gps_mode_string) elif gps_mode_string != "normalOperation" \ and gps_mode_string != "gpsSync": # that is a warning condition, NTP could still work without the GPS antenna return warning, ("GPS status: " + gps_mode_string) return None
[ "def", "check_gps_status", "(", "self", ",", "gps_status_int", ")", ":", "gps_mode_string", "=", "self", ".", "gps_mode", ".", "get", "(", "gps_status_int", ",", "\"unknown\"", ")", "if", "gps_mode_string", "==", "\"unknown\"", ":", "return", "unknown", ",", "...
check the GPS status
[ "check", "the", "GPS", "status" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/meinberg.py#L152-L166
train
38,546
rsmuc/health_monitoring_plugins
health_monitoring_plugins/meinberg.py
Meinberg.process_satellites
def process_satellites(self, helper, sess): """ check and show the good satellites """ good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good']) # Show the summary and add the metric and afterwards check the metric helper.add_summary("Good satellites: {}".format(good_satellites)) helper.add_metric(label='satellites', value=good_satellites)
python
def process_satellites(self, helper, sess): """ check and show the good satellites """ good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good']) # Show the summary and add the metric and afterwards check the metric helper.add_summary("Good satellites: {}".format(good_satellites)) helper.add_metric(label='satellites', value=good_satellites)
[ "def", "process_satellites", "(", "self", ",", "helper", ",", "sess", ")", ":", "good_satellites", "=", "helper", ".", "get_snmp_value", "(", "sess", ",", "helper", ",", "self", ".", "oids", "[", "'oid_gps_satellites_good'", "]", ")", "# Show the summary and add...
check and show the good satellites
[ "check", "and", "show", "the", "good", "satellites" ]
7ac29dfb9fe46c055b018cb72ad0d7d8065589b9
https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/meinberg.py#L168-L176
train
38,547
mozilla/fxapom
fxapom/pages/sign_in.py
SignIn.login_password
def login_password(self, value): """Set the value of the login password field.""" password = self.selenium.find_element(*self._password_input_locator) password.clear() password.send_keys(value)
python
def login_password(self, value): """Set the value of the login password field.""" password = self.selenium.find_element(*self._password_input_locator) password.clear() password.send_keys(value)
[ "def", "login_password", "(", "self", ",", "value", ")", ":", "password", "=", "self", ".", "selenium", ".", "find_element", "(", "*", "self", ".", "_password_input_locator", ")", "password", ".", "clear", "(", ")", "password", ".", "send_keys", "(", "valu...
Set the value of the login password field.
[ "Set", "the", "value", "of", "the", "login", "password", "field", "." ]
d09ee84c21b46c1b27dd19b65490bebe038005c4
https://github.com/mozilla/fxapom/blob/d09ee84c21b46c1b27dd19b65490bebe038005c4/fxapom/pages/sign_in.py#L32-L36
train
38,548
mozilla/fxapom
fxapom/pages/sign_in.py
SignIn.email
def email(self, value): """Set the value of the email field.""" email = self.wait.until(expected.visibility_of_element_located( self._email_input_locator)) email.clear() email.send_keys(value)
python
def email(self, value): """Set the value of the email field.""" email = self.wait.until(expected.visibility_of_element_located( self._email_input_locator)) email.clear() email.send_keys(value)
[ "def", "email", "(", "self", ",", "value", ")", ":", "email", "=", "self", ".", "wait", ".", "until", "(", "expected", ".", "visibility_of_element_located", "(", "self", ".", "_email_input_locator", ")", ")", "email", ".", "clear", "(", ")", "email", "."...
Set the value of the email field.
[ "Set", "the", "value", "of", "the", "email", "field", "." ]
d09ee84c21b46c1b27dd19b65490bebe038005c4
https://github.com/mozilla/fxapom/blob/d09ee84c21b46c1b27dd19b65490bebe038005c4/fxapom/pages/sign_in.py#L47-L52
train
38,549
mozilla/fxapom
fxapom/pages/sign_in.py
SignIn.sign_in
def sign_in(self, email, password): """Signs in using the specified email address and password.""" self.email = email self.login_password = password if self.is_element_present(*self._next_button_locator): self.wait.until(expected.visibility_of_element_located( self._next_button_locator)) self.click_next() self.click_sign_in()
python
def sign_in(self, email, password): """Signs in using the specified email address and password.""" self.email = email self.login_password = password if self.is_element_present(*self._next_button_locator): self.wait.until(expected.visibility_of_element_located( self._next_button_locator)) self.click_next() self.click_sign_in()
[ "def", "sign_in", "(", "self", ",", "email", ",", "password", ")", ":", "self", ".", "email", "=", "email", "self", ".", "login_password", "=", "password", "if", "self", ".", "is_element_present", "(", "*", "self", ".", "_next_button_locator", ")", ":", ...
Signs in using the specified email address and password.
[ "Signs", "in", "using", "the", "specified", "email", "address", "and", "password", "." ]
d09ee84c21b46c1b27dd19b65490bebe038005c4
https://github.com/mozilla/fxapom/blob/d09ee84c21b46c1b27dd19b65490bebe038005c4/fxapom/pages/sign_in.py#L74-L82
train
38,550
mozilla/fxapom
fxapom/fxapom.py
WebDriverFxA.sign_in
def sign_in(self, email=None, password=None): """Signs in a user, either with the specified email address and password, or a returning user.""" from .pages.sign_in import SignIn sign_in = SignIn(self.selenium, self.timeout) sign_in.sign_in(email, password)
python
def sign_in(self, email=None, password=None): """Signs in a user, either with the specified email address and password, or a returning user.""" from .pages.sign_in import SignIn sign_in = SignIn(self.selenium, self.timeout) sign_in.sign_in(email, password)
[ "def", "sign_in", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "from", ".", "pages", ".", "sign_in", "import", "SignIn", "sign_in", "=", "SignIn", "(", "self", ".", "selenium", ",", "self", ".", "timeout", ")", "sig...
Signs in a user, either with the specified email address and password, or a returning user.
[ "Signs", "in", "a", "user", "either", "with", "the", "specified", "email", "address", "and", "password", "or", "a", "returning", "user", "." ]
d09ee84c21b46c1b27dd19b65490bebe038005c4
https://github.com/mozilla/fxapom/blob/d09ee84c21b46c1b27dd19b65490bebe038005c4/fxapom/fxapom.py#L31-L35
train
38,551
xflr6/gsheets
gsheets/export.py
write_csv
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT): """Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.""" csvwriter = csv.writer(fileobj, dialect=dialect) csv_writerows(csvwriter, rows, encoding)
python
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT): """Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.""" csvwriter = csv.writer(fileobj, dialect=dialect) csv_writerows(csvwriter, rows, encoding)
[ "def", "write_csv", "(", "fileobj", ",", "rows", ",", "encoding", "=", "ENCODING", ",", "dialect", "=", "DIALECT", ")", ":", "csvwriter", "=", "csv", ".", "writer", "(", "fileobj", ",", "dialect", "=", "dialect", ")", "csv_writerows", "(", "csvwriter", "...
Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.
[ "Dump", "rows", "to", "fileobj", "with", "the", "given", "encoding", "and", "CSV", "dialect", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/export.py#L21-L24
train
38,552
xflr6/gsheets
gsheets/urls.py
SheetUrl.from_string
def from_string(cls, link): """Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0> """ ma = cls._pattern.search(link) if ma is None: raise ValueError(link) id = ma.group('id') return cls(id)
python
def from_string(cls, link): """Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0> """ ma = cls._pattern.search(link) if ma is None: raise ValueError(link) id = ma.group('id') return cls(id)
[ "def", "from_string", "(", "cls", ",", "link", ")", ":", "ma", "=", "cls", ".", "_pattern", ".", "search", "(", "link", ")", "if", "ma", "is", "None", ":", "raise", "ValueError", "(", "link", ")", "id", "=", "ma", ".", "group", "(", "'id'", ")", ...
Return a new SheetUrl instance from parsed URL string. >>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam') <SheetUrl id='spam' gid=0>
[ "Return", "a", "new", "SheetUrl", "instance", "from", "parsed", "URL", "string", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/urls.py#L18-L28
train
38,553
xflr6/gsheets
gsheets/tools.py
doctemplate
def doctemplate(*args): """Return a decorator putting ``args`` into the docstring of the decorated ``func``. >>> @doctemplate('spam', 'spam') ... def spam(): ... '''Returns %s, lovely %s.''' ... return 'Spam' >>> spam.__doc__ 'Returns spam, lovely spam.' """ def decorator(func): func.__doc__ = func.__doc__ % tuple(args) return func return decorator
python
def doctemplate(*args): """Return a decorator putting ``args`` into the docstring of the decorated ``func``. >>> @doctemplate('spam', 'spam') ... def spam(): ... '''Returns %s, lovely %s.''' ... return 'Spam' >>> spam.__doc__ 'Returns spam, lovely spam.' """ def decorator(func): func.__doc__ = func.__doc__ % tuple(args) return func return decorator
[ "def", "doctemplate", "(", "*", "args", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", ".", "__doc__", "=", "func", ".", "__doc__", "%", "tuple", "(", "args", ")", "return", "func", "return", "decorator" ]
Return a decorator putting ``args`` into the docstring of the decorated ``func``. >>> @doctemplate('spam', 'spam') ... def spam(): ... '''Returns %s, lovely %s.''' ... return 'Spam' >>> spam.__doc__ 'Returns spam, lovely spam.'
[ "Return", "a", "decorator", "putting", "args", "into", "the", "docstring", "of", "the", "decorated", "func", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/tools.py#L43-L57
train
38,554
xflr6/gsheets
gsheets/tools.py
group_dict
def group_dict(items, keyfunc): """Return a list defaultdict with ``items`` grouped by ``keyfunc``. >>> sorted(group_dict('eggs', lambda x: x).items()) [('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])] """ result = collections.defaultdict(list) for i in items: key = keyfunc(i) result[key].append(i) return result
python
def group_dict(items, keyfunc): """Return a list defaultdict with ``items`` grouped by ``keyfunc``. >>> sorted(group_dict('eggs', lambda x: x).items()) [('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])] """ result = collections.defaultdict(list) for i in items: key = keyfunc(i) result[key].append(i) return result
[ "def", "group_dict", "(", "items", ",", "keyfunc", ")", ":", "result", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "i", "in", "items", ":", "key", "=", "keyfunc", "(", "i", ")", "result", "[", "key", "]", ".", "append", "(", "i...
Return a list defaultdict with ``items`` grouped by ``keyfunc``. >>> sorted(group_dict('eggs', lambda x: x).items()) [('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])]
[ "Return", "a", "list", "defaultdict", "with", "items", "grouped", "by", "keyfunc", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/tools.py#L106-L116
train
38,555
xflr6/gsheets
gsheets/tools.py
uniqued
def uniqued(iterable): """Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g'] """ seen = set() return [item for item in iterable if item not in seen and not seen.add(item)]
python
def uniqued(iterable): """Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g'] """ seen = set() return [item for item in iterable if item not in seen and not seen.add(item)]
[ "def", "uniqued", "(", "iterable", ")", ":", "seen", "=", "set", "(", ")", "return", "[", "item", "for", "item", "in", "iterable", "if", "item", "not", "in", "seen", "and", "not", "seen", ".", "add", "(", "item", ")", "]" ]
Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g']
[ "Return", "unique", "list", "of", "iterable", "items", "preserving", "order", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/tools.py#L133-L140
train
38,556
xflr6/gsheets
gsheets/backend.py
build_service
def build_service(name=None, **kwargs): """Return a service endpoint for interacting with a Google API.""" if name is not None: for kw, value in iteritems(SERVICES[name]): kwargs.setdefault(kw, value) return apiclient.discovery.build(**kwargs)
python
def build_service(name=None, **kwargs): """Return a service endpoint for interacting with a Google API.""" if name is not None: for kw, value in iteritems(SERVICES[name]): kwargs.setdefault(kw, value) return apiclient.discovery.build(**kwargs)
[ "def", "build_service", "(", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "name", "is", "not", "None", ":", "for", "kw", ",", "value", "in", "iteritems", "(", "SERVICES", "[", "name", "]", ")", ":", "kwargs", ".", "setdefault", "("...
Return a service endpoint for interacting with a Google API.
[ "Return", "a", "service", "endpoint", "for", "interacting", "with", "a", "Google", "API", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/backend.py#L21-L26
train
38,557
xflr6/gsheets
gsheets/backend.py
spreadsheet
def spreadsheet(service, id): """Fetch and return spreadsheet meta data with Google sheets API.""" request = service.spreadsheets().get(spreadsheetId=id) try: response = request.execute() except apiclient.errors.HttpError as e: if e.resp.status == 404: raise KeyError(id) else: # pragma: no cover raise return response
python
def spreadsheet(service, id): """Fetch and return spreadsheet meta data with Google sheets API.""" request = service.spreadsheets().get(spreadsheetId=id) try: response = request.execute() except apiclient.errors.HttpError as e: if e.resp.status == 404: raise KeyError(id) else: # pragma: no cover raise return response
[ "def", "spreadsheet", "(", "service", ",", "id", ")", ":", "request", "=", "service", ".", "spreadsheets", "(", ")", ".", "get", "(", "spreadsheetId", "=", "id", ")", "try", ":", "response", "=", "request", ".", "execute", "(", ")", "except", "apiclien...
Fetch and return spreadsheet meta data with Google sheets API.
[ "Fetch", "and", "return", "spreadsheet", "meta", "data", "with", "Google", "sheets", "API", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/backend.py#L50-L60
train
38,558
xflr6/gsheets
gsheets/backend.py
values
def values(service, id, ranges): """Fetch and return spreadsheet cell values with Google sheets API.""" params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE', 'dateTimeRenderOption': 'FORMATTED_STRING'} params.update(spreadsheetId=id, ranges=ranges) response = service.spreadsheets().values().batchGet(**params).execute() return response['valueRanges']
python
def values(service, id, ranges): """Fetch and return spreadsheet cell values with Google sheets API.""" params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE', 'dateTimeRenderOption': 'FORMATTED_STRING'} params.update(spreadsheetId=id, ranges=ranges) response = service.spreadsheets().values().batchGet(**params).execute() return response['valueRanges']
[ "def", "values", "(", "service", ",", "id", ",", "ranges", ")", ":", "params", "=", "{", "'majorDimension'", ":", "'ROWS'", ",", "'valueRenderOption'", ":", "'UNFORMATTED_VALUE'", ",", "'dateTimeRenderOption'", ":", "'FORMATTED_STRING'", "}", "params", ".", "upd...
Fetch and return spreadsheet cell values with Google sheets API.
[ "Fetch", "and", "return", "spreadsheet", "cell", "values", "with", "Google", "sheets", "API", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/backend.py#L63-L69
train
38,559
xflr6/gsheets
gsheets/oauth2.py
get_credentials
def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False): """Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files. Args: scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``) secrets: location of secrets file (default: ``%r``) storage: location of storage file (default: ``%r``) no_webserver: url/code prompt instead of webbrowser based auth see https://developers.google.com/sheets/quickstart/python see https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ scopes = Scopes.get(scopes) if secrets is None: secrets = SECRETS if storage is None: storage = STORAGE secrets, storage = map(os.path.expanduser, (secrets, storage)) store = file.Storage(storage) creds = store.get() if creds is None or creds.invalid: flow = client.flow_from_clientsecrets(secrets, scopes) args = ['--noauth_local_webserver'] if no_webserver else [] flags = tools.argparser.parse_args(args) creds = tools.run_flow(flow, store, flags) return creds
python
def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False): """Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files. Args: scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``) secrets: location of secrets file (default: ``%r``) storage: location of storage file (default: ``%r``) no_webserver: url/code prompt instead of webbrowser based auth see https://developers.google.com/sheets/quickstart/python see https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ scopes = Scopes.get(scopes) if secrets is None: secrets = SECRETS if storage is None: storage = STORAGE secrets, storage = map(os.path.expanduser, (secrets, storage)) store = file.Storage(storage) creds = store.get() if creds is None or creds.invalid: flow = client.flow_from_clientsecrets(secrets, scopes) args = ['--noauth_local_webserver'] if no_webserver else [] flags = tools.argparser.parse_args(args) creds = tools.run_flow(flow, store, flags) return creds
[ "def", "get_credentials", "(", "scopes", "=", "None", ",", "secrets", "=", "None", ",", "storage", "=", "None", ",", "no_webserver", "=", "False", ")", ":", "scopes", "=", "Scopes", ".", "get", "(", "scopes", ")", "if", "secrets", "is", "None", ":", ...
Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files. Args: scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``) secrets: location of secrets file (default: ``%r``) storage: location of storage file (default: ``%r``) no_webserver: url/code prompt instead of webbrowser based auth see https://developers.google.com/sheets/quickstart/python see https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
[ "Make", "OAuth", "2", ".", "0", "credentials", "for", "scopes", "from", "secrets", "and", "storage", "files", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/oauth2.py#L23-L53
train
38,560
xflr6/gsheets
gsheets/oauth2.py
Scopes.get
def get(cls, scope=None): """Return default or predefined URLs from keyword, pass through ``scope``.""" if scope is None: scope = cls.default if isinstance(scope, string_types) and scope in cls._keywords: return getattr(cls, scope) return scope
python
def get(cls, scope=None): """Return default or predefined URLs from keyword, pass through ``scope``.""" if scope is None: scope = cls.default if isinstance(scope, string_types) and scope in cls._keywords: return getattr(cls, scope) return scope
[ "def", "get", "(", "cls", ",", "scope", "=", "None", ")", ":", "if", "scope", "is", "None", ":", "scope", "=", "cls", ".", "default", "if", "isinstance", "(", "scope", ",", "string_types", ")", "and", "scope", "in", "cls", ".", "_keywords", ":", "r...
Return default or predefined URLs from keyword, pass through ``scope``.
[ "Return", "default", "or", "predefined", "URLs", "from", "keyword", "pass", "through", "scope", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/oauth2.py#L93-L99
train
38,561
tristantao/py-bing-search
py_bing_search/py_bing_search.py
PyBingSearch.search_all
def search_all(self, limit=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects''' desired_limit = limit results = self._search(limit, format) limit = limit - len(results) while len(results) < desired_limit: more_results = self._search(limit, format) if not more_results: break results += more_results limit = limit - len(more_results) time.sleep(1) return results
python
def search_all(self, limit=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects''' desired_limit = limit results = self._search(limit, format) limit = limit - len(results) while len(results) < desired_limit: more_results = self._search(limit, format) if not more_results: break results += more_results limit = limit - len(more_results) time.sleep(1) return results
[ "def", "search_all", "(", "self", ",", "limit", "=", "50", ",", "format", "=", "'json'", ")", ":", "desired_limit", "=", "limit", "results", "=", "self", ".", "_search", "(", "limit", ",", "format", ")", "limit", "=", "limit", "-", "len", "(", "resul...
Returns a single list containing up to 'limit' Result objects
[ "Returns", "a", "single", "list", "containing", "up", "to", "limit", "Result", "objects" ]
d18b8fcfe5a5502682c65dd458f50c0a29a510e9
https://github.com/tristantao/py-bing-search/blob/d18b8fcfe5a5502682c65dd458f50c0a29a510e9/py_bing_search/py_bing_search.py#L22-L34
train
38,562
tristantao/py-bing-search
py_bing_search/py_bing_search.py
PyBingVideoSearch._search
def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page bing search url. ''' url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), self.current_offset, format) r = requests.get(url, auth=("", self.api_key)) try: json_results = r.json() except ValueError as vE: if not self.safe: raise PyBingVideoException("Request returned with code %s, error msg: %s" % (r.status_code, r.text)) else: print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text)) time.sleep(5) packaged_results = [VideoResult(single_result_json) for single_result_json in json_results['d']['results']] self.current_offset += min(50, limit, len(packaged_results)) return packaged_results
python
def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page bing search url. ''' url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), self.current_offset, format) r = requests.get(url, auth=("", self.api_key)) try: json_results = r.json() except ValueError as vE: if not self.safe: raise PyBingVideoException("Request returned with code %s, error msg: %s" % (r.status_code, r.text)) else: print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text)) time.sleep(5) packaged_results = [VideoResult(single_result_json) for single_result_json in json_results['d']['results']] self.current_offset += min(50, limit, len(packaged_results)) return packaged_results
[ "def", "_search", "(", "self", ",", "limit", ",", "format", ")", ":", "url", "=", "self", ".", "QUERY_URL", ".", "format", "(", "requests", ".", "utils", ".", "quote", "(", "\"'{}'\"", ".", "format", "(", "self", ".", "query", ")", ")", ",", "min",...
Returns a list of result objects, with the url for the next page bing search url.
[ "Returns", "a", "list", "of", "result", "objects", "with", "the", "url", "for", "the", "next", "page", "bing", "search", "url", "." ]
d18b8fcfe5a5502682c65dd458f50c0a29a510e9
https://github.com/tristantao/py-bing-search/blob/d18b8fcfe5a5502682c65dd458f50c0a29a510e9/py_bing_search/py_bing_search.py#L216-L232
train
38,563
xflr6/gsheets
gsheets/coordinates.py
base26int
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
python
def base26int(s, _start=1 - ord('A')): """Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799 """ return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
[ "def", "base26int", "(", "s", ",", "_start", "=", "1", "-", "ord", "(", "'A'", ")", ")", ":", "return", "sum", "(", "(", "_start", "+", "ord", "(", "c", ")", ")", "*", "26", "**", "i", "for", "i", ",", "c", "in", "enumerate", "(", "reversed",...
Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799
[ "Return", "string", "s", "as", "int", "in", "bijective", "base26", "notation", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/coordinates.py#L13-L19
train
38,564
xflr6/gsheets
gsheets/coordinates.py
base26
def base26(x, _alphabet=string.ascii_uppercase): """Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV' """ result = [] while x: x, digit = divmod(x, 26) if not digit: x -= 1 digit = 26 result.append(_alphabet[digit - 1]) return ''.join(result[::-1])
python
def base26(x, _alphabet=string.ascii_uppercase): """Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV' """ result = [] while x: x, digit = divmod(x, 26) if not digit: x -= 1 digit = 26 result.append(_alphabet[digit - 1]) return ''.join(result[::-1])
[ "def", "base26", "(", "x", ",", "_alphabet", "=", "string", ".", "ascii_uppercase", ")", ":", "result", "=", "[", "]", "while", "x", ":", "x", ",", "digit", "=", "divmod", "(", "x", ",", "26", ")", "if", "not", "digit", ":", "x", "-=", "1", "di...
Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV'
[ "Return", "positive", "int", "x", "as", "string", "in", "bijective", "base26", "notation", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/coordinates.py#L22-L41
train
38,565
xflr6/gsheets
gsheets/coordinates.py
Coordinates._parse
def _parse(coord, _match=_regex.match): """Return match groups from single sheet coordinate. >>> Coordinates._parse('A1') ('A', '1', None, None) >>> Coordinates._parse('A'), Coordinates._parse('1') ((None, None, 'A', None), (None, None, None, '1')) >>> Coordinates._parse('spam') Traceback (most recent call last): ... ValueError: spam """ try: return _match(coord).groups() except AttributeError: raise ValueError(coord)
python
def _parse(coord, _match=_regex.match): """Return match groups from single sheet coordinate. >>> Coordinates._parse('A1') ('A', '1', None, None) >>> Coordinates._parse('A'), Coordinates._parse('1') ((None, None, 'A', None), (None, None, None, '1')) >>> Coordinates._parse('spam') Traceback (most recent call last): ... ValueError: spam """ try: return _match(coord).groups() except AttributeError: raise ValueError(coord)
[ "def", "_parse", "(", "coord", ",", "_match", "=", "_regex", ".", "match", ")", ":", "try", ":", "return", "_match", "(", "coord", ")", ".", "groups", "(", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "coord", ")" ]
Return match groups from single sheet coordinate. >>> Coordinates._parse('A1') ('A', '1', None, None) >>> Coordinates._parse('A'), Coordinates._parse('1') ((None, None, 'A', None), (None, None, None, '1')) >>> Coordinates._parse('spam') Traceback (most recent call last): ... ValueError: spam
[ "Return", "match", "groups", "from", "single", "sheet", "coordinate", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/coordinates.py#L87-L104
train
38,566
xflr6/gsheets
gsheets/coordinates.py
Coordinates._cint
def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}): """Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam """ try: return _map[col.upper()] except KeyError: raise ValueError(col)
python
def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}): """Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam """ try: return _map[col.upper()] except KeyError: raise ValueError(col)
[ "def", "_cint", "(", "col", ",", "_map", "=", "{", "base26", "(", "i", ")", ":", "i", "-", "1", "for", "i", "in", "range", "(", "1", ",", "257", ")", "}", ")", ":", "try", ":", "return", "_map", "[", "col", ".", "upper", "(", ")", "]", "e...
Return zero-based column index from bijective base26 string. >>> Coordinates._cint('Ab') 27 >>> Coordinates._cint('spam') Traceback (most recent call last): ... ValueError: spam
[ "Return", "zero", "-", "based", "column", "index", "from", "bijective", "base26", "string", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/coordinates.py#L107-L121
train
38,567
xflr6/gsheets
gsheets/coordinates.py
Slice.from_slice
def from_slice(cls, coord): """Return a value fetching callable given a slice of coordinate strings.""" if coord.step is not None: raise NotImplementedError('no slice step support') elif coord.start is not None and coord.stop is not None: return DoubleSlice.from_slice(coord) elif coord.start is not None: xcol, xrow, col, row = cls._parse(coord.start) if xcol is not None: return StartCell(cls._cint(xcol), cls._rint(xrow)) elif col is not None: return StartCol(cls._cint(col)) return StartRow(cls._rint(row)) elif coord.stop is not None: xcol, xrow, col, row = cls._parse(coord.stop) if xcol is not None: return StopCell(cls._cint(xcol) + 1, cls._rint(xrow) + 1) elif col is not None: return StopCol(cls._cint(col) + 1) return StopRow(cls._rint(row) + 1) return cls()
python
def from_slice(cls, coord): """Return a value fetching callable given a slice of coordinate strings.""" if coord.step is not None: raise NotImplementedError('no slice step support') elif coord.start is not None and coord.stop is not None: return DoubleSlice.from_slice(coord) elif coord.start is not None: xcol, xrow, col, row = cls._parse(coord.start) if xcol is not None: return StartCell(cls._cint(xcol), cls._rint(xrow)) elif col is not None: return StartCol(cls._cint(col)) return StartRow(cls._rint(row)) elif coord.stop is not None: xcol, xrow, col, row = cls._parse(coord.stop) if xcol is not None: return StopCell(cls._cint(xcol) + 1, cls._rint(xrow) + 1) elif col is not None: return StopCol(cls._cint(col) + 1) return StopRow(cls._rint(row) + 1) return cls()
[ "def", "from_slice", "(", "cls", ",", "coord", ")", ":", "if", "coord", ".", "step", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'no slice step support'", ")", "elif", "coord", ".", "start", "is", "not", "None", "and", "coord", ".", "...
Return a value fetching callable given a slice of coordinate strings.
[ "Return", "a", "value", "fetching", "callable", "given", "a", "slice", "of", "coordinate", "strings", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/coordinates.py#L201-L221
train
38,568
xflr6/gsheets
gsheets/models.py
SpreadSheet.find
def find(self, title): """Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given ``title`` """ if title not in self._titles: raise KeyError(title) return self._titles[title][0]
python
def find(self, title): """Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given ``title`` """ if title not in self._titles: raise KeyError(title) return self._titles[title][0]
[ "def", "find", "(", "self", ",", "title", ")", ":", "if", "title", "not", "in", "self", ".", "_titles", ":", "raise", "KeyError", "(", "title", ")", "return", "self", ".", "_titles", "[", "title", "]", "[", "0", "]" ]
Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given ``title``
[ "Return", "the", "first", "worksheet", "with", "the", "given", "title", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L108-L120
train
38,569
xflr6/gsheets
gsheets/models.py
SpreadSheet.findall
def findall(self, title=None): """Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty) """ if title is None: return list(self._sheets) if title not in self._titles: return [] return list(self._titles[title])
python
def findall(self, title=None): """Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty) """ if title is None: return list(self._sheets) if title not in self._titles: return [] return list(self._titles[title])
[ "def", "findall", "(", "self", ",", "title", "=", "None", ")", ":", "if", "title", "is", "None", ":", "return", "list", "(", "self", ".", "_sheets", ")", "if", "title", "not", "in", "self", ".", "_titles", ":", "return", "[", "]", "return", "list",...
Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty)
[ "Return", "a", "list", "of", "worksheets", "with", "the", "given", "title", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L122-L134
train
38,570
xflr6/gsheets
gsheets/models.py
SpreadSheet.to_csv
def to_csv(self, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``. """ for s in self._sheets: s.to_csv(None, encoding, dialect, make_filename)
python
def to_csv(self, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``. """ for s in self._sheets: s.to_csv(None, encoding, dialect, make_filename)
[ "def", "to_csv", "(", "self", ",", "encoding", "=", "export", ".", "ENCODING", ",", "dialect", "=", "export", ".", "DIALECT", ",", "make_filename", "=", "export", ".", "MAKE_FILENAME", ")", ":", "for", "s", "in", "self", ".", "_sheets", ":", "s", ".", ...
Dump all worksheets of the spreadsheet to individual CSV files. Args: encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``.
[ "Dump", "all", "worksheets", "of", "the", "spreadsheet", "to", "individual", "CSV", "files", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L170-L190
train
38,571
xflr6/gsheets
gsheets/models.py
SheetsView.titles
def titles(self, unique=False): """Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings """ if unique: return tools.uniqued(s.title for s in self._items) return [s.title for s in self._items]
python
def titles(self, unique=False): """Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings """ if unique: return tools.uniqued(s.title for s in self._items) return [s.title for s in self._items]
[ "def", "titles", "(", "self", ",", "unique", "=", "False", ")", ":", "if", "unique", ":", "return", "tools", ".", "uniqued", "(", "s", ".", "title", "for", "s", "in", "self", ".", "_items", ")", "return", "[", "s", ".", "title", "for", "s", "in",...
Return a list of contained worksheet titles. Args: unique (bool): drop duplicates Returns: list: list of titles/name strings
[ "Return", "a", "list", "of", "contained", "worksheet", "titles", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L226-L236
train
38,572
xflr6/gsheets
gsheets/models.py
WorkSheet.at
def at(self, row, col): """Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` IndexError: if the position is out of range """ if not (isinstance(row, int) and isinstance(col, int)): raise TypeError(row, col) return self._values[row][col]
python
def at(self, row, col): """Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` IndexError: if the position is out of range """ if not (isinstance(row, int) and isinstance(col, int)): raise TypeError(row, col) return self._values[row][col]
[ "def", "at", "(", "self", ",", "row", ",", "col", ")", ":", "if", "not", "(", "isinstance", "(", "row", ",", "int", ")", "and", "isinstance", "(", "col", ",", "int", ")", ")", ":", "raise", "TypeError", "(", "row", ",", "col", ")", "return", "s...
Return the value at the given cell position. Args: row (int): zero-based row number col (int): zero-based column number Returns: cell value Raises: TypeError: if ``row`` or ``col`` is not an ``int`` IndexError: if the position is out of range
[ "Return", "the", "value", "at", "the", "given", "cell", "position", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L287-L301
train
38,573
xflr6/gsheets
gsheets/models.py
WorkSheet.values
def values(self, column_major=False): """Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values """ if column_major: return list(map(list, zip(*self._values))) return [row[:] for row in self._values]
python
def values(self, column_major=False): """Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values """ if column_major: return list(map(list, zip(*self._values))) return [row[:] for row in self._values]
[ "def", "values", "(", "self", ",", "column_major", "=", "False", ")", ":", "if", "column_major", ":", "return", "list", "(", "map", "(", "list", ",", "zip", "(", "*", "self", ".", "_values", ")", ")", ")", "return", "[", "row", "[", ":", "]", "fo...
Return a nested list with the worksheet values. Args: column_major (bool): as list of columns (default list of rows) Returns: list: list of lists with values
[ "Return", "a", "nested", "list", "with", "the", "worksheet", "values", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L303-L313
train
38,574
xflr6/gsheets
gsheets/models.py
WorkSheet.to_csv
def to_csv(self, filename=None, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump the worksheet to a CSV file. Args: filename (str): result filename (if ``None`` use ``make_filename``) encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``. """ if filename is None: if make_filename is None: make_filename = export.MAKE_FILENAME infos = { 'id': self._spreadsheet._id, 'title': self._spreadsheet._title, 'sheet': self._title, 'gid': self._id, 'index': self._index, 'dialect': dialect, } if isinstance(make_filename, string_types): filename = make_filename % infos else: filename = make_filename(infos) with export.open_csv(filename, 'w', encoding=encoding) as fd: export.write_csv(fd, self._values, encoding, dialect)
python
def to_csv(self, filename=None, encoding=export.ENCODING, dialect=export.DIALECT, make_filename=export.MAKE_FILENAME): """Dump the worksheet to a CSV file. Args: filename (str): result filename (if ``None`` use ``make_filename``) encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``. """ if filename is None: if make_filename is None: make_filename = export.MAKE_FILENAME infos = { 'id': self._spreadsheet._id, 'title': self._spreadsheet._title, 'sheet': self._title, 'gid': self._id, 'index': self._index, 'dialect': dialect, } if isinstance(make_filename, string_types): filename = make_filename % infos else: filename = make_filename(infos) with export.open_csv(filename, 'w', encoding=encoding) as fd: export.write_csv(fd, self._values, encoding, dialect)
[ "def", "to_csv", "(", "self", ",", "filename", "=", "None", ",", "encoding", "=", "export", ".", "ENCODING", ",", "dialect", "=", "export", ".", "DIALECT", ",", "make_filename", "=", "export", ".", "MAKE_FILENAME", ")", ":", "if", "filename", "is", "None...
Dump the worksheet to a CSV file. Args: filename (str): result filename (if ``None`` use ``make_filename``) encoding (str): result string encoding dialect (str): :mod:`csv` dialect name or object to use make_filename: template or one-argument callable returning the filename If ``make_filename`` is a string, it is string-interpolated with an infos-dictionary with the fields ``id`` (spreadhseet id), ``title`` (spreadsheet title), ``sheet`` (worksheet title), ``gid`` (worksheet id), ``index`` (worksheet index), and ``dialect`` CSV dialect to generate the filename: ``filename = make_filename % infos``. If ``make_filename`` is a callable, it will be called with the infos-dictionary to generate the filename: ``filename = make_filename(infos)``.
[ "Dump", "the", "worksheet", "to", "a", "CSV", "file", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L358-L395
train
38,575
xflr6/gsheets
gsheets/models.py
WorkSheet.to_frame
def to_frame(self, **kwargs): r"""Return a pandas DataFrame loaded from the worksheet data. Args: \**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``) Returns: pandas.DataFrame: new ``DataFrame`` instance """ df = export.write_dataframe(self._values, **kwargs) df.name = self.title return df
python
def to_frame(self, **kwargs): r"""Return a pandas DataFrame loaded from the worksheet data. Args: \**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``) Returns: pandas.DataFrame: new ``DataFrame`` instance """ df = export.write_dataframe(self._values, **kwargs) df.name = self.title return df
[ "def", "to_frame", "(", "self", ",", "*", "*", "kwargs", ")", ":", "df", "=", "export", ".", "write_dataframe", "(", "self", ".", "_values", ",", "*", "*", "kwargs", ")", "df", ".", "name", "=", "self", ".", "title", "return", "df" ]
r"""Return a pandas DataFrame loaded from the worksheet data. Args: \**kwargs: passed to ``pandas.read_csv()`` (e.g. ``header``, ``index_col``) Returns: pandas.DataFrame: new ``DataFrame`` instance
[ "r", "Return", "a", "pandas", "DataFrame", "loaded", "from", "the", "worksheet", "data", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L397-L407
train
38,576
xflr6/gsheets
gsheets/api.py
Sheets.from_files
def from_files(cls, secrets=None, storage=None, scopes=None, no_webserver=False): """Return a spreadsheet collection making OAauth 2.0 credentials. Args: secrets (str): location of secrets file (default: ``%r``) storage (str): location of storage file (default: ``%r``) scopes: scope URL(s) or ``'read'`` or ``'write'`` (default: ``%r``) no_webserver (bool): URL/code prompt instead of webbrowser auth Returns: Sheets: new Sheets instance with OAauth 2.0 credentials """ creds = oauth2.get_credentials(scopes, secrets, storage, no_webserver) return cls(creds)
python
def from_files(cls, secrets=None, storage=None, scopes=None, no_webserver=False): """Return a spreadsheet collection making OAauth 2.0 credentials. Args: secrets (str): location of secrets file (default: ``%r``) storage (str): location of storage file (default: ``%r``) scopes: scope URL(s) or ``'read'`` or ``'write'`` (default: ``%r``) no_webserver (bool): URL/code prompt instead of webbrowser auth Returns: Sheets: new Sheets instance with OAauth 2.0 credentials """ creds = oauth2.get_credentials(scopes, secrets, storage, no_webserver) return cls(creds)
[ "def", "from_files", "(", "cls", ",", "secrets", "=", "None", ",", "storage", "=", "None", ",", "scopes", "=", "None", ",", "no_webserver", "=", "False", ")", ":", "creds", "=", "oauth2", ".", "get_credentials", "(", "scopes", ",", "secrets", ",", "sto...
Return a spreadsheet collection making OAauth 2.0 credentials. Args: secrets (str): location of secrets file (default: ``%r``) storage (str): location of storage file (default: ``%r``) scopes: scope URL(s) or ``'read'`` or ``'write'`` (default: ``%r``) no_webserver (bool): URL/code prompt instead of webbrowser auth Returns: Sheets: new Sheets instance with OAauth 2.0 credentials
[ "Return", "a", "spreadsheet", "collection", "making", "OAauth", "2", ".", "0", "credentials", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L17-L29
train
38,577
xflr6/gsheets
gsheets/api.py
Sheets.get
def get(self, id_or_url, default=None): """Fetch and return the spreadsheet with the given id or url. Args: id_or_url (str): unique alphanumeric id or URL of the spreadsheet Returns: New SpreadSheet instance or given default if none is found Raises: ValueError: if an URL is given from which no id could be extracted """ if '/' in id_or_url: id = urls.SheetUrl.from_string(id_or_url).id else: id = id_or_url try: return self[id] except KeyError: return default
python
def get(self, id_or_url, default=None): """Fetch and return the spreadsheet with the given id or url. Args: id_or_url (str): unique alphanumeric id or URL of the spreadsheet Returns: New SpreadSheet instance or given default if none is found Raises: ValueError: if an URL is given from which no id could be extracted """ if '/' in id_or_url: id = urls.SheetUrl.from_string(id_or_url).id else: id = id_or_url try: return self[id] except KeyError: return default
[ "def", "get", "(", "self", ",", "id_or_url", ",", "default", "=", "None", ")", ":", "if", "'/'", "in", "id_or_url", ":", "id", "=", "urls", ".", "SheetUrl", ".", "from_string", "(", "id_or_url", ")", ".", "id", "else", ":", "id", "=", "id_or_url", ...
Fetch and return the spreadsheet with the given id or url. Args: id_or_url (str): unique alphanumeric id or URL of the spreadsheet Returns: New SpreadSheet instance or given default if none is found Raises: ValueError: if an URL is given from which no id could be extracted
[ "Fetch", "and", "return", "the", "spreadsheet", "with", "the", "given", "id", "or", "url", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L92-L109
train
38,578
xflr6/gsheets
gsheets/api.py
Sheets.find
def find(self, title): """Fetch and return the first spreadsheet with the given title. Args: title(str): title/name of the spreadsheet to return Returns: SpreadSheet: new SpreadSheet instance Raises: KeyError: if no spreadsheet with the given ``title`` is found """ files = backend.iterfiles(self._drive, name=title) try: return next(self[id] for id, _ in files) except StopIteration: raise KeyError(title)
python
def find(self, title): """Fetch and return the first spreadsheet with the given title. Args: title(str): title/name of the spreadsheet to return Returns: SpreadSheet: new SpreadSheet instance Raises: KeyError: if no spreadsheet with the given ``title`` is found """ files = backend.iterfiles(self._drive, name=title) try: return next(self[id] for id, _ in files) except StopIteration: raise KeyError(title)
[ "def", "find", "(", "self", ",", "title", ")", ":", "files", "=", "backend", ".", "iterfiles", "(", "self", ".", "_drive", ",", "name", "=", "title", ")", "try", ":", "return", "next", "(", "self", "[", "id", "]", "for", "id", ",", "_", "in", "...
Fetch and return the first spreadsheet with the given title. Args: title(str): title/name of the spreadsheet to return Returns: SpreadSheet: new SpreadSheet instance Raises: KeyError: if no spreadsheet with the given ``title`` is found
[ "Fetch", "and", "return", "the", "first", "spreadsheet", "with", "the", "given", "title", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L111-L125
train
38,579
xflr6/gsheets
gsheets/api.py
Sheets.findall
def findall(self, title=None): """Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty) """ if title is None: return list(self) files = backend.iterfiles(self._drive, name=title) return [self[id] for id, _ in files]
python
def findall(self, title=None): """Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty) """ if title is None: return list(self) files = backend.iterfiles(self._drive, name=title) return [self[id] for id, _ in files]
[ "def", "findall", "(", "self", ",", "title", "=", "None", ")", ":", "if", "title", "is", "None", ":", "return", "list", "(", "self", ")", "files", "=", "backend", ".", "iterfiles", "(", "self", ".", "_drive", ",", "name", "=", "title", ")", "return...
Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty)
[ "Fetch", "and", "return", "a", "list", "of", "spreadsheets", "with", "the", "given", "title", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L127-L138
train
38,580
xflr6/gsheets
gsheets/api.py
Sheets.titles
def titles(self, unique=False): """Return a list of all available spreadsheet titles. Args: unique (bool): drop duplicates Returns: list: list of title/name strings """ if unique: return tools.uniqued(title for _, title in self.iterfiles()) return [title for _, title in self.iterfiles()]
python
def titles(self, unique=False): """Return a list of all available spreadsheet titles. Args: unique (bool): drop duplicates Returns: list: list of title/name strings """ if unique: return tools.uniqued(title for _, title in self.iterfiles()) return [title for _, title in self.iterfiles()]
[ "def", "titles", "(", "self", ",", "unique", "=", "False", ")", ":", "if", "unique", ":", "return", "tools", ".", "uniqued", "(", "title", "for", "_", ",", "title", "in", "self", ".", "iterfiles", "(", ")", ")", "return", "[", "title", "for", "_", ...
Return a list of all available spreadsheet titles. Args: unique (bool): drop duplicates Returns: list: list of title/name strings
[ "Return", "a", "list", "of", "all", "available", "spreadsheet", "titles", "." ]
ca4f1273044704e529c1138e3f942836fc496e1b
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/api.py#L156-L166
train
38,581
openstack/python-saharaclient
saharaclient/api/data_sources.py
DataSourceManagerV1.create
def create(self, name, description, data_source_type, url, credential_user=None, credential_pass=None, is_public=None, is_protected=None, s3_credentials=None): """Create a Data Source.""" data = { 'name': name, 'description': description, 'type': data_source_type, 'url': url, } credentials = {} self._copy_if_defined(credentials, user=credential_user, password=credential_pass) credentials = credentials or s3_credentials self._copy_if_defined(data, is_public=is_public, is_protected=is_protected, credentials=credentials) return self._create('/data-sources', data, 'data_source')
python
def create(self, name, description, data_source_type, url, credential_user=None, credential_pass=None, is_public=None, is_protected=None, s3_credentials=None): """Create a Data Source.""" data = { 'name': name, 'description': description, 'type': data_source_type, 'url': url, } credentials = {} self._copy_if_defined(credentials, user=credential_user, password=credential_pass) credentials = credentials or s3_credentials self._copy_if_defined(data, is_public=is_public, is_protected=is_protected, credentials=credentials) return self._create('/data-sources', data, 'data_source')
[ "def", "create", "(", "self", ",", "name", ",", "description", ",", "data_source_type", ",", "url", ",", "credential_user", "=", "None", ",", "credential_pass", "=", "None", ",", "is_public", "=", "None", ",", "is_protected", "=", "None", ",", "s3_credential...
Create a Data Source.
[ "Create", "a", "Data", "Source", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/data_sources.py#L27-L47
train
38,582
openstack/python-saharaclient
saharaclient/api/data_sources.py
DataSourceManagerV1.update
def update(self, data_source_id, update_data): """Update a Data Source. :param dict update_data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * type * url * is_public * is_protected * credentials - dict with the keys `user` and `password` for data source in Swift, or with the keys `accesskey`, `secretkey`, `endpoint`, `ssl`, and `bucket_in_path` for data source in S3 """ if self.version >= 2: UPDATE_FUNC = self._patch else: UPDATE_FUNC = self._update return UPDATE_FUNC('/data-sources/%s' % data_source_id, update_data)
python
def update(self, data_source_id, update_data): """Update a Data Source. :param dict update_data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * type * url * is_public * is_protected * credentials - dict with the keys `user` and `password` for data source in Swift, or with the keys `accesskey`, `secretkey`, `endpoint`, `ssl`, and `bucket_in_path` for data source in S3 """ if self.version >= 2: UPDATE_FUNC = self._patch else: UPDATE_FUNC = self._update return UPDATE_FUNC('/data-sources/%s' % data_source_id, update_data)
[ "def", "update", "(", "self", ",", "data_source_id", ",", "update_data", ")", ":", "if", "self", ".", "version", ">=", "2", ":", "UPDATE_FUNC", "=", "self", ".", "_patch", "else", ":", "UPDATE_FUNC", "=", "self", ".", "_update", "return", "UPDATE_FUNC", ...
Update a Data Source. :param dict update_data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * type * url * is_public * is_protected * credentials - dict with the keys `user` and `password` for data source in Swift, or with the keys `accesskey`, `secretkey`, `endpoint`, `ssl`, and `bucket_in_path` for data source in S3
[ "Update", "a", "Data", "Source", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/data_sources.py#L65-L90
train
38,583
Enteee/pdml2flow
pdml2flow/autovivification.py
getitem_by_path
def getitem_by_path(d, path): """Access item in d using path. a = { 0: { 1: 'item' } } getitem_by_path(a, [0, 1]) == 'item' """ return reduce( lambda d, k: d[k], path, d )
python
def getitem_by_path(d, path): """Access item in d using path. a = { 0: { 1: 'item' } } getitem_by_path(a, [0, 1]) == 'item' """ return reduce( lambda d, k: d[k], path, d )
[ "def", "getitem_by_path", "(", "d", ",", "path", ")", ":", "return", "reduce", "(", "lambda", "d", ",", "k", ":", "d", "[", "k", "]", ",", "path", ",", "d", ")" ]
Access item in d using path. a = { 0: { 1: 'item' } } getitem_by_path(a, [0, 1]) == 'item'
[ "Access", "item", "in", "d", "using", "path", "." ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L7-L17
train
38,584
Enteee/pdml2flow
pdml2flow/autovivification.py
AutoVivification.clean_empty
def clean_empty(self, d=DEFAULT): """Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074 """ if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.clean_empty(v) for v in d) if v or v == 0] elif isinstance(d, type(self)): return type(self)({k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0}) elif isinstance(d, dict): return {k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0} return d
python
def clean_empty(self, d=DEFAULT): """Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074 """ if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.clean_empty(v) for v in d) if v or v == 0] elif isinstance(d, type(self)): return type(self)({k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0}) elif isinstance(d, dict): return {k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0} return d
[ "def", "clean_empty", "(", "self", ",", "d", "=", "DEFAULT", ")", ":", "if", "d", "is", "DEFAULT", ":", "d", "=", "self", "if", "isinstance", "(", "d", ",", "list", ")", ":", "return", "[", "v", "for", "v", "in", "(", "self", ".", "clean_empty", ...
Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074
[ "Returns", "a", "copy", "of", "d", "without", "empty", "leaves", "." ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L21-L34
train
38,585
Enteee/pdml2flow
pdml2flow/autovivification.py
AutoVivification.compress
def compress(self, d=DEFAULT): """Returns a copy of d with compressed leaves.""" if d is DEFAULT: d = self if isinstance(d, list): l = [v for v in (self.compress(v) for v in d)] try: return list(set(l)) except TypeError: # list contains not hashables ret = [] for i in l: if i not in ret: ret.append(i) return ret elif isinstance(d, type(self)): return type(self)({k: v for k, v in ((k, self.compress(v)) for k, v in d.items())}) elif isinstance(d, dict): return {k: v for k, v in ((k, self.compress(v)) for k, v in d.items())} return d
python
def compress(self, d=DEFAULT): """Returns a copy of d with compressed leaves.""" if d is DEFAULT: d = self if isinstance(d, list): l = [v for v in (self.compress(v) for v in d)] try: return list(set(l)) except TypeError: # list contains not hashables ret = [] for i in l: if i not in ret: ret.append(i) return ret elif isinstance(d, type(self)): return type(self)({k: v for k, v in ((k, self.compress(v)) for k, v in d.items())}) elif isinstance(d, dict): return {k: v for k, v in ((k, self.compress(v)) for k, v in d.items())} return d
[ "def", "compress", "(", "self", ",", "d", "=", "DEFAULT", ")", ":", "if", "d", "is", "DEFAULT", ":", "d", "=", "self", "if", "isinstance", "(", "d", ",", "list", ")", ":", "l", "=", "[", "v", "for", "v", "in", "(", "self", ".", "compress", "(...
Returns a copy of d with compressed leaves.
[ "Returns", "a", "copy", "of", "d", "with", "compressed", "leaves", "." ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L36-L55
train
38,586
Enteee/pdml2flow
pdml2flow/autovivification.py
AutoVivification.cast_dicts
def cast_dicts(self, to=DEFAULT, d=DEFAULT): """Returns a copy of d with all dicts casted to the type 'to'.""" if to is DEFAULT: to = type(self) if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.cast_dicts(to, v) for v in d)] elif isinstance(d, dict): return to({k: v for k, v in ((k, self.cast_dicts(to, v)) for k, v in d.items())}) return d
python
def cast_dicts(self, to=DEFAULT, d=DEFAULT): """Returns a copy of d with all dicts casted to the type 'to'.""" if to is DEFAULT: to = type(self) if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.cast_dicts(to, v) for v in d)] elif isinstance(d, dict): return to({k: v for k, v in ((k, self.cast_dicts(to, v)) for k, v in d.items())}) return d
[ "def", "cast_dicts", "(", "self", ",", "to", "=", "DEFAULT", ",", "d", "=", "DEFAULT", ")", ":", "if", "to", "is", "DEFAULT", ":", "to", "=", "type", "(", "self", ")", "if", "d", "is", "DEFAULT", ":", "d", "=", "self", "if", "isinstance", "(", ...
Returns a copy of d with all dicts casted to the type 'to'.
[ "Returns", "a", "copy", "of", "d", "with", "all", "dicts", "casted", "to", "the", "type", "to", "." ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L57-L67
train
38,587
openstack/python-saharaclient
saharaclient/api/job_binaries.py
JobBinariesManagerV1.create
def create(self, name, url, description=None, extra=None, is_public=None, is_protected=None): """Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3 """ data = { "name": name, "url": url } self._copy_if_defined(data, description=description, extra=extra, is_public=is_public, is_protected=is_protected) return self._create('/job-binaries', data, 'job_binary')
python
def create(self, name, url, description=None, extra=None, is_public=None, is_protected=None): """Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3 """ data = { "name": name, "url": url } self._copy_if_defined(data, description=description, extra=extra, is_public=is_public, is_protected=is_protected) return self._create('/job-binaries', data, 'job_binary')
[ "def", "create", "(", "self", ",", "name", ",", "url", ",", "description", "=", "None", ",", "extra", "=", "None", ",", "is_public", "=", "None", ",", "is_protected", "=", "None", ")", ":", "data", "=", "{", "\"name\"", ":", "name", ",", "\"url\"", ...
Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3
[ "Create", "a", "Job", "Binary", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_binaries.py#L27-L45
train
38,588
openstack/python-saharaclient
saharaclient/api/job_binaries.py
JobBinariesManagerV1.get_file
def get_file(self, job_binary_id): """Download a Job Binary.""" resp = self.api.get('/job-binaries/%s/data' % job_binary_id) if resp.status_code != 200: self._raise_api_exception(resp) return resp.content
python
def get_file(self, job_binary_id): """Download a Job Binary.""" resp = self.api.get('/job-binaries/%s/data' % job_binary_id) if resp.status_code != 200: self._raise_api_exception(resp) return resp.content
[ "def", "get_file", "(", "self", ",", "job_binary_id", ")", ":", "resp", "=", "self", ".", "api", ".", "get", "(", "'/job-binaries/%s/data'", "%", "job_binary_id", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "self", ".", "_raise_api_exception", ...
Download a Job Binary.
[ "Download", "a", "Job", "Binary", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_binaries.py#L63-L69
train
38,589
openstack/python-saharaclient
saharaclient/api/job_binaries.py
JobBinariesManagerV1.update
def update(self, job_binary_id, data): """Update Job Binary. :param dict data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * url * is_public * is_protected * extra - dict with the keys `user` and `password` for job binary in Swift, or with the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3 """ if self.version >= 2: UPDATE_FUNC = self._patch else: UPDATE_FUNC = self._update return UPDATE_FUNC( '/job-binaries/%s' % job_binary_id, data, 'job_binary')
python
def update(self, job_binary_id, data): """Update Job Binary. :param dict data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * url * is_public * is_protected * extra - dict with the keys `user` and `password` for job binary in Swift, or with the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3 """ if self.version >= 2: UPDATE_FUNC = self._patch else: UPDATE_FUNC = self._update return UPDATE_FUNC( '/job-binaries/%s' % job_binary_id, data, 'job_binary')
[ "def", "update", "(", "self", ",", "job_binary_id", ",", "data", ")", ":", "if", "self", ".", "version", ">=", "2", ":", "UPDATE_FUNC", "=", "self", ".", "_patch", "else", ":", "UPDATE_FUNC", "=", "self", ".", "_update", "return", "UPDATE_FUNC", "(", "...
Update Job Binary. :param dict data: dict that contains fields that should be updated with new values. Fields that can be updated: * name * description * url * is_public * is_protected * extra - dict with the keys `user` and `password` for job binary in Swift, or with the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3
[ "Update", "Job", "Binary", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_binaries.py#L71-L95
train
38,590
Enteee/pdml2flow
pdml2flow/conf.py
Conf.set
def set(conf): """Applies a configuration to the global config object""" for name, value in conf.items(): if value is not None: setattr(Conf, name.upper(), value)
python
def set(conf): """Applies a configuration to the global config object""" for name, value in conf.items(): if value is not None: setattr(Conf, name.upper(), value)
[ "def", "set", "(", "conf", ")", ":", "for", "name", ",", "value", "in", "conf", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "setattr", "(", "Conf", ",", "name", ".", "upper", "(", ")", ",", "value", ")" ]
Applies a configuration to the global config object
[ "Applies", "a", "configuration", "to", "the", "global", "config", "object" ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/conf.py#L70-L74
train
38,591
Enteee/pdml2flow
pdml2flow/conf.py
Conf.get
def get(): """Gets the configuration as a dict""" return { attr: getattr(Conf, attr) for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__") }
python
def get(): """Gets the configuration as a dict""" return { attr: getattr(Conf, attr) for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__") }
[ "def", "get", "(", ")", ":", "return", "{", "attr", ":", "getattr", "(", "Conf", ",", "attr", ")", "for", "attr", "in", "dir", "(", "Conf", "(", ")", ")", "if", "not", "callable", "(", "getattr", "(", "Conf", ",", "attr", ")", ")", "and", "not"...
Gets the configuration as a dict
[ "Gets", "the", "configuration", "as", "a", "dict" ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/conf.py#L77-L82
train
38,592
Enteee/pdml2flow
pdml2flow/conf.py
Conf.load
def load(description, add_arguments_cb = lambda x: None, postprocess_conf_cb = lambda x: None): """Loads the global Conf object from command line arguments. Encode the next argument after +plugin to ensure that it does not start with a prefix_char """ argparser = ArgumentParser( description = description, prefix_chars = '-+' ) argparser.add_argument( '--version', dest = 'PRINT_VERSION', action = 'store_true', help = 'Print version and exit' ) add_arguments_cb(argparser) # set up plugin argument argparser plugin_argparser = argparser.add_argument_group('Plugins') plugins = {} def load_plugin_group(group): """Load all plugins from the given plugin_group.""" for entry_point in iter_entry_points(group = group): name = str(entry_point).split(' =',1)[0] plugin = entry_point.load() if isclass(plugin) \ and not plugin in Conf.SUPPORTED_PLUGIN_INTERFACES \ and any([ issubclass(plugin, supported_plugin_interface) for supported_plugin_interface in Conf.SUPPORTED_PLUGIN_INTERFACES ]): plugin_argparser.add_argument( '+{}'.format(name), dest = 'PLUGIN_{}'.format(name), type = str, nargs = '?', default = DEFAULT, metavar = 'args'.format(name), help = make_argparse_help_safe( call_plugin( plugin, 'help' ) ) ) # register plugin plugins[name] = plugin else: warning('Plugin not supported: {}'.format(name)) load_plugin_group(Conf.PLUGIN_GROUP_BASE) if Conf.LOAD_PLUGINS: load_plugin_group(Conf.PLUGIN_GROUP) conf = vars( argparser.parse_args([ v if i == 0 or v[0] == '+' or Conf.ARGS[i-1][0] != '+' else b32encode(v.encode()).decode() for i, v in enumerate(Conf.ARGS) ]) ) postprocess_conf_cb(conf) # apply configuration Conf.set(conf) if Conf.PRINT_VERSION: print( 'pdml2flow version {}'.format( Conf.VERSION ), file = Conf.OUT ) sys.exit(0) # initialize plugins Conf.PLUGINS = [] for conf_name, args in conf.items(): if conf_name.startswith('PLUGIN_') and args != DEFAULT: plugin_name = conf_name[7:] Conf.PLUGINS.append( # instantiate plugin plugins[plugin_name]( *split( b32decode(args.encode()).decode() if args is not None else '' ) ) )
python
def load(description, add_arguments_cb = lambda x: None, postprocess_conf_cb = lambda x: None): """Loads the global Conf object from command line arguments. Encode the next argument after +plugin to ensure that it does not start with a prefix_char """ argparser = ArgumentParser( description = description, prefix_chars = '-+' ) argparser.add_argument( '--version', dest = 'PRINT_VERSION', action = 'store_true', help = 'Print version and exit' ) add_arguments_cb(argparser) # set up plugin argument argparser plugin_argparser = argparser.add_argument_group('Plugins') plugins = {} def load_plugin_group(group): """Load all plugins from the given plugin_group.""" for entry_point in iter_entry_points(group = group): name = str(entry_point).split(' =',1)[0] plugin = entry_point.load() if isclass(plugin) \ and not plugin in Conf.SUPPORTED_PLUGIN_INTERFACES \ and any([ issubclass(plugin, supported_plugin_interface) for supported_plugin_interface in Conf.SUPPORTED_PLUGIN_INTERFACES ]): plugin_argparser.add_argument( '+{}'.format(name), dest = 'PLUGIN_{}'.format(name), type = str, nargs = '?', default = DEFAULT, metavar = 'args'.format(name), help = make_argparse_help_safe( call_plugin( plugin, 'help' ) ) ) # register plugin plugins[name] = plugin else: warning('Plugin not supported: {}'.format(name)) load_plugin_group(Conf.PLUGIN_GROUP_BASE) if Conf.LOAD_PLUGINS: load_plugin_group(Conf.PLUGIN_GROUP) conf = vars( argparser.parse_args([ v if i == 0 or v[0] == '+' or Conf.ARGS[i-1][0] != '+' else b32encode(v.encode()).decode() for i, v in enumerate(Conf.ARGS) ]) ) postprocess_conf_cb(conf) # apply configuration Conf.set(conf) if Conf.PRINT_VERSION: print( 'pdml2flow version {}'.format( Conf.VERSION ), file = Conf.OUT ) sys.exit(0) # initialize plugins Conf.PLUGINS = [] for conf_name, args in conf.items(): if conf_name.startswith('PLUGIN_') and args != DEFAULT: plugin_name = conf_name[7:] Conf.PLUGINS.append( # instantiate plugin plugins[plugin_name]( *split( b32decode(args.encode()).decode() if args is not None else '' ) ) )
[ "def", "load", "(", "description", ",", "add_arguments_cb", "=", "lambda", "x", ":", "None", ",", "postprocess_conf_cb", "=", "lambda", "x", ":", "None", ")", ":", "argparser", "=", "ArgumentParser", "(", "description", "=", "description", ",", "prefix_chars",...
Loads the global Conf object from command line arguments. Encode the next argument after +plugin to ensure that it does not start with a prefix_char
[ "Loads", "the", "global", "Conf", "object", "from", "command", "line", "arguments", "." ]
bc9efe379b0b2406bfbbbd8e0f678b1f63805c66
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/conf.py#L85-L180
train
38,593
openstack/python-saharaclient
saharaclient/api/node_group_templates.py
NodeGroupTemplateManagerV2.create
def create(self, name, plugin_name, plugin_version, flavor_id, description=None, volumes_per_node=None, volumes_size=None, node_processes=None, node_configs=None, floating_ip_pool=None, security_groups=None, auto_security_group=None, availability_zone=None, volumes_availability_zone=None, volume_type=None, image_id=None, is_proxy_gateway=None, volume_local_to_instance=None, use_autoconfig=None, shares=None, is_public=None, is_protected=None, volume_mount_prefix=None, boot_from_volume=None, boot_volume_type=None, boot_volume_availability_zone=None, boot_volume_local_to_instance=None): """Create a Node Group Template.""" data = { 'name': name, 'plugin_name': plugin_name, 'plugin_version': plugin_version, 'flavor_id': flavor_id, 'node_processes': node_processes } return self._do_create(data, description, volumes_per_node, volumes_size, node_configs, floating_ip_pool, security_groups, auto_security_group, availability_zone, volumes_availability_zone, volume_type, image_id, is_proxy_gateway, volume_local_to_instance, use_autoconfig, shares, is_public, is_protected, volume_mount_prefix, boot_from_volume, boot_volume_type, boot_volume_availability_zone, boot_volume_local_to_instance)
python
def create(self, name, plugin_name, plugin_version, flavor_id, description=None, volumes_per_node=None, volumes_size=None, node_processes=None, node_configs=None, floating_ip_pool=None, security_groups=None, auto_security_group=None, availability_zone=None, volumes_availability_zone=None, volume_type=None, image_id=None, is_proxy_gateway=None, volume_local_to_instance=None, use_autoconfig=None, shares=None, is_public=None, is_protected=None, volume_mount_prefix=None, boot_from_volume=None, boot_volume_type=None, boot_volume_availability_zone=None, boot_volume_local_to_instance=None): """Create a Node Group Template.""" data = { 'name': name, 'plugin_name': plugin_name, 'plugin_version': plugin_version, 'flavor_id': flavor_id, 'node_processes': node_processes } return self._do_create(data, description, volumes_per_node, volumes_size, node_configs, floating_ip_pool, security_groups, auto_security_group, availability_zone, volumes_availability_zone, volume_type, image_id, is_proxy_gateway, volume_local_to_instance, use_autoconfig, shares, is_public, is_protected, volume_mount_prefix, boot_from_volume, boot_volume_type, boot_volume_availability_zone, boot_volume_local_to_instance)
[ "def", "create", "(", "self", ",", "name", ",", "plugin_name", ",", "plugin_version", ",", "flavor_id", ",", "description", "=", "None", ",", "volumes_per_node", "=", "None", ",", "volumes_size", "=", "None", ",", "node_processes", "=", "None", ",", "node_co...
Create a Node Group Template.
[ "Create", "a", "Node", "Group", "Template", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/node_group_templates.py#L161-L192
train
38,594
openstack/python-saharaclient
saharaclient/api/images.py
_ImageManager.update_image
def update_image(self, image_id, user_name, desc=None): """Create or update an Image in Image Registry.""" desc = desc if desc else '' data = {"username": user_name, "description": desc} return self._post('/images/%s' % image_id, data)
python
def update_image(self, image_id, user_name, desc=None): """Create or update an Image in Image Registry.""" desc = desc if desc else '' data = {"username": user_name, "description": desc} return self._post('/images/%s' % image_id, data)
[ "def", "update_image", "(", "self", ",", "image_id", ",", "user_name", ",", "desc", "=", "None", ")", ":", "desc", "=", "desc", "if", "desc", "else", "''", "data", "=", "{", "\"username\"", ":", "user_name", ",", "\"description\"", ":", "desc", "}", "r...
Create or update an Image in Image Registry.
[ "Create", "or", "update", "an", "Image", "in", "Image", "Registry", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/images.py#L40-L46
train
38,595
openstack/python-saharaclient
saharaclient/api/images.py
ImageManagerV1.update_tags
def update_tags(self, image_id, new_tags): """Update an Image tags. :param new_tags: list of tags that will replace currently assigned tags """ # Do not add :param list in the docstring above until this is solved: # https://github.com/sphinx-doc/sphinx/issues/2549 old_image = self.get(image_id) old_tags = frozenset(old_image.tags) new_tags = frozenset(new_tags) to_add = list(new_tags - old_tags) to_remove = list(old_tags - new_tags) add_response, remove_response = None, None if to_add: add_response = self._post('/images/%s/tag' % image_id, {'tags': to_add}, 'image') if to_remove: remove_response = self._post('/images/%s/untag' % image_id, {'tags': to_remove}, 'image') return remove_response or add_response or self.get(image_id)
python
def update_tags(self, image_id, new_tags): """Update an Image tags. :param new_tags: list of tags that will replace currently assigned tags """ # Do not add :param list in the docstring above until this is solved: # https://github.com/sphinx-doc/sphinx/issues/2549 old_image = self.get(image_id) old_tags = frozenset(old_image.tags) new_tags = frozenset(new_tags) to_add = list(new_tags - old_tags) to_remove = list(old_tags - new_tags) add_response, remove_response = None, None if to_add: add_response = self._post('/images/%s/tag' % image_id, {'tags': to_add}, 'image') if to_remove: remove_response = self._post('/images/%s/untag' % image_id, {'tags': to_remove}, 'image') return remove_response or add_response or self.get(image_id)
[ "def", "update_tags", "(", "self", ",", "image_id", ",", "new_tags", ")", ":", "# Do not add :param list in the docstring above until this is solved:", "# https://github.com/sphinx-doc/sphinx/issues/2549", "old_image", "=", "self", ".", "get", "(", "image_id", ")", "old_tags"...
Update an Image tags. :param new_tags: list of tags that will replace currently assigned tags
[ "Update", "an", "Image", "tags", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/images.py#L50-L76
train
38,596
openstack/python-saharaclient
saharaclient/osc/plugin.py
build_option_parser
def build_option_parser(parser): """Hook to add global options.""" parser.add_argument( "--os-data-processing-api-version", metavar="<data-processing-api-version>", default=utils.env( 'OS_DATA_PROCESSING_API_VERSION', default=DEFAULT_DATA_PROCESSING_API_VERSION), help=("Data processing API version, default=" + DEFAULT_DATA_PROCESSING_API_VERSION + ' (Env: OS_DATA_PROCESSING_API_VERSION)')) parser.add_argument( "--os-data-processing-url", default=utils.env( "OS_DATA_PROCESSING_URL"), help=("Data processing API URL, " "(Env: OS_DATA_PROCESSING_API_URL)")) return parser
python
def build_option_parser(parser): """Hook to add global options.""" parser.add_argument( "--os-data-processing-api-version", metavar="<data-processing-api-version>", default=utils.env( 'OS_DATA_PROCESSING_API_VERSION', default=DEFAULT_DATA_PROCESSING_API_VERSION), help=("Data processing API version, default=" + DEFAULT_DATA_PROCESSING_API_VERSION + ' (Env: OS_DATA_PROCESSING_API_VERSION)')) parser.add_argument( "--os-data-processing-url", default=utils.env( "OS_DATA_PROCESSING_URL"), help=("Data processing API URL, " "(Env: OS_DATA_PROCESSING_API_URL)")) return parser
[ "def", "build_option_parser", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "\"--os-data-processing-api-version\"", ",", "metavar", "=", "\"<data-processing-api-version>\"", ",", "default", "=", "utils", ".", "env", "(", "'OS_DATA_PROCESSING_API_VERSION'", ...
Hook to add global options.
[ "Hook", "to", "add", "global", "options", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/osc/plugin.py#L51-L68
train
38,597
openstack/python-saharaclient
saharaclient/api/cluster_templates.py
ClusterTemplateManagerV1.create
def create(self, name, plugin_name, hadoop_version, description=None, cluster_configs=None, node_groups=None, anti_affinity=None, net_id=None, default_image_id=None, use_autoconfig=None, shares=None, is_public=None, is_protected=None, domain_name=None): """Create a Cluster Template.""" data = { 'name': name, 'plugin_name': plugin_name, 'hadoop_version': hadoop_version, } return self._do_create(data, description, cluster_configs, node_groups, anti_affinity, net_id, default_image_id, use_autoconfig, shares, is_public, is_protected, domain_name)
python
def create(self, name, plugin_name, hadoop_version, description=None, cluster_configs=None, node_groups=None, anti_affinity=None, net_id=None, default_image_id=None, use_autoconfig=None, shares=None, is_public=None, is_protected=None, domain_name=None): """Create a Cluster Template.""" data = { 'name': name, 'plugin_name': plugin_name, 'hadoop_version': hadoop_version, } return self._do_create(data, description, cluster_configs, node_groups, anti_affinity, net_id, default_image_id, use_autoconfig, shares, is_public, is_protected, domain_name)
[ "def", "create", "(", "self", ",", "name", ",", "plugin_name", ",", "hadoop_version", ",", "description", "=", "None", ",", "cluster_configs", "=", "None", ",", "node_groups", "=", "None", ",", "anti_affinity", "=", "None", ",", "net_id", "=", "None", ",",...
Create a Cluster Template.
[ "Create", "a", "Cluster", "Template", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/cluster_templates.py#L27-L43
train
38,598
openstack/python-saharaclient
saharaclient/api/cluster_templates.py
ClusterTemplateManagerV2.update
def update(self, cluster_template_id, name=NotUpdated, plugin_name=NotUpdated, plugin_version=NotUpdated, description=NotUpdated, cluster_configs=NotUpdated, node_groups=NotUpdated, anti_affinity=NotUpdated, net_id=NotUpdated, default_image_id=NotUpdated, use_autoconfig=NotUpdated, shares=NotUpdated, is_public=NotUpdated, is_protected=NotUpdated, domain_name=NotUpdated): """Update a Cluster Template.""" data = {} self._copy_if_updated(data, name=name, plugin_name=plugin_name, plugin_version=plugin_version, description=description, cluster_configs=cluster_configs, node_groups=node_groups, anti_affinity=anti_affinity, neutron_management_network=net_id, default_image_id=default_image_id, use_autoconfig=use_autoconfig, shares=shares, is_public=is_public, is_protected=is_protected, domain_name=domain_name) return self._patch('/cluster-templates/%s' % cluster_template_id, data, 'cluster_template')
python
def update(self, cluster_template_id, name=NotUpdated, plugin_name=NotUpdated, plugin_version=NotUpdated, description=NotUpdated, cluster_configs=NotUpdated, node_groups=NotUpdated, anti_affinity=NotUpdated, net_id=NotUpdated, default_image_id=NotUpdated, use_autoconfig=NotUpdated, shares=NotUpdated, is_public=NotUpdated, is_protected=NotUpdated, domain_name=NotUpdated): """Update a Cluster Template.""" data = {} self._copy_if_updated(data, name=name, plugin_name=plugin_name, plugin_version=plugin_version, description=description, cluster_configs=cluster_configs, node_groups=node_groups, anti_affinity=anti_affinity, neutron_management_network=net_id, default_image_id=default_image_id, use_autoconfig=use_autoconfig, shares=shares, is_public=is_public, is_protected=is_protected, domain_name=domain_name) return self._patch('/cluster-templates/%s' % cluster_template_id, data, 'cluster_template')
[ "def", "update", "(", "self", ",", "cluster_template_id", ",", "name", "=", "NotUpdated", ",", "plugin_name", "=", "NotUpdated", ",", "plugin_version", "=", "NotUpdated", ",", "description", "=", "NotUpdated", ",", "cluster_configs", "=", "NotUpdated", ",", "nod...
Update a Cluster Template.
[ "Update", "a", "Cluster", "Template", "." ]
c53831d686d9e94187ce5dfdbfa43883b792280e
https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/cluster_templates.py#L136-L163
train
38,599