code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
assert index < STATES
population = index // FIRE_CLASSES
fire = index % FIRE_CLASSES
return(population, fire) | def convertIndexToState(index) | Convert transition probability matrix index to state parameters.
Parameters
----------
index : int
The index into the transition probability matrix that corresponds to
the state parameters.
Returns
-------
population, fire : tuple of int
``population``, the popu... | 12.948373 | 9.200271 | 1.40739 |
assert 0 <= x < POPULATION_CLASSES
assert 0 <= F < FIRE_CLASSES
assert 0 <= s <= 1
assert 0 <= a < ACTIONS
prob = np.zeros((STATES,))
r = getHabitatSuitability(F)
# Efect of action on time in years since fire.
if a == 0:
# Increase the time since the patch has been burned b... | def getTransitionProbabilities(s, x, F, a) | Calculate the transition probabilities for the given state and action.
Parameters
----------
s : float
The probability of a population remaining in its current abundance
class
x : int
The population abundance class
F : int
The number of years since a fire
a :... | 3.244002 | 3.059117 | 1.060437 |
assert 0 <= s <= 1, "'s' must be between 0 and 1"
# The transition probability array
P = np.zeros((ACTIONS, STATES, STATES))
# The reward vector
R = np.zeros(STATES)
# Loop over all states
for idx in range(STATES):
# Get the state index as inputs to our functions
x, F = ... | def getTransitionAndRewardArrays(s) | Generate the fire management transition and reward matrices.
The output arrays from this function are valid input to the mdptoolbox.mdp
classes.
Let ``S`` = number of states, and ``A`` = number of actions.
Parameters
----------
s : float
The class-independent probability o... | 3.949975 | 3.900189 | 1.012765 |
P, R = getTransitionAndRewardArrays(0.5)
sdp = mdp.FiniteHorizon(P, R, 0.96, 50)
sdp.run()
return(sdp) | def solveMDP() | Solve the problem as a finite horizon Markov decision process.
The optimal policy at each stage is found using backwards induction.
Possingham and Tuck report strategies for a 50 year time horizon, so the
number of stages for the finite horizon algorithm is set to 50. There is no
discount factor re... | 9.229076 | 7.188768 | 1.283819 |
p = np.array(policy).reshape(POPULATION_CLASSES, FIRE_CLASSES)
range_F = range(FIRE_CLASSES)
print(" " + " ".join("%2d" % f for f in range_F))
print(" " + "---" * FIRE_CLASSES)
for x in range(POPULATION_CLASSES):
print(" %2d|" % x + " ".join("%2d" % p[x, f] for f in range_F)) | def printPolicy(policy) | Print out a policy vector as a table to console
Let ``S`` = number of states.
The output is a table that has the population class as rows, and the years
since a fire as the columns. The items in the table are the optimal action
for that population class and years since fire combination.
... | 3.609862 | 3.542605 | 1.018985 |
assert 0 <= x < POPULATION_CLASSES, "'x' must be in " \
"{0, 1...%s}" % POPULATION_CLASSES - 1
assert 0 <= s <= 1, "'s' must be in [0; 1]"
assert 0 <= r <= 1, "'r' must be in [0; 1]"
assert fire in (True, False), "'fire' must be a boolean value"
x = int(x)
if x == 0:
pass
... | def simulateTransition(x, s, r, fire) | Simulate a state transition.
Parameters
----------
x : int
The current abundance class of the threatened species.
s : float
The state-independent probability of the population staying in its
current abundance class.
r : float
The probability the population moves ... | 2.992043 | 2.771573 | 1.079547 |
# definition of transition matrix : square stochastic matrix
P = _np.zeros((actions, states, states))
# definition of reward matrix (values between -1 and +1)
R = _np.zeros((actions, states, states))
for action in range(actions):
for state in range(states):
# create our own ... | def _randDense(states, actions, mask) | Generate random dense ``P`` and ``R``. See ``rand`` for details. | 3.185504 | 3.117596 | 1.021782 |
# definition of transition matrix : square stochastic matrix
P = [None] * actions
# definition of reward matrix (values between -1 and +1)
R = [None] * actions
for action in range(actions):
# it may be more efficient to implement this by constructing lists
# of rows, columns and... | def _randSparse(states, actions, mask) | Generate random sparse ``P`` and ``R``. See ``rand`` for details. | 3.704955 | 3.649603 | 1.015167 |
data_json = self._create_json()
data_json.update(self.additional_params)
request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self)
r = self._session.put(
request_url,
json=data_json,
headers={'Content-Type': '... | def _create_and_update(self) | Create or update request, re-read object from Artifactory
:return: None | 5.384309 | 4.808801 | 1.119678 |
logging.debug('Read {x.__class__.__name__} [{x.name}]'.format(x=self))
request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self)
r = self._session.get(
request_url,
auth=self._auth,
)
if 404 == r.status_code or 40... | def read(self) | Read object from artifactory. Fill object if exist
:return:
True if object exist,
False else | 2.959973 | 2.629249 | 1.125786 |
logging.debug('Remove {x.__class__.__name__} [{x.name}]'.format(x=self))
request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self)
r = self._session.delete(
request_url,
auth=self._auth,
)
r.raise_for_status()
... | def delete(self) | Remove object
:return: None | 5.85697 | 5.740279 | 1.020328 |
data_json = {
'name': self.name,
'email': self.email,
'password': self.password,
'admin': self.admin,
"profileUpdatable": self.profileUpdatable,
"internalPasswordDisabled": self.internalPasswordDisabled,
"groups": self.... | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 4.172375 | 3.70833 | 1.125136 |
# self.password = '' # never returned
self.name = response['name']
self.email = response['email']
self.admin = response['admin']
self.profileUpdatable = response['profileUpdatable']
self.internalPasswordDisabled = response['internalPasswordDisabled']
sel... | def _read_response(self, response) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 3.717593 | 3.513302 | 1.058148 |
data_json = {
"name": self.name,
"description": self.description,
"autoJoin": self.autoJoin,
"realm": self.realm,
}
return data_json | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 4.295371 | 3.484113 | 1.232845 |
self.name = response['name']
self.description = response['description']
self.autoJoin = response['autoJoin']
self.realm = response['realm']
self.realmAttributes = response.get('realmAttributes', None) | def _read_response(self, response) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 4.312828 | 3.45635 | 1.247798 |
data_json = super(GroupLDAP, self)._create_json()
data_json.update({
'realmAttributes': self.realmAttributes,
'external': True,
})
return data_json | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 6.962721 | 5.879643 | 1.184208 |
data_json = {
"rclass": "local",
"key": self.name,
"description": self.description,
"packageType": self.packageType,
"notes": "",
"includesPattern": "**/*",
"excludesPattern": "",
"repoLayoutRef": self.repoL... | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON | 6.435534 | 4.762205 | 1.351377 |
self.name = response['key']
self.description = response['description']
self.layoutName = response['repoLayoutRef']
self.archiveBrowsingEnabled = response['archiveBrowsingEnabled'] | def _read_response(self, response) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON | 7.237781 | 3.861008 | 1.874583 |
data_json = {
"rclass": "virtual",
"key": self.name,
"description": self.description,
"packageType": self.packageType,
"repositories": self._repositories,
"notes": self.notes,
}
return data_json | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON | 6.396979 | 4.440339 | 1.440651 |
rclass = response['rclass']
if rclass != "virtual":
raise ArtifactoryException("Repositiry '{}' have '{}', but expect 'virtual'".format(self.name, rclass))
self.name = response["key"]
self.description = response["description"]
self.packageType = response["pa... | def _read_response(self, response) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON | 7.250329 | 4.933263 | 1.469682 |
data_json = {
"name": self.name,
"includesPattern": self.includesPattern,
"excludesPattern": self.excludesPattern,
"repositories": self._repositories,
"principals": {
'users': self._users,
'groups': self._groups... | def _create_json(self) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 3.588813 | 2.941699 | 1.21998 |
self.name = response['name']
self.includesPattern = response['includesPattern']
self.excludesPattern = response['excludesPattern']
self._repositories = response.get('repositories', [])
if 'principals' in response:
if 'users' in response['principals']:
... | def _read_response(self, response) | JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON | 2.504869 | 2.148855 | 1.165676 |
config_path = os.path.expanduser(config_path)
if not os.path.isfile(config_path):
raise OSError(errno.ENOENT,
"Artifactory configuration file not found: '%s'" %
config_path)
p = configparser.ConfigParser()
p.read(config_path)
result = {}
... | def read_config(config_path=default_config_path) | Read configuration file and produce a dictionary of the following structure:
{'<instance1>': {'username': '<user>', 'password': '<pass>',
'verify': <True/False>, 'cert': '<path-to-cert>'}
'<instance2>': {...},
...}
Format of the file:
[https://artifactory-instance.... | 2.073695 | 1.981858 | 1.046338 |
if not config:
return None
# First, try to search for the best match
for item in config:
if url.startswith(item):
return item
# Then search for indirect match
for item in config:
if without_http_prefix(url).startswith(without_http_prefix(item)):
... | def get_base_url(config, url) | Look through config and try to find best matching base for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the base for | 4.905839 | 4.606253 | 1.065039 |
if not config:
return None
# First, try to search for the best match
if url in config:
return config[url]
# Then search for indirect match
for item in config:
if without_http_prefix(item) == without_http_prefix(url):
return config[item] | def get_config_entry(config, url) | Look through config and try to find best matching entry for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the config for | 4.899439 | 4.538302 | 1.079575 |
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * sha1.block_size), b''):
sha1.update(chunk)
return sha1.hexdigest() | def sha1sum(filename) | Calculates sha1 hash of a file | 1.476383 | 1.503313 | 0.982086 |
it = iter(data)
for i in range(0, len(data), size):
yield {k: data[k] for k in islice(it, size)} | def chunks(data, size) | Get chink for dict, copy as-is from https://stackoverflow.com/a/8290508/6753144 | 1.955802 | 1.632493 | 1.198046 |
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):
value = (';%s=' % (param)).join(parameters[param])
else:
value = parameters[param]
result.append("%s=%s" % (param, value))
return ';'.join(result) | def encode_matrix_parameters(parameters) | Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs. | 2.960796 | 2.791203 | 1.06076 |
dirs, nondirs = [], []
for child in pathobj:
relpath = str(child.relative_to(str(pathobj)))
if relpath.startswith('/'):
relpath = relpath[1:]
if relpath.endswith('/'):
relpath = relpath[:-1]
if child.is_dir():
dirs.append(relpath)
... | def walk(pathobj, topdown=True) | os.walk like function to traverse the URI like a file system.
The only difference is that this function takes and returns Path objects
in places where original implementation will return strings | 1.730402 | 1.87704 | 0.921878 |
drv = ''
root = ''
base = get_global_base_url(part)
if base and without_http_prefix(part).startswith(without_http_prefix(base)):
mark = without_http_prefix(base).rstrip(sep) + sep
parts = part.split(mark)
else:
url = urllib3.util.pars... | def splitroot(self, part, sep=sep) | Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is taken
for relative path.
If '/artifacto... | 3.164068 | 3.064166 | 1.032603 |
res = session.delete(url, params=params, verify=verify, cert=cert)
return res.text, res.status_code | def rest_del(self, url, params=None, session=None, verify=True, cert=None) | Perform a DELETE request to url with requests.session | 2.636416 | 2.816196 | 0.936162 |
res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)
return res.text, res.status_code | def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None) | Perform a chunked PUT request to url with requests.session
This is specifically to upload files. | 2.443978 | 2.480291 | 0.98536 |
res = session.get(url, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code | def rest_get_stream(self, url, session=None, verify=True, cert=None) | Perform a chunked GET request to url with requests.session
This is specifically to download files. | 3.028429 | 2.908951 | 1.041072 |
jsn = self.get_stat_json(pathobj)
is_dir = False
if 'size' not in jsn:
is_dir = True
children = None
if 'children' in jsn:
children = [child['uri'][1:] for child in jsn['children']]
stat = ArtifactoryFileStat(
ctime=dateutil... | def stat(self, pathobj) | Request remote file/directory status info
Returns an object of class ArtifactoryFileStat.
The following fields are available:
ctime -- file creation time
mtime -- file modification time
created_by -- original uploader
modified_by -- last user modifying the file
... | 2.303895 | 1.884212 | 1.222736 |
try:
stat = self.stat(pathobj)
return stat.is_dir
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
return False | def is_dir(self, pathobj) | Returns True if given path is a directory | 2.943717 | 3.027401 | 0.972358 |
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: %s" % str(pathobj))
return stat.children | def listdir(self, pathobj) | Returns a list of immediate sub-directories and files in path | 3.503155 | 3.891235 | 0.900268 |
if not pathobj.drive or not pathobj.root:
raise RuntimeError("Full path required: '%s'" % str(pathobj))
if pathobj.exists():
raise OSError(17, "File exists: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_put(url, session=pathobj.s... | def mkdir(self, pathobj, _) | Creates remote directory
Note that this operation is not recursive | 4.088546 | 3.84584 | 1.063109 |
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if code not in [200, 202, 2... | def rmdir(self, pathobj) | Removes a directory | 3.53209 | 3.752717 | 0.941209 |
# TODO: Why do we forbid remove folder?
# if stat.is_dir:
# raise OSError(1, "Operation not permitted: '%s'" % str(pathobj))
url = str(pathobj)
text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify,
cert=p... | def unlink(self, pathobj) | Removes a file | 5.441085 | 5.391739 | 1.009152 |
if not pathobj.drive or not pathobj.root:
raise RuntimeError('Full path required')
if pathobj.exists():
return
url = str(pathobj)
text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if not code == ... | def touch(self, pathobj) | Create an empty file | 4.933396 | 5.106523 | 0.966097 |
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
else:
return 'nobody' | def owner(self, pathobj) | Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available | 5.32866 | 3.778641 | 1.410206 |
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.created_by
else:
return 'nobody' | def creator(self, pathobj) | Returns file creator
This makes little sense for Artifactory, but to be consistent
with pathlib, we return created_by instead, if available | 6.201031 | 4.440587 | 1.396444 |
url = '/'.join([src.drive,
'api/copy',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/'),
'suppressLayouts': int(suppress_layouts)}
text, code = self.rest_post(url... | def copy(self, src, dst, suppress_layouts=False) | Copy artifact from src to dst | 3.962015 | 4.027624 | 0.98371 |
obj = super(ArtifactoryPath, self).parent
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
obj.session = self.session
return obj | def parent(self) | The logical parent of the path. | 4.636168 | 4.186913 | 1.1073 |
obj = super(ArtifactoryPath, self).with_name(name)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
obj.session = self.session
return obj | def with_name(self, name) | Return a new path with the file name changed. | 3.335245 | 3.329209 | 1.001813 |
obj = super(ArtifactoryPath, self).with_suffix(suffix)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
obj.session = self.session
return obj | def with_suffix(self, suffix) | Return a new path with the file suffix changed (or added, if none). | 3.312521 | 3.328608 | 0.995167 |
if mode != 'r' or buffering != -1 or encoding or errors or newline:
raise NotImplementedError('Only the default open() ' +
'arguments are supported')
return self._accessor.open(self) | def open(self, mode='r', buffering=-1, encoding=None,
errors=None, newline=None) | Open the given Artifactory URI and return a file-like object
HTTPResponse, as if it was a regular filesystem object.
The only difference is that this object doesn't support seek() | 5.475261 | 5.266056 | 1.039727 |
if self.exists() and not exist_ok:
raise OSError(17, "File exists", str(self))
self._accessor.touch(self) | def touch(self, mode=0o666, exist_ok=True) | Create a file if it doesn't exist.
Mode is ignored by Artifactory. | 5.200844 | 4.5684 | 1.138439 |
return self._accessor.deploy(self, fobj, md5, sha1, parameters) | def deploy(self, fobj, md5=None, sha1=None, parameters={}) | Upload the given file object to this path | 5.380051 | 5.465163 | 0.984427 |
if calc_md5:
md5 = md5sum(file_name)
if calc_sha1:
sha1 = sha1sum(file_name)
target = self
if self.is_dir():
target = self / pathlib.Path(file_name).name
with open(file_name, 'rb') as fobj:
target.deploy(fobj, md5, sha1,... | def deploy_file(self,
file_name,
calc_md5=True,
calc_sha1=True,
parameters={}) | Upload the given file to this path | 2.679012 | 2.709228 | 0.988847 |
params = {
'deb.distribution': distribution,
'deb.component': component,
'deb.architecture': architecture
}
params.update(parameters)
self.deploy_file(file_name, parameters=params) | def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}) | Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file that will be deployed
distribution -- debian distribution (e.g. 'wheezy')
component -- repository component (e.g. 'main')
architecture -- package architecture (e.g. 'i386')
... | 2.6464 | 3.61798 | 0.731458 |
if self.drive == dst.drive:
self._accessor.copy(self, dst, suppress_layouts=suppress_layouts)
else:
with self.open() as fobj:
dst.deploy(fobj) | def copy(self, dst, suppress_layouts=False) | Copy artifact from this path to destinaiton.
If files are on the same instance of artifactory, lightweight (local)
copying will be attempted.
The suppress_layouts parameter, when set to True, will allow artifacts
from one path to be copied directly into another path without enforcing
... | 6.066974 | 8.872811 | 0.683771 |
if self.drive != dst.drive:
raise NotImplementedError(
"Moving between instances is not implemented yet")
self._accessor.move(self, dst) | def move(self, dst) | Move artifact from this path to destinaiton. | 9.130073 | 8.041232 | 1.135407 |
if not properties:
return
# If URL > 13KB, nginx default raise error '414 Request-URI Too Large'
MAX_SIZE = 50
if len(properties) > MAX_SIZE:
for chunk in chunks(properties, MAX_SIZE):
self._accessor.set_properties(self, chunk, recursive)... | def set_properties(self, properties, recursive=True) | Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
for a key.
recursive - on folders property attachment is rec... | 5.563825 | 6.067808 | 0.916941 |
return self._accessor.del_properties(self, properties, recursive) | def del_properties(self, properties, recursive=None) | Delete properties listed in properties
properties - iterable contains the property names to delete. If it is an
str it will be casted to tuple.
recursive - on folders property attachment is recursive by default. It is
possible to force recursive behavior. | 6.790998 | 10.901601 | 0.622936 |
aql_query_url = '{}/api/search/aql'.format(self.drive)
aql_query_text = self.create_aql_text(*args)
r = self.session.post(aql_query_url, data=aql_query_text)
r.raise_for_status()
content = r.json()
return content['results'] | def aql(self, *args) | Send AQL query to Artifactory
:param args:
:return: | 3.166055 | 3.040446 | 1.041313 |
aql_query_text = ""
for arg in args:
if isinstance(arg, dict):
arg = "({})".format(json.dumps(arg))
elif isinstance(arg, list):
arg = "({})".format(json.dumps(arg)).replace("[", "").replace("]", "")
aql_query_text += arg
... | def create_aql_text(*args) | Create AQL querty from string or list or dict arguments | 2.253512 | 2.113928 | 1.066031 |
result_type = result.get('type')
if result_type not in ('file', 'folder'):
raise RuntimeError("Path object with type '{}' doesn't support. File or folder only".format(result_type))
result_path = "{}/{repo}/{path}/{name}".format(self.drive, **result)
obj = Artifactor... | def from_aql(self, result) | Convert raw AQL result to pathlib object
:param result: ONE raw result
:return: | 5.435491 | 5.427048 | 1.001556 |
wd = self.__watches.get(path)
if wd is None:
return
_LOGGER.debug("Removing watch for watch-handle (%d): [%s]",
wd, path)
del self.__watches[path]
self.remove_watch_with_id(wd) | def remove_watch(self, path, superficial=False) | Remove our tracking information and call inotify to stop watching
the given path. When a directory is removed, we'll just have to remove
our tracking since inotify already cleans-up the watch. | 5.722251 | 5.753135 | 0.994632 |
b = os.read(wd, 1024)
if not b:
return
self.__buffer += b
while 1:
length = len(self.__buffer)
if length < _STRUCT_HEADER_LENGTH:
_LOGGER.debug("Not enough bytes for a header.")
return
# We have... | def _handle_inotify_event(self, wd) | Handle a series of events coming-in from inotify. | 3.939844 | 3.871645 | 1.017615 |
# We will either return due to the optional filter or because of a
# timeout. The former will always set this. The latter will never set
# this.
self.__last_success_return = None
last_hit_s = time.time()
while True:
block_duration_s = self.__get_blo... | def event_gen(
self, timeout_s=None, yield_nones=True, filter_predicate=None,
terminal_events=_DEFAULT_TERMINAL_EVENTS) | Yield one event after another. If `timeout_s` is provided, we'll
break when no event is received for that many seconds. | 3.910627 | 4.006334 | 0.976111 |
for event in self._i.event_gen(**kwargs):
if event is not None:
(header, type_names, path, filename) = event
if header.mask & inotify.constants.IN_ISDIR:
full_path = os.path.join(path, filename)
if (
... | def event_gen(self, ignore_missing_new_folders=False, **kwargs) | This is a secondary generator that wraps the principal one, and
adds/removes watches as directories are added/removed.
If we're doing anything funky and allowing the events to queue while a
rename occurs then the folder may no longer exist. In this case, set
`ignore_missing_new_folders`... | 2.650872 | 2.557269 | 1.036603 |
if self.escape:
v = v.strip().replace("\\" + self.quote, self.quote)
return super(kv_transformer, self).set(e, k, v, real_k=real_k, check_kw_name=check_kw_name) | def set(self, e, k, v, real_k=None, check_kw_name=False) | override base to handle escape case: replace \" to " | 3.822967 | 2.96354 | 1.29 |
# copy project
ret = from_client.get_project(from_project)
try:
ret = to_client.create_project(to_project, ret.get_description())
except LogException as ex:
if ex.get_error_code() == 'ProjectAlreadyExist':
# don't create the project as it already exists
pass... | def copy_project(from_client, to_client, from_project, to_project, copy_machine_group=False) | copy project, logstore, machine group and logtail config to target project,
will create the target project if it doesn't exist
:type from_client: LogClient
:param from_client: logclient instance
:type to_client: LogClient
:param to_client: logclient instance
:type from_project: string
:pa... | 2.05162 | 1.984468 | 1.033839 |
if size < 0:
expected_total_size = six.MAXSIZE
else:
expected_total_size = size
batch_size = min(size, batch_size)
response = None
total_count_got = 0
while True:
ret = fn(*args, offset=offset, size=batch_size)
if response is None:
response =... | def list_more(fn, offset, size, batch_size, *args) | list all data using the fn | 2.471381 | 2.490784 | 0.99221 |
if size < 0:
expected_total_size = six.MAXSIZE
else:
expected_total_size = size
batch_size = min(size, batch_size)
response = None
total_count_got = 0
complete = False
while True:
ret = fn(*args, offset=offset, size=batch_size)
if response is None:
... | def query_more(fn, offset, size, batch_size, *args) | list all data using the fn | 2.860227 | 2.853199 | 1.002463 |
if not shard_list:
return current_shard_list
target_shards = []
for n in shard_list.split(","):
n = n.strip()
if n.isdigit() and n in current_shard_list:
target_shards.append(n)
elif n:
rng = n.split("-")
if len(rng) == 2:
... | def _parse_shard_list(shard_list, current_shard_list) | parse shard list
:param shard_list: format like: 1,5-10,20
:param current_shard_list: current shard list
:return: | 2.705723 | 2.735014 | 0.98929 |
to_client = to_client or from_client
# increase the timeout to 2 min at least
from_client.timeout = max(from_client.timeout, 120)
to_client.timeout = max(to_client.timeout, 120)
to_project = to_project or from_project
to_logstore = to_logstore or from_logstore
to_time = to_time or "end... | def copy_data(from_client, from_project, from_logstore, from_time, to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
batch_size=None, compress=None, new_topic=None, new_source=None) | copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side. | 2.35559 | 2.368804 | 0.994422 |
distance = shard_info['length'] // count
if distance <= 0 or count <= 1:
return [shard_info['info']], 0
rw_shards, increased_shard_count = {shard_info['id']: shard_info['info']}, 0
for x in range(1, count):
new_hash = shard_info['start'] + distance * x
new_hash = hex(new_ha... | def _split_one_shard_to_multiple(client, project, logstore, shard_info, count, current_shard_count) | return new_rw_shards_list, increased_shard_count | 2.714829 | 2.466655 | 1.100612 |
if not singular:
return ''
plural = ABERRANT_PLURAL_MAP.get(singular)
if plural:
return plural
root = singular
try:
if singular[-1] == 'y' and singular[-2] not in VOWELS:
root = singular[:-1]
suffix = 'ies'
elif singular[-1] == 's':
... | def pluralize(singular) | Return plural form of given lowercase singular word (English only). Based on
ActiveState recipe http://code.activestate.com/recipes/413172/
>>> pluralize('')
''
>>> pluralize('goose')
'geese'
>>> pluralize('dolly')
'dollies'
>>> pluralize('genius')
'genii'
>>> pluralize('jones')... | 1.975438 | 2.117931 | 0.93272 |
def is_stats_query(query):
if not query:
return False
# remove all " enclosed strings
nq = re.sub(r'"[^"]*"', '', query)
# check if there's | .... select
if re.findall(r'\|.*\bselect\b', nq, re.I|re.DOTALL):
return True
return False | check if the query is a normal search or select query
:param query:
:return: | null | null | null | |
def get_host_ip(logHost):
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((logHost, 80))
ip = s.getsockname()[0]
return ip
except Exception:
return '127.0.0.1'
finally:
... | If it is not match your local ip, you should fill the PutLogsRequest
parameter source by yourself. | null | null | null | |
def get_request_authorization(method, resource, key, params, headers):
if not key:
return six.b('')
content = method + "\n"
if 'Content-MD5' in headers:
content += headers['Content-MD5']
content += '\n'
if 'Content-Type' in headers:
... | :return bytes (PY2) or string (PY2) | null | null | null | |
def convert_unicode_to_str(data):
if six.PY2 and isinstance(data, six.text_type):
return data.encode('utf8')
elif six.PY3 and isinstance(data, six.binary_type):
return data.decode('utf8')
elif isinstance(data, collections.Mapping):
return dict(... | Py2, always translate to utf8 from unicode
Py3, always translate to unicode
:param data:
:return: | null | null | null | |
def h_v_t(header, key):
if key not in header:
key = key.title()
if key not in header:
raise ValueError("Unexpected header in response, missing: " + key + " headers:\n" + str(header))
return header[key] | get header value with title
try to get key from header and consider case sensitive
e.g. header['x-log-abc'] or header['X-Log-Abc']
:param header:
:param key:
:return: | null | null | null | |
def h_v_td(header, key, default):
if key not in header:
key = key.title()
return header.get(key, default) | get header value with title with default value
try to get key from header and consider case sensitive
e.g. header['x-log-abc'] or header['X-Log-Abc']
:param header:
:param key:
:param default:
:return: | null | null | null | |
input_detail = copy.deepcopy(json_value['inputDetail'])
output_detail = json_value['outputDetail']
logSample = json_value.get('logSample', '')
config_name = json_value['configName']
logstore_name = output_detail['logstoreName']
endpoint = output_detail.get('endpo... | def generate_common_reg_log_config(json_value) | Generate common logtail config from loaded json value
:param json_value:
:return: | 2.443948 | 2.442636 | 1.000537 |
input_detail = json_value['inputDetail']
output_detail = json_value['outputDetail']
config_name = json_value['configName']
logSample = json_value.get('logSample', '')
logstore_name = output_detail['logstoreName']
endpoint = output_detail.get('endpoint', '')
... | def generate_apsara_log_config(json_value) | Generate apsara logtail config from loaded json value
:param json_value:
:return: | 2.84236 | 2.904035 | 0.978762 |
logger.warning("aliyun.log.LogtailConfigHelper is deprecated and will be removed in future version."
"Use LogtailConfigGenerator instead")
if json_value['inputDetail']['logType'] == 'apsara_log':
return LogtailConfigHelper.generate_apsara_log_config(json_value... | def generate_logtail_config(json_value) | Generate logtail config from loaded json value
:param json_value:
:return: | 6.604867 | 6.361045 | 1.038331 |
reqs = []
s = time()
while len(reqs) < self.batch_size and (time() - s) < timeout:
try:
req = self.queue.get(block=False)
self.queue.task_done()
reqs.append(req)
except Empty as ex:
if self.stop_fla... | def _get_batch_requests(self, timeout=None) | try to get request as fast as possible, once empty and stop falg or time-out, just return Empty | 3.088555 | 2.942916 | 1.049488 |
# if self.task_future is None:
# # there's no any ongoing task
# self._update_status(False)
# self.generate_next_task()
# return
if self.task_future is None or self.task_future.done():
task_success = False
task_result = s... | def check_and_generate_next_task(self) | check if the previous task is done and proceed to fire another task
:return: | 3.955639 | 3.95375 | 1.000478 |
if self.consumer_status == ConsumerStatus.INITIALIZING:
self.current_task_exist = True
self.task_future = self.executor.submit(consumer_initialize_task, self.processor, self.log_client,
self.shard_id, self.cursor_position, self... | def _generate_next_task(self) | submit consumer framework defined task
:return: | 3.452425 | 3.30046 | 1.046043 |
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return False
from IPython import get_ipython
# check for `kernel` attribute on the IPython instance
if getattr(get_ipython(), 'kernel', None) is None:
return False
try:
import ipywi... | def can_use_widgets() | Expanded from from http://stackoverflow.com/a/34092072/1958900 | 3.420816 | 3.20086 | 1.068718 |
@wraps(fn)
def _wrapped(self, event, *args, **kwargs):
if _is_event_list(event):
result = []
for e in event:
ret = fn(self, e, *args, **kwargs)
if ret is None:
continue
if isinstance(ret, (tuple, list)):
... | def support_event_list_simple(fn) | enable __call__ to accept event_list.
:param fn:
:return: | 1.906281 | 1.908129 | 0.999031 |
if six.PY2:
if isinstance(d, six.binary_type):
return d.decode("utf8", "ignore")
elif isinstance(d, list):
return [u(x) for x in d]
elif isinstance(d, tuple):
return tuple(u(x) for x in d)
elif isinstance(d, dict):
return dict( (u(... | def u(d) | convert string, string container or unicode
:param d:
:return: | 1.981843 | 2.025918 | 0.978244 |
def _apply_cn_keys_patch():
import sys
if sys.version_info[:2] == (3, 5):
import http.client as hc
old_parse = hc.parse_headers
def parse_header(*args, **kwargs):
fp = args[0]
old_readline = fp.readline
def new_readline(*args, **kwarg... | apply this patch due to an issue in http.client.parse_headers
when there're multi-bytes in headers. it will truncate some headers.
https://github.com/aliyun/aliyun-log-python-sdk/issues/79 | null | null | null | |
def put_log_raw(self, project, logstore, log_group, compress=None):
body = log_group.SerializeToString()
raw_body_size = len(body)
headers = {'x-log-bodyrawsize': str(raw_body_size), 'Content-Type': 'application/x-protobuf'}
if compress is None or compress:
i... | Put logs to log service. using raw data in protobuf
:type project: string
:param project: the Project name
:type logstore: string
:param logstore: the logstore name
:type log_group: LogGroup
:param log_group: log group structure
:type compress: bool... | null | null | null | |
def put_logs(self, request):
if len(request.get_log_items()) > 512000:
raise LogException('InvalidLogSize',
"logItems' length exceeds maximum limitation: 512000 lines. now: {0}".format(
len(request.get_log_items())))
... | Put logs to log service. up to 512000 logs up to 10MB size
Unsuccessful opertaion will cause an LogException.
:type request: PutLogsRequest
:param request: the PutLogs request parameters class
:return: PutLogsResponse
:raise: LogException | null | null | null | |
def list_logstores(self, request):
headers = {}
params = {}
resource = '/logstores'
project = request.get_project()
(resp, header) = self._send("GET", project, None, resource, params, headers)
return ListLogstoresResponse(resp, header) | List all logstores of requested project.
Unsuccessful opertaion will cause an LogException.
:type request: ListLogstoresRequest
:param request: the ListLogstores request parameters class.
:return: ListLogStoresResponse
:raise: LogException | null | null | null | |
def list_topics(self, request):
headers = {}
params = {}
if request.get_token() is not None:
params['token'] = request.get_token()
if request.get_line() is not None:
params['line'] = request.get_line()
params['type'] = 'topic'
log... | List all topics in a logstore.
Unsuccessful opertaion will cause an LogException.
:type request: ListTopicsRequest
:param request: the ListTopics request parameters class.
:return: ListTopicsResponse
:raise: LogException | null | null | null | |
def get_histograms(self, request):
headers = {}
params = {}
if request.get_topic() is not None:
params['topic'] = request.get_topic()
if request.get_from() is not None:
params['from'] = request.get_from()
if request.get_to() is not None:
... | Get histograms of requested query from log service.
Unsuccessful opertaion will cause an LogException.
:type request: GetHistogramsRequest
:param request: the GetHistograms request parameters class.
:return: GetHistogramsResponse
:raise: LogExce... | null | null | null | |
def get_log(self, project, logstore, from_time, to_time, topic=None,
query=None, reverse=False, offset=0, size=100):
# need to use extended method to get more when: it's not select query, and size > default page size
if not is_stats_query(query) and (int(size) == -1 or int... | Get logs from log service. will retry when incomplete.
Unsuccessful opertaion will cause an LogException.
Note: for larger volume of data (e.g. > 1 million logs), use get_log_all
:type project: string
:param project: project name
:type logstore: string
:param lo... | null | null | null | |
def get_logs(self, request):
project = request.get_project()
logstore = request.get_logstore()
from_time = request.get_from()
to_time = request.get_to()
topic = request.get_topic()
query = request.get_query()
reverse = request.get_reverse()
... | Get logs from log service.
Unsuccessful opertaion will cause an LogException.
Note: for larger volume of data (e.g. > 1 million logs), use get_log_all
:type request: GetLogsRequest
:param request: the GetLogs request parameters class.
:return: GetLogsResponse
... | null | null | null | |
def get_log_all(self, project, logstore, from_time, to_time, topic=None,
query=None, reverse=False, offset=0):
while True:
response = self.get_log(project, logstore, from_time, to_time, topic=topic,
query=query, reverse=reverse, o... | Get logs from log service. will retry when incomplete.
Unsuccessful opertaion will cause an LogException. different with `get_log` with size=-1,
It will try to iteratively fetch all data every 100 items and yield them, in CLI, it could apply jmes filter to
each batch and make it possible to f... | null | null | null | |
def get_project_logs(self, request):
headers = {}
params = {}
if request.get_query() is not None:
params['query'] = request.get_query()
project = request.get_project()
resource = "/logs"
(resp, header) = self._send("GET", project, None, resour... | Get logs from log service.
Unsuccessful opertaion will cause an LogException.
:type request: GetProjectLogsRequest
:param request: the GetProjectLogs request parameters class.
:return: GetLogsResponse
:raise: LogException | null | null | null | |
def get_cursor(self, project_name, logstore_name, shard_id, start_time):
headers = {'Content-Type': 'application/json'}
params = {'type': 'cursor',
'from': str(start_time) if start_time in ("begin", "end") else parse_timestamp(start_time)}
resource = "/logstor... | Get cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shard_id: int
... | null | null | null | |
def get_cursor_time(self, project_name, logstore_name, shard_id, cursor):
headers = {'Content-Type': 'application/json'}
params = {'type': 'cursor_time', 'cursor': cursor}
resource = "/logstores/" + logstore_name + "/shards/" + str(shard_id)
(resp, header) = self._send(... | Get cursor time from log service
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shard_id: int
:param shard_... | null | null | null | |
def get_previous_cursor_time(self, project_name, logstore_name, shard_id, cursor, normalize=True):
try:
pre_cursor_int = self._get_cursor_as_int(cursor) - 1
pre_cursor = e64(str(pre_cursor_int)).strip()
except Exception:
raise LogException("InvalidCur... | Get previous cursor time from log service.
Note: normalize = true: if the cursor is out of range, it will be nornalized to nearest cursor
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_na... | null | null | null | |
def get_begin_cursor(self, project_name, logstore_name, shard_id):
return self.get_cursor(project_name, logstore_name, shard_id, "begin") | Get begin cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shard_id: int
... | null | null | null | |
def get_end_cursor(self, project_name, logstore_name, shard_id):
return self.get_cursor(project_name, logstore_name, shard_id, "end") | Get end cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shard_id: int
... | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.