code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not self._apikey or not self._secret: raise PoloniexCredentialsException('missing apikey/secret') with self.nonce_lock: params.update({'command': command, 'nonce': next(self.nonce_iter)}) response = self.session.post( self._private_url, da...
def _private(self, command, **params)
Invoke the 'command' public API with optional params.
4.823817
4.603068
1.047957
return self._private('returnDepositsWithdrawals', start=start, end=end)
def returnDepositsWithdrawals(self, start=0, end=2**32-1)
Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.
4.419915
6.205903
0.712211
return self._private('returnTradeHistory', currencyPair=currencyPair, start=start, end=end, limit=limit)
def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500)
Returns your trade history for a given market, specified by the "currencyPair" POST parameter. You may specify "all" as the currencyPair to receive your trade history for all markets. You may optionally specify a range via "start" and/or "end" POST parameters, given in UNIX timestamp for...
3.069577
3.436397
0.893254
return super(Poloniex, self).returnTradeHistory(currencyPair, start, end)
def returnTradeHistoryPublic(self, currencyPair, start=None, end=None)
Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.
4.209635
5.690827
0.739723
return self._private('buy', currencyPair=currencyPair, rate=rate, amount=amount, fillOrKill=fillOrKill, immediateOrCancel=immediateOrCancel, postOnly=postOnly)
def buy(self, currencyPair, rate, amount, fillOrKill=None, immediateOrCancel=None, postOnly=None)
Places a limit buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. You may optionally set "fillOrKill", "immediateOrCancel", "postOnly" to 1. A fill-or-kill order will either fill in its e...
1.979539
2.359878
0.838831
return self._private('moveOrder', orderNumber=orderNumber, rate=rate, amount=amount, postOnly=postOnly, immediateOrCancel=immediateOrCancel)
def moveOrder(self, orderNumber, rate, amount=None, postOnly=None, immediateOrCancel=None)
Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "orderNumber" and "rate"; you may optionally specify "amount" if you wish to change the amount of the new ...
2.481347
2.699249
0.919273
return self._private('withdraw', currency=currency, amount=amount, address=address, paymentId=paymentId)
def withdraw(self, currency, amount, address, paymentId=None)
Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". For XMR withdrawals, you may optionally specify "pay...
3.711507
3.948267
0.940034
return self._private('transferBalance', currency=currency, amount=amount, fromAccount=fromAccount, toAccount=toAccount)
def transferBalance(self, currency, amount, fromAccount, toAccount)
Transfers funds from one account to another (e.g. from your exchange account to your margin account). Required POST parameters are "currency", "amount", "fromAccount", and "toAccount".
3.601743
3.659622
0.984184
return self._private('marginBuy', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
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 result...
3.238556
3.289639
0.984472
return self._private('marginSell', currencyPair=currencyPair, rate=rate, amount=amount, lendingRate=lendingRate)
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.
3.219036
3.318059
0.970156
return self._private('createLoanOffer', currency=currency, amount=amount, duration=duration, autoRenew=autoRenew, lendingRate=lendingRate)
def createLoanOffer(self, currency, amount, duration, autoRenew, lendingRate)
Creates a loan offer for a given currency. Required POST parameters are "currency", "amount", "duration", "autoRenew" (0 or 1), and "lendingRate".
2.571611
2.985174
0.861461
return self._private('returnLendingHistory', start=start, end=end, limit=limit)
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.
4.850216
5.694941
0.851671
cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = str(uuid.uuid4()) set_cid(cid) return cid
def get_cid()
Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)` We want the simplest thing here and let `genera...
3.869093
2.12864
1.817636
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())) re...
def generate_new_cid(upstream_cid=None)
Generate a new correlation id, possibly based on the given one.
3.314572
3.191466
1.038573
try: # Nod to tastypie's use of importlib. parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = "Coul...
def import_from_string(val, setting_name)
Attempt to import a class from a string representation.
2.701828
2.540163
1.063644
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)
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.
7.860748
7.07409
1.111203
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)
OID .1.3.6.1.2.1.33.1.3.3.1.2.1 MIB excerpt The present input frequency.
6.023959
6.55393
0.919137
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)
OID .1.3.6.1.2.1.33.1.4.4.1.3.1 MIB excerpt The present output current.
5.969111
6.246923
0.955528
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)
OID .1.3.6.1.2.1.33.1.6.1.0 MIB excerpt The present number of active alarm conditions.
5.28747
4.511717
1.171942
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)
OID .1.3.6.1.4.1.534.1.2.4.0 MIB Excerpt Battery percent charge.
8.644216
8.859332
0.975719
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)
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.
7.375834
7.417946
0.994323
# 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 R...
def check_ressources(sess)
check the Ressources of the Fortinet Controller all thresholds are currently hard coded. should be fine.
2.398872
2.277704
1.053197
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...
def check_controller(sess)
check the status of the controller
2.28375
2.282917
1.000365
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 =...
def check_accesspoints(sess)
check the status of all connected access points
2.481285
2.466954
1.005809
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, "{} '{}': ...
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
2.850653
2.296528
1.241288
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, "{} '{}': {}"...
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
2.775318
2.233126
1.242795
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_typ...
def add_device_information(helper, session)
add general device information to summary
3.24882
3.068274
1.058843
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(...
def process_status(self, helper, session, check)
process a single status
4.157546
4.101896
1.013567
snmp_result_status = helper.walk_snmp_values(session, helper, DEVICE_STATES_OIDS["oid_" + check], check) snmp_result_names = helper.walk_snmp_values(session, helper, ...
def process_states(self, helper, session, check)
process status values from a table
2.634996
2.617748
1.006589
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_TEMPERATU...
def process_temperature_sensors(helper, session)
process the temperature sensors
3.132464
3.096251
1.011696
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format( drivename, DISK_STATES[int(drivestatus)]["result"])
def check_drives(drivename, drivestatus)
check the drive status
9.702594
9.505945
1.020687
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"], "Power unit '{}' redundancy: {}".format(power_unit_name_data, POWER_UNIT_REDUNDANCY_STATE[ ...
def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data)
check the status of the power units
4.671419
4.35201
1.073393
# only check the status, if the "no" flag is not set if flag: # get the data via snmp myData = get_data(sess, oid, helper) data_summary_output, data_long_output = state_summary(myData, name, normal_state, helper) add_output(data_summary_output, data_long_output, helper)
def check_global_status(flag, name, oid)
check a global status check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0')
9.321136
8.721627
1.068738
if power_state_flag: power_state = get_data(sess, oid_power_state, helper) power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power', server_power_state, helper, server_power_state[3]) add_output(power_state_summary_output, power_state_long_output, ...
def check_server_power()
Check if the server is powered on Skip this check, if the --noPowerState is set
6.371577
6.021426
1.058151
if ctrl_flag: ctrl = walk_data(sess, oid_ctrl, helper)[0] for x, data in enumerate(ctrl, 1): ctrl_summary_output, ctrl_long_output = state_summary(data, 'Controller %d' % x, normal_state, helper) add_output(ctrl_summary_output, ctrl_long_output, helper)
def check_storage_controllers()
Check the status of the storage controllers Skip this check, if --noController is set
10.537853
10.119424
1.041349
# 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 i...
def check_temperature_sensors()
Check all temperature sensors of the server All sensors with the value or threshold is -99 or 0 are ignored
6.301178
5.787725
1.088714
# human readable status hr_status = normal_state[int(state)] if hr_status != "ok": # if the power supply is ok, we will set a critical status and add it to the summary helper.add_summary('Power supply status %s: %s' % (x, hr_status)) h...
def check_ps(): if int(input_pwr_sply) != 0: ps_data = walk_data(sess, oid_ps, helper)[0] ps_ok_count = 0 for x, state in enumerate(ps_data, 1)
Check if the power supplies are ok, and we have the configured amount The check is skipped if --ps=0
4.635969
4.448979
1.04203
# skip the check if --noPowerRedundancy is set if power_redundancy_flag: # walk the data ps_redundant_data = walk_data(sess, oid_ps_redundant, helper)[0] for x, state in enumerate(ps_redundant_data, 1): # human readable status hr_status = ps_...
def check_power_redundancy()
Check if the power supplies are redundant The check is skipped if --noPowerRedundancy is set
6.867061
6.090133
1.127572
# 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...
def check_fan(input_fan)
check the fans
6.607224
6.502388
1.016123
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(...
def get_snmp_from_host1(self)
Get SNMP values from 1st host.
2.834059
2.727268
1.039157
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)
Get SNMP values from 2nd host.
7.828594
6.977427
1.121989
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 ...
def check(self)
Evaluate health status from device parameters.
1.934983
1.899736
1.018554
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(stat...
def update_status(self, helper, status)
update the helper
3.999428
3.931042
1.017396
snmp_result = sess.get_oids(oid)[0] if snmp_result is None: helper.exit(summary="No response from device for oid " + oid, exit_code=unknown, perfdata='') else: return snmp_result
def get_snmp_value(sess, helper, oid)
return a snmp value or exits the plugin with unknown
8.030851
7.353323
1.092139
try: snmp_walk = sess.walk_oid(oid) result_list = [] for x in range(len(snmp_walk)): result_list.append(snmp_walk[x].val) if result_list != []: return result_list else: raise SnmpException("No...
def walk_snmp_values(sess, helper, oid, check)
return a snmp value or exits the plugin with unknown
5.468391
5.252662
1.04107
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)
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.
5.227837
5.183191
1.008614
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()
show all available partitions
31.273645
27.236437
1.148228
# if we want to have a linux partition (/) we use the full path (startswith "/" would result in / /var /dev etc). # if we start with something else, we use the startswith function if "/" in partition: use_fullcompare = True else: use_fullcompare = False if ...
def partition_found(partition, description)
returns True, if the partition (--partition) is in the description we received from the host
8.537322
7.83147
1.09013
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...
def check_partition()
check the defined partition
5.326064
5.319936
1.001152
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 th...
def check_sensors()
collect and check all available sensors
8.626835
8.449339
1.021007
apc_battery_states = { '1' : 'unknown', '2' : 'batteryNormal', '3' : 'batteryLow', '4' : 'batteryInFaultCondition' } a_state = apc_battery_states.get(the_snmp_value, 'unknown') if the_snmp_value == '2': the_helper.add_status(pynag.Plugins.ok) elif t...
def check_basic_battery_status(the_session, the_helper, the_snmp_value)
OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0 MIB Excerpt The status of the UPS batteries. A batteryLow(3) value indicates the UPS will be unable to sustain the current load, and its services will be lost if power is not restored. The amount of run time in reserve at the time of low battery can be c...
3.367209
2.550884
1.320016
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.se...
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
5.004765
5.110333
0.979342
apc_states = { '1' : 'Battery does not need to be replaced', '2' : 'Battery needs to be replaced!'} a_state = apc_states.get(the_snmp_value, "Unknown battery replacement state!") if the_snmp_value == '1': the_helper.add_status(pynag.Plugins.ok) else: the_helper.add...
def check_battery_replace_indicator(the_session, the_helper, the_snmp_value)
OID .1.3.6.1.4.1.318.1.1.1.2.2.4.0 MIB Excerpt Indicates whether the UPS batteries need replacing. Value List noBatteryNeedsReplacing (1) batteryNeedsReplacing (2)
4.692577
4.211464
1.114239
a_snmp_unit = snmpSessionBaseClass.get_data( the_session, apc_oid_environment_temperature_unit, the_helper) snmp_units = { '1' : 'C', '2' : 'F' } a_unit = snmp_units.get(a_snmp_unit, 'UNKNOWN_UNIT') the_helper.add_metric( label=the_helper.op...
def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1)
OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1 MIB Excerpt The current temperature reading from the probe displayed in the units shown in the 'iemStatusProbeTempUnits' OID (Celsius or Fahrenheit). Description of unit OID OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.5 The temperature scale used to display t...
4.301061
4.691186
0.916839
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)
check if typ parameter is TCP or UDP
21.87722
16.353886
1.337738
try: int(port) except ValueError: helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='')
def check_port(helper, port)
check if the port parameter is really a port or "scan"
20.149775
15.656949
1.286954
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() ...
def check_udp(helper, host, port, session)
the check logic for UDP ports
8.97002
8.734875
1.02692
# 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", "1...
def check_tcp(helper, host, port, warning_param, critical_param, session)
the check logic for check TCP ports
3.608452
3.578121
1.008477
i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
def to_json(obj)
Return a json string representing the python object obj.
4.915572
4.170927
1.178532
"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(...
def get_data(self)
Get SNMP values from host
4.090848
3.461751
1.181728
"Build list with active alarms" self.active_alarms = [] for i in range(0, len(self.models[self.modem_type]['alarms'])): if bool(int(snmp_data[i])) == True: self.active_alarms.append(self.models[self.modem_type]['alarms'][i])
def process_alarms(self, snmp_data)
Build list with active alarms
3.442329
2.90268
1.185914
"Build list with metrics" self.metrics = {} for i in range(0, len(snmp_data)): metric_id = self.models[self.modem_type]['metrics'][i] value = int(snmp_data[i]) self.metrics[metric_id] = value
def process_metrics(self, snmp_data)
Build list with metrics
4.763526
3.934083
1.210835
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)
calculate the correct OID for the service name
4.71648
4.309472
1.094445
"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...
def get_data(self)
Return one SNMP response list for all status OIDs, and one list for all metric OIDs.
4.610816
2.960561
1.557413
"Build list with active alarms" self.active_alarms = {} for i in range(0, len(self.models[self.modem_type]['alarms'])): mib_name = self.models[self.modem_type]['alarms'][i] conv = status_mib[mib_name]['conv'] self.active_alarms[mib_name] = conv(snmp_data[i])
def process_alarms(self, snmp_data)
Build list with active alarms
4.218602
3.696186
1.141339
"Build list with metrics" self.metrics = {} for i in range(0, len(snmp_data)): mib_name = self.models[self.modem_type]['metrics'][i] conv = metric_mib[mib_name]['conv'] self.metrics[mib_name] = conv(snmp_data[i])
def process_metrics(self, snmp_data)
Build list with metrics
5.463266
4.64543
1.176052
return str(float(value) / math.pow(10, float(digit)))
def real_value(value, digit)
function to calculate the real value we need to devide the value by the digit e.g. value = 100 digit = 2 return: "1.0"
5.424316
5.388329
1.006679
# 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(s...
def check_inlet(self, helper)
check the Inlets of Raritan PDUs
3.015291
2.964131
1.01726
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...
def check_outlet(self, helper)
check the status of the specified outlet
7.127317
6.917686
1.030304
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...
def check_sensor(self, helper)
check the status of the specified sensor
3.03639
3.031094
1.001747
os.dup2(dev_null, sys.stdout.fileno()) return_object = func(*a, **kwargs) sys.stdout.flush() os.dup2(tmp_stdout, sys.stdout.fileno()) return return_object
def dev_null_wrapper(func, *a, **kwargs)
Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null. This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases.
2.532971
2.372957
1.067432
# translate the value (integer) we receive to a human readable value (e.g. ok, critical etc.) with the given state_list state_value = state_list[int(value)] summary_output = '' long_output = '' if not info: info = '' if state_value != ok_value: summary_output += ('%s sta...
def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None)
Always add the status to the long output, and if the status is not ok (or ok_value), we show it in the summary and set the status to critical
4.776985
4.154297
1.14989
if summary_output != '': helper.add_summary(summary_output) helper.add_long_output(long_output)
def add_output(summary_output, long_output, helper)
if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report
2.955859
2.406068
1.228502
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)
just print the current GPS position
6.549944
6.215285
1.053845
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.o...
def process_status(self, helper, sess, check)
get the snmp value, check the status and update the helper
3.507588
3.118188
1.12488
# 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 ...
def check_ntp_status(self, ntp_status_int)
check the NTP status
5.840716
5.755957
1.014725
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 ...
def check_gps_status(self, gps_status_int)
check the GPS status
6.510482
6.383772
1.019849
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_s...
def process_satellites(self, helper, sess)
check and show the good satellites
8.603396
7.307813
1.177287
password = self.selenium.find_element(*self._password_input_locator) password.clear() password.send_keys(value)
def login_password(self, value)
Set the value of the login password field.
3.452539
3.031427
1.138915
email = self.wait.until(expected.visibility_of_element_located( self._email_input_locator)) email.clear() email.send_keys(value)
def email(self, value)
Set the value of the email field.
4.489799
3.923407
1.144362
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)
Signs in using the specified email address and password.
3.548126
3.476602
1.020573
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)
Signs in a user, either with the specified email address and password, or a returning user.
3.701967
3.452035
1.072401
csvwriter = csv.writer(fileobj, dialect=dialect) csv_writerows(csvwriter, rows, encoding)
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT)
Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.
3.50222
4.324467
0.809862
global pandas if pandas is None: # pragma: no cover import pandas with contextlib.closing(CsvBuffer()) as fd: write_csv(fd, rows, encoding, dialect) fd.seek(0) df = read_csv(pandas, fd, encoding, dialect, kwargs) return df
def write_dataframe(rows, encoding=ENCODING, dialect=DIALECT, **kwargs)
Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``.
4.634285
4.418762
1.048775
ma = cls._pattern.search(link) if ma is None: raise ValueError(link) id = ma.group('id') return cls(id)
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>
4.444136
6.032089
0.736749
def decorator(func): func.__doc__ = func.__doc__ % tuple(args) return func return decorator
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.'
3.761762
5.847863
0.643271
result = collections.defaultdict(list) for i in items: key = keyfunc(i) result[key].append(i) return result
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'])]
2.150496
3.208002
0.670354
seen = set() return [item for item in iterable if item not in seen and not seen.add(item)]
def uniqued(iterable)
Return unique list of ``iterable`` items preserving order. >>> uniqued('spameggs') ['s', 'p', 'a', 'm', 'e', 'g']
2.240298
3.383788
0.662068
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)
Return a service endpoint for interacting with a Google API.
5.937461
4.730668
1.2551
params = {'orderBy': order, 'pageToken': None} q = [] if name is not None: q.append("name='%s'" % name) if mimeType is not None: q.append("mimeType='%s'" % mimeType) if q: params['q'] = ' and '.join(q) while True: response = service.files().list(**params).ex...
def iterfiles(service, name=None, mimeType=SHEET, order=FILEORDER)
Fetch and yield ``(id, name)`` pairs for Google drive files.
1.855214
1.79126
1.035703
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)
Fetch and return spreadsheet meta data with Google sheets API.
2.257386
2.21271
1.020191
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)
Fetch and return spreadsheet cell values with Google sheets API.
3.08274
2.317926
1.329956
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 = ...
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...
2.204759
2.223904
0.991391
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)
Return default or predefined URLs from keyword, pass through ``scope``.
4.221542
3.352852
1.25909
''' 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...
def search_all(self, limit=50, format='json')
Returns a single list containing up to 'limit' Result objects
3.404618
2.820013
1.207306
''' 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: ...
def _search(self, limit, format)
Returns a list of result objects, with the url for the next page bing search url.
4.396599
3.414553
1.287606
return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s)))
def base26int(s, _start=1 - ord('A'))
Return string ``s`` as ``int`` in bijective base26 notation. >>> base26int('SPAM') 344799
3.216736
5.678343
0.566492
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)
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'
2.225719
2.89698
0.768289
try: return _match(coord).groups() except AttributeError: raise ValueError(coord)
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...
4.085256
7.091166
0.576105
try: return _map[col.upper()] except KeyError: raise ValueError(col)
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
3.720353
7.114764
0.522906