INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the left and right part of the import. | def split_fqn(fqn):
"""
Returns the left and right part of the import.
``fqn`` can be either a string of the form ``appname.modulename.ClassName``
or a function that returns such a string.
"""
if hasattr(fqn, '__call__'):
fqn_string = fqn()
else:
fqn_string = fqn
return... |
小组信息 | def info(self):
"""小组信息
:return: 小组信息
:rtype: dict
返回值示例 ::
{
'title': u'title', # 标题
'leader': u'leader', # 组长
'date_created': datetime.datetime(2013, 10, 6, 0, 0), # 创建日期
'rank': 1000, # 排名
'number':... |
更新成员加入条件 | def update_limit(self, days, kind=2, condition='>='):
"""更新成员加入条件
:rtype: bool
"""
url = 'http://www.shanbay.com/team/setqualification/%s' % self.team_id
data = {
'kind': kind,
'condition': condition,
'value': days,
'team': self.te... |
获取小组所有成员的信息列表 | def members(self):
"""获取小组所有成员的信息列表"""
all_members = []
for page in range(1, self.max_page() + 1):
all_members.extend(self.single_page_members(page))
return all_members |
获取小组成员管理页面的最大页数 | def max_page(self):
"""获取小组成员管理页面的最大页数"""
html = self.request(self.dismiss_url).text
soup = BeautifulSoup(html)
# 分页所在 div
try:
pagination = soup.find_all(class_='pagination')[0]
except IndexError as e:
logger.exception(e)
return 1
... |
获取单个页面内的小组成员信息 | def single_page_members(self, page_number=1):
"""获取单个页面内的小组成员信息
:param page_number: 页码
:return: 包含小组成员信息的列表
返回值示例: ::
[{
'id': 123, # member_id
'username': 'jim', # username
'nickname': 'Jim', ... |
踢人. 注意别把自己给踢了. | def dismiss(self, member_ids):
"""踢人. 注意别把自己给踢了.
:param member_ids: 组员 ids
:return: bool
"""
url = 'http://www.shanbay.com/api/v1/team/member/'
data = {
'action': 'dispel',
}
if isinstance(member_ids, (list, tuple)):
data['ids'] = ... |
小组发帖要用的 forum_id | def forum_id(self):
"""小组发帖要用的 forum_id"""
html = self.request(self.team_url).text
soup = BeautifulSoup(html)
return soup.find(id='forum_id').attrs['value'] |
小组发贴 | def new_topic(self, title, content):
"""小组发贴
:return: 帖子 id 或 ``None``
"""
data = {
'title': title,
'body': content,
'csrfmiddlewaretoken': self._request.cookies.get('csrftoken')
}
url = 'http://www.shanbay.com/api/v1/forum/%s/thread/'... |
小组回帖 | def reply_topic(self, topic_id, content):
"""小组回帖
:return: 帖子 id 或 ``None``
"""
data = {
'body': content,
'csrfmiddlewaretoken': self._request.cookies.get('csrftoken')
}
url = 'http://www.shanbay.com/api/v1/forum/thread/%s/post/' % topic_id
... |
Connects to the server. | def connect(self, origin=None):
"""
Connects to the server.
:param origin: (Optional) The origin.
"""
self.logger.debug('Establish connection...')
if self.connected:
self.logger.warning('Connection already established. Return...')
return
... |
Closes the connection. | def disconnect(self):
"""
Closes the connection.
"""
self.logger.debug('Close connection...')
self.auto_reconnect = False
if self.websocket is not None:
self.websocket.close() |
Sends data to the server. | def send(self, data):
"""
Sends data to the server.
"""
self.logger.debug('Send data: {}'.format(data))
if not self.connected:
self.logger.warning('Connection not established. Return...')
return
self.websocket.send(json.dumps(data)) |
Called aways when a message arrives. | def _on_message(self, socket, message):
"""
Called aways when a message arrives.
"""
data = json.loads(message)
message_type = None
identifier = None
subscription = None
if 'type' in data:
message_type = data['type']
if 'identifier' i... |
Called when the connection was closed. | def _on_close(self, socket):
"""
Called when the connection was closed.
"""
self.logger.debug('Connection closed.')
for subscription in self.subscriptions.values():
if subscription.state == 'subscribed':
subscription.state = 'connection_pending' |
If connected to server. | def connected(self):
"""
If connected to server.
"""
return self.websocket is not None and \
self.websocket.sock is not None and \
self.websocket.sock.connected |
Finds a subscription by it s identifier. | def find_subscription(self, identifier):
"""
Finds a subscription
by it's identifier.
"""
for subscription in self.subscriptions.values():
if subscription.identifier == identifier:
return subscription |
Subscribes at the server. | def create(self):
"""
Subscribes at the server.
"""
self.logger.debug('Create subscription on server...')
if not self.connection.connected:
self.state = 'connection_pending'
return
data = {
'command': 'subscribe',
'identif... |
Removes the subscription. | def remove(self):
"""
Removes the subscription.
"""
self.logger.debug('Remove subscription from server...')
data = {
'command': 'unsubscribe',
'identifier': self._identifier_string()
}
self.connection.send(data)
self.state = 'unsu... |
Sends data to the server on the subscription channel. | def send(self, message):
"""
Sends data to the server on the
subscription channel.
:param data: The JSON data to send.
"""
self.logger.debug('Send message: {}'.format(message))
if self.state == 'pending' or self.state == 'connection_pending':
self.lo... |
API for the connection to forward information to this subscription instance. | def received(self, data):
"""
API for the connection to forward
information to this subscription instance.
:param data: The JSON data which was received.
:type data: Message
"""
self.logger.debug('Data received: {}'.format(data))
message_type = None
... |
Called when the subscription was accepted successfully. | def _subscribed(self):
"""
Called when the subscription was
accepted successfully.
"""
self.logger.debug('Subscription confirmed.')
self.state = 'subscribed'
for message in self.message_queue:
self.send(message) |
Handle the command line options | def cli_opts():
""" Handle the command line options """
parser = argparse.ArgumentParser()
parser.add_argument(
"--homeassistant-config",
type=str,
required=False,
dest="config",
help="Create configuration section for home assistant",)
parser.add_argument(
... |
Register signal handlers | def _setup_signal_handler(self):
""" Register signal handlers """
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGQUIT, self._signal_handler) |
Method called when handling signals | def _signal_handler(self, signum, frame):
""" Method called when handling signals """
if self._options.config:
with open(self._options.config, "w") as cfg:
yaml.dump(self._home_assistant_config(), cfg)
print(
"Dumped home assistant configur... |
Monitor the bus for events and handle them | def start(self):
""" Monitor the bus for events and handle them """
print("Entering monitoring mode, press CTRL-C to quit")
serial = self._connection.serial
while True:
serial.write(b"@R")
length = int(serial.read(), 16)
data = serial.read(length * 2)... |
Add device to the list of known ones | def _add_device(self, scs_id, ha_id, name):
""" Add device to the list of known ones """
if scs_id in self._devices:
return
self._devices[scs_id] = {
'name': name,
'ha_id': ha_id
} |
Creates home assistant configuration for the known devices | def _home_assistant_config(self):
""" Creates home assistant configuration for the known devices """
devices = {}
for scs_id, dev in self._devices.items():
devices[dev['ha_id']] = {
'name': dev['name'],
'scs_id': scs_id}
return {'devices': dev... |
Load the filter file and populates self. _devices accordingly | def _load_filter(self, config):
""" Load the filter file and populates self._devices accordingly """
path = pathlib.Path(config)
if not path.is_file():
return
with open(config, 'r') as conf:
devices = yaml.load(conf)['devices']
for ha_id, dev in devic... |
Closes the connection to the serial port and ensure no pending operatoin are left | def close(self):
""" Closes the connection to the serial port and ensure no pending
operatoin are left """
self._serial.write(b"@c")
self._serial.read()
self._serial.close() |
Load a value converting it to the proper type if validation_type exists. | def load(self, value):
"""Load a value, converting it to the proper type if validation_type exists."""
if self.property_type is None:
return value
elif not isinstance(self.property_type, BaseType):
raise TypeError('property_type must be schematics BaseType')
else:... |
Iterate over all ConfigProperty attributes yielding ( attr_name config_property ) | def _iter_config_props(cls):
"""Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """
props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty))
for attr_name, config_prop in props:
yield attr_name, config_prop |
Set unspecified property_keys for each ConfigProperty to the name of the class attr | def _update_property_keys(cls):
"""Set unspecified property_keys for each ConfigProperty to the name of the class attr"""
for attr_name, config_prop in cls._iter_config_props():
if config_prop.property_key is None:
config_prop.property_key = attr_name |
Set instance property to a value and add it varz if needed | def _set_instance_prop(self, attr_name, config_prop, value):
"""Set instance property to a value and add it varz if needed"""
setattr(self, attr_name, value)
# add to varz if it is not private
if not config_prop.exclude_from_varz:
self.varz[attr_name] = value |
Load values for all ConfigProperty attributes | def _load(self):
"""Load values for all ConfigProperty attributes"""
for attr_name, config_prop in self._iter_config_props():
found = False
for loader in self._loaders:
if loader.exists(config_prop.property_key):
raw_value = loader.get(config_p... |
Reload all ConfigProperty values ( reading from loader sources again if applicable ) | def reload(self):
"""Reload all ConfigProperty values (reading from loader sources again, if applicable)"""
for loader in self._loaders:
loader.reload()
self.varz = {} # reset varz
self._load() |
Return all properties and values in a dictionary ( includes private properties ) | def as_dict(self):
"""Return all properties and values in a dictionary (includes private properties)"""
return {config_name: getattr(self, config_name)
for config_name, _ in self._iter_config_props()} |
Return an absolute path to a target file that is located in the same directory as as_file | def in_same_dir(as_file, target_file):
"""Return an absolute path to a target file that is located in the same directory as as_file
Args:
as_file: File name (including __file__)
Use the directory path of this file
target_file: Name of the target file
"""
return os.path.abspa... |
Compares a name in question to a specified name separated into given and family. | def compare_name(given_name, family_name, question_name):
"""Compares a name in question to a specified name separated into given and family.
The name in question ``question_name`` can be of varying format, including
"Kyle E. Niemeyer", "Kyle Niemeyer", "K. E. Niemeyer", "KE Niemeyer", and
"K Niemeyer"... |
Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range ( bool ): flag from schema indicating T range is to be checked field ( str ): T_range values ( list ): List of temperature values indicating low middle and high ranges | def _validate_isvalid_t_range(self, isvalid_t_range, field, values):
"""Checks that the temperature ranges given for thermo data are valid
Args:
isvalid_t_range (`bool`): flag from schema indicating T range is to be checked
field (`str`): T_range
values (`list`): List... |
Checks for appropriate units using Pint unit registry. Args: isvalid_unit ( bool ): flag from schema indicating units to be checked. field ( str ): property associated with units in question. value ( dict ): dictionary of values from file associated with this property. | def _validate_isvalid_unit(self, isvalid_unit, field, value):
"""Checks for appropriate units using Pint unit registry.
Args:
isvalid_unit (`bool`): flag from schema indicating units to be checked.
field (`str`): property associated with units in question.
value (`dic... |
Checks that the given time history is properly formatted. | def _validate_isvalid_history(self, isvalid_history, field, value):
"""Checks that the given time history is properly formatted.
Args:
isvalid_history (`bool`): flag from schema indicating units to be checked.
field (`str`): property associated with history in question.
... |
Checks for valid given value and appropriate units. | def _validate_isvalid_quantity(self, isvalid_quantity, field, value):
"""Checks for valid given value and appropriate units.
Args:
isvalid_quantity (`bool`): flag from schema indicating quantity to be checked.
field (`str`): property associated with quantity in question.
... |
Checks for valid given value and appropriate units with uncertainty. | def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value):
"""Checks for valid given value and appropriate units with uncertainty.
Args:
isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked
field (`str`): property associated with t... |
Checks valid reference metadata using DOI ( if present ). | def _validate_isvalid_reference(self, isvalid_reference, field, value):
"""Checks valid reference metadata using DOI (if present).
Args:
isvalid_reference (`bool`): flag from schema indicating reference to be checked.
field (`str`): 'reference'
value (`dict`): dictio... |
Checks for valid ORCID if given. | def _validate_isvalid_orcid(self, isvalid_orcid, field, value):
"""Checks for valid ORCID if given.
Args:
isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked.
field (`str`): 'author'
value (`dict`): dictionary of author metadata.
The rule... |
Checks for valid specification of composition. | def _validate_isvalid_composition(self, isvalid_composition, field, value):
"""Checks for valid specification of composition.
Args:
isvalid_composition (bool): flag from schema indicating
composition to be checked.
field (str): 'composition'
value (di... |
Read a CSV in canonical form::: | def read_csv(filename, keys=None, convert_types=False, **kwargs):
'''
Read a CSV in canonical form: ::
<agent_id, t_step, key, value, value_type>
'''
df = pd.read_csv(filename)
if convert_types:
df = convert_types_slow(df)
if keys:
df = df[df['key'].isin(keys)]
df =... |
This is a slow operation. | def convert_types_slow(df):
'''This is a slow operation.'''
dtypes = get_types(df)
for k, v in dtypes.items():
t = df[df['key']==k]
t['value'] = t['value'].astype(v)
df = df.apply(convert_row, axis=1)
return df |
Split a dataframe in two dataframes: one with the history of agents and one with the environment history | def split_df(df):
'''
Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history
'''
envmask = (df['agent_id'] == 'env')
n_env = envmask.sum()
if n_env == len(df):
return df, None
elif n_env == 0:
return None, df
agents, ... |
Process a dataframe in canonical form ( t_step agent_id key value value_type ) into two dataframes with a column per key: one with the history of the agents and one for the history of the environment. | def process(df, **kwargs):
'''
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into
two dataframes with a column per key: one with the history of the agents, and one for the
history of the environment.
'''
env, agents = split_df(df)
return process_one(env... |
Process a dataframe in canonical form ( t_step agent_id key value value_type ) into a dataframe with a column per key | def process_one(df, *keys, columns=['key', 'agent_id'], values='value',
fill=True, index=['t_step',],
aggfunc='first', **kwargs):
'''
Process a dataframe in canonical form ``(t_step, agent_id, key, value, value_type)`` into
a dataframe with a column per key
'''
if df ... |
Read all the trial data and plot the result of applying a function on them. | def plot_all(*args, **kwargs):
'''
Read all the trial data and plot the result of applying a function on them.
'''
dfs = do_all(*args, **kwargs)
ps = []
for line in dfs:
f, df, config = line
df.plot(title=config['name'])
ps.append(df)
return ps |
Return a name that can be imported to serialize/ deserialize an object | def name(value, known_modules=[]):
'''Return a name that can be imported, to serialize/deserialize an object'''
if value is None:
return 'None'
if not isinstance(value, type): # Get the class name first
value = type(value)
tname = value.__name__
if hasattr(builtins, tname):
... |
Get a text representation of an object. | def serialize(v, known_modules=[]):
'''Get a text representation of an object.'''
tname = name(v, known_modules=known_modules)
func = serializer(tname)
return func(v), tname |
Get an object from a text representation | def deserialize(type_, value=None, **kwargs):
'''Get an object from a text representation'''
if not isinstance(type_, str):
return type_
des = deserializer(type_, **kwargs)
if value is None:
return des
return des(value) |
Return parsed data. Parse it if not already parsed. | def content(self):
"""
Return parsed data. Parse it if not already parsed.
Returns:
list: list of dictionaries (one for each parsed line).
"""
if self._content is None:
self._content = self.parse_files()
return self._content |
Find files. | def matching_files(self):
"""
Find files.
Returns:
list: the list of matching files.
"""
matching = []
matcher = self.file_path_regex
pieces = self.file_path_regex.pattern.split(sep)
partial_matchers = list(map(re.compile, (
sep.jo... |
Find the files and parse them. | def parse_files(self):
"""
Find the files and parse them.
Returns:
list: list of dictionaries (one for each parsed line).
"""
log_re = self.log_format_regex
log_lines = []
for log_file in self.matching_files():
with open(log_file) as f:
... |
Calculate the threshold values ( thresholds for a uniform distribution ) of an agent distribution given the weights of each agent type. | def calculate_distribution(network_agents=None,
agent_type=None):
'''
Calculate the threshold values (thresholds for a uniform distribution)
of an agent distribution given the weights of each agent type.
The input has this form: ::
[
{'agent_type': 'a... |
When serializing an agent distribution remove the thresholds in order to avoid cluttering the YAML definition file. | def serialize_distribution(network_agents, known_modules=[]):
'''
When serializing an agent distribution, remove the thresholds, in order
to avoid cluttering the YAML definition file.
'''
d = deepcopy(list(network_agents))
for v in d:
if 'threshold' in v:
del v['threshold']
... |
Validate states to avoid ignoring states during initialization | def _validate_states(states, topology):
'''Validate states to avoid ignoring states during initialization'''
states = states or []
if isinstance(states, dict):
for x in states:
assert x in topology.node
else:
assert len(states) <= len(topology)
return states |
Convenience method to allow specifying agents by class or class name. | def _convert_agent_types(ind, to_string=False, **kwargs):
'''Convenience method to allow specifying agents by class or class name.'''
if to_string:
return serialize_distribution(ind, **kwargs)
return deserialize_distribution(ind, **kwargs) |
Used in the initialization of agents given an agent distribution. | def _agent_from_distribution(distribution, value=-1, agent_id=None):
"""Used in the initialization of agents given an agent distribution."""
if value < 0:
value = random.random()
for d in sorted(distribution, key=lambda x: x['threshold']):
threshold = d['threshold']
# Check if the de... |
Get a list of nodes in the ego network of * node * of radius * steps * | def ego_search(self, steps=1, center=False, node=None, **kwargs):
'''Get a list of nodes in the ego network of *node* of radius *steps*'''
node = as_node(node if node is not None else self)
G = self.subgraph(**kwargs)
return nx.ego_graph(G, node, center=center, radius=steps).nodes() |
Get a list of nodes whose coordinates are closer than * radius * to * node *. | def geo_search(self, radius, node=None, center=False, **kwargs):
'''Get a list of nodes whose coordinates are closer than *radius* to *node*.'''
node = as_node(node if node is not None else self)
G = self.subgraph(**kwargs)
pos = nx.get_node_attributes(G, 'pos')
if not pos:
... |
Receiving a message from the websocket parse and act accordingly. | def on_message(self, message):
""" Receiving a message from the websocket, parse, and act accordingly. """
msg = tornado.escape.json_decode(message)
if msg['type'] == 'config_file':
if self.application.verbose:
print(msg['data'])
self.config = list(yam... |
Run the app. | def launch(self, port=None):
""" Run the app. """
if port is not None:
self.port = port
url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)
print('Interface starting at {url}'.format(url=url))
self.listen(self.port)
# webbrowser.open(url)
t... |
Get stats for status codes by date. | def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(
lambda dt: ms_since_epoch(datetime.combine(
... |
Get stats for most visited pages. | def most_visited_pages_stats():
"""
Get stats for most visited pages.
Args:
logs (list): logs data to use.
Returns:
dict: more_than_10 and less_than_10: list of dict (bound + url list).
"""
stats = {'more_than_10': [], 'less_than_10': {}}
counter = Counter(list(RequestLog.... |
Agents will try to enter. The pub checks if it is possible | def enter(self, pub_id, *nodes):
'''Agents will try to enter. The pub checks if it is possible'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
if not pub['open'] or (pub['capacity'] < (len(nodes) + pub... |
Agents will notify the pub they want to leave | def exit(self, pub_id, *node_ids):
'''Agents will notify the pub they want to leave'''
try:
pub = self['pubs'][pub_id]
except KeyError:
raise ValueError('Pub {} is not available'.format(pub_id))
for node_id in node_ids:
node = self.get_agent(node_id)
... |
Look for friends to drink with | def looking_for_friends(self):
'''Look for friends to drink with'''
self.info('I am looking for friends')
available_friends = list(self.get_agents(drunk=False,
pub=None,
state_id=self.looking_for_fr... |
Look for a pub that accepts me and my friends | def looking_for_pub(self):
'''Look for a pub that accepts me and my friends'''
if self['pub'] != None:
return self.sober_in_pub
self.debug('I am looking for a pub')
group = list(self.get_neighboring_agents())
for pub in self.env.available_pubs():
self.debu... |
Try to become friends with another agent. The chances of success depend on both agents openness. | def befriend(self, other_agent, force=False):
'''
Try to become friends with another agent. The chances of
success depend on both agents' openness.
'''
if force or self['openness'] > random():
self.env.add_edge(self, other_agent)
self.info('Made some frien... |
Look for random agents around me and try to befriend them | def try_friends(self, others):
''' Look for random agents around me and try to befriend them'''
befriended = False
k = int(10*self['openness'])
shuffle(others)
for friend in islice(others, k): # random.choice >= 3.7
if friend == self:
continue
... |
Compute the mean standard deviation min quartile1 quartile2 quartile3 and max of a vector | def profile_distribution(data):
"""
Compute the mean, standard deviation, min, quartile1, quartile2, quartile3, and max of a vector
Parameters
----------
data: array of real values
Returns
-------
features = dictionary containing the min, max, mean, and standard deviation
"""
i... |
Return the value as a dict raising error if conversion to dict is not possible | def to_native(self, value):
"""Return the value as a dict, raising error if conversion to dict is not possible"""
if isinstance(value, dict):
return value
elif isinstance(value, six.string_types):
native_value = json.loads(value)
if isinstance(native_value, di... |
Load a value as a list converting items if necessary | def to_native(self, value):
"""Load a value as a list, converting items if necessary"""
if isinstance(value, six.string_types):
value_list = value.split(self.string_delim)
else:
value_list = value
to_native = self.member_type.to_native if self.member_type is not ... |
Validate each member of the list if member_type exists | def validate_member_type(self, value):
"""Validate each member of the list, if member_type exists"""
if self.member_type:
for item in value:
self.member_type.validate(item) |
Validate the length of value if min_length or max_length was specified | def validate_length(self, value):
"""Validate the length of value, if min_length or max_length was specified"""
list_len = len(value) if value else 0
if self.max_length is not None and list_len > self.max_length:
raise ValidationError(
u'List has {} values; max lengt... |
Validate the network resource with exponential backoff | def validate_resource(self, value):
"""Validate the network resource with exponential backoff"""
def do_backoff(*args, **kwargs):
"""Call self._test_connection with exponential backoff, for self._max_tries attempts"""
attempts = 0
while True:
try:
... |
登录 | def login(self, **kwargs):
"""登录"""
payload = {
'username': self.username,
'password': self.password,
}
headers = kwargs.setdefault('headers', {})
headers.setdefault(
'Referer',
'https://www.shanbay.com/web/account/login'
)
... |
获取扇贝网服务器时间(UTC 时间) | def server_date_utc(self):
"""获取扇贝网服务器时间(UTC 时间)"""
date_str = self.request('http://www.shanbay.com', 'head'
).headers['date']
date_utc = datetime.datetime.strptime(date_str,
'%a, %d %b %Y %H:%M:%S GMT')
return... |
Returns a list of metafeatures computable by the Metafeatures class. | def list_metafeatures(cls, group="all"):
"""
Returns a list of metafeatures computable by the Metafeatures class.
"""
# todo make group for intractable metafeatures for wide datasets or
# datasets with high cardinality categorical columns:
# PredPCA1, PredPCA2, PredPCA3, ... |
Parameters ---------- X: pandas. DataFrame the dataset features Y: pandas. Series the dataset targets column_types: Dict [ str str ] dict from column name to column type as NUMERIC or CATEGORICAL or TEXT must include Y column metafeature_ids: list the metafeatures to compute. default of None indicates to compute all me... | def compute(
self, X: DataFrame, Y: Series=None,
column_types: Dict[str, str]=None, metafeature_ids: List=None,
exclude: List=None, sample_shape=None, seed=None, n_folds=2,
verbose=False, timeout=None
) -> dict:
"""
Parameters
----------
X: pandas.Data... |
Stratified uniform sampling of rows according to the classes in Y. Ensures there are enough samples from each class in Y for cross validation. | def _sample_rows(self, X, Y, sample_shape, seed):
"""
Stratified uniform sampling of rows, according to the classes in Y.
Ensures there are enough samples from each class in Y for cross
validation.
"""
if sample_shape[0] is None or X.shape[0] <= sample_shape[0]:
... |
Constructor: use token authentication to read secrets from a Vault path | def from_token(cls, url, path, token):
"""Constructor: use token authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/token.html
Args:
url: Vault url
path: Vault path where secrets are stored
vault_token: token (must hav... |
Constructor: use AppRole authentication to read secrets from a Vault path | def from_app_role(cls, url, path, role_id, secret_id):
"""Constructor: use AppRole authentication to read secrets from a Vault path
See https://www.vaultproject.io/docs/auth/approle.html
Args:
url: Vault url
path: Vault path where secrets are stored
role_id:... |
Read data from the vault path | def _fetch_secrets(vault_url, path, token):
"""Read data from the vault path"""
url = _url_joiner(vault_url, 'v1', path)
resp = requests.get(url, headers=VaultLoader._get_headers(token))
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise V... |
Get a Vault token using the RoleID and SecretID | def _fetch_app_role_token(vault_url, role_id, secret_id):
"""Get a Vault token, using the RoleID and SecretID"""
url = _url_joiner(vault_url, 'v1/auth/approle/login')
resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id})
resp.raise_for_status()
data = resp.... |
Reread secrets from the vault path | def reload(self):
"""Reread secrets from the vault path"""
self._source = self._fetch_secrets(self._vault_url, self._path, self._token) |
Convenience method: look up the vault token | def lookup_token(self):
"""Convenience method: look up the vault token"""
url = _url_joiner(self._vault_url, 'v1/auth/token/lookup-self')
resp = requests.get(url, headers=self._headers)
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise Va... |
Convenience method: renew Vault token | def renew_token(self):
"""Convenience method: renew Vault token"""
url = _url_joiner(self._vault_url, 'v1/auth/token/renew-self')
resp = requests.get(url, headers=self._headers)
resp.raise_for_status()
data = resp.json()
if data.get('errors'):
raise VaultExcep... |
Sort sort options for display. | def sorted_options(sort_options):
"""Sort sort options for display.
:param sort_options: A dictionary containing the field name as key and
asc/desc as value.
:returns: A dictionary with sorting options for Invenio-Search-JS.
"""
return [
{
'title': v['title'],
... |
Converts html code into formatted plain text. | def html_to_plain_text(html):
"""Converts html code into formatted plain text."""
# Use BeautifulSoup to normalize the html
soup = BeautifulSoup(html, "html.parser")
# Init the parser
parser = HTML2PlainParser()
parser.feed(str(soup.encode('utf-8')))
# Strip the end of the plain text
res... |
Handles every start tag like e. g. <p >. | def handle_starttag(self, tag, attrs):
"""Handles every start tag like e.g. <p>."""
if (tag in self.newline_before_elements):
self.text += '\n'
if (tag in self.stroke_before_elements and not
self.text.endswith(self.stroke_text)):
# Put a stroke in front of... |
Handles data between tags. | def handle_data(self, data):
"""Handles data between tags."""
# Only proceed with unignored elements
if self.lasttag not in self.ignored_elements:
# Remove any predefined linebreaks
text = data.replace('\n', '')
# If there's some text left, proceed!
... |
Handles every end tag like e. g. </ p >. | def handle_endtag(self, tag):
"""Handles every end tag like e.g. </p>."""
if tag in self.stroke_after_elements:
if self.text.endswith(self.stroke_text):
# Only add a stroke if there isn't already a stroke posted
# In this case, there was no content between the... |
Starts the thread | def run(self):
""" Starts the thread """
task = None
monitor_task = MonitorTask(
notification_endpoint=self._handle_message)
while True:
if self._terminate:
self._logger.info("scsgate.Reactor exiting")
self._connection.close()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.