code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def start_selection(self, selection_type=SelectionType.CHARACTERS):
self.selection_state = SelectionState(self.cursor_position, selection_type) | Take the current cursor position as the start of this selection. |
def prepare(self, context):
if __debug__:
log.debug("Assigning thread local request context.")
self.local.context = context | Executed prior to processing a request. |
def update(self):
cursor = u"█" if self._canvas.unicode_aware else "O"
back = u"░" if self._canvas.unicode_aware else "|"
try:
sb_pos = self._get_pos()
sb_pos = min(1, max(0, sb_pos))
sb_pos = max(int(self._height * sb_pos) - 1, 0)
except ZeroDivisionE... | Draw the scroll bar. |
def reset (self):
super(HttpUrl, self).reset()
self.headers = {}
self.auth = None
self.ssl_cipher = None
self.ssl_cert = None | Initialize HTTP specific variables. |
def Field(self, field, Value = None):
if Value == None:
try:
return self.__Bitmap[field]
except KeyError:
return None
elif Value == 1 or Value == 0:
self.__Bitmap[field] = Value
else:
raise ValueError | Add field to bitmap |
def fulltext_delete(self, index, docs=None, queries=None):
xml = Document()
root = xml.createElement('delete')
if docs:
for doc in docs:
doc_element = xml.createElement('id')
text = xml.createTextNode(doc)
doc_element.appendChild(text)
... | Removes documents from the full-text index. |
def squawk(self) -> Set[str]:
return set(self.data.squawk.ffill().bfill()) | Returns all the unique squawk values in the trajectory. |
def _visit_filesystem(self):
self.logger.debug("Parsing File System content.")
root_partition = self._filesystem.inspect_get_roots()[0]
yield from self._root_dirent()
for entry in self._filesystem.filesystem_walk(root_partition):
yield Dirent(
entry['tsk_inode... | Walks through the filesystem content. |
def echo_attributes(request,
config_loader_path=None,
template='djangosaml2/echo_attributes.html'):
state = StateCache(request.session)
conf = get_config(config_loader_path, request)
client = Saml2Client(conf, state_cache=state,
identity_cache... | Example view that echo the SAML attributes of an user |
def showHostDivision(self, headless):
scoop.logger.info('Worker d--istribution: ')
for worker, number in self.worker_hosts:
first_worker = (worker == self.worker_hosts[0][0])
scoop.logger.info(' {0}:\t{1} {2}'.format(
worker,
number - 1 if first_... | Show the worker distribution over the hosts. |
def establish_scp_conn(self):
ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
self.scp_conn.connect(**ssh_connect_params)
self.scp_client = scp.SCPClient(self.scp_conn.get_transport()) | Establish the secure copy connection. |
def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
dt = d.isoformat(" ")
return _mysql.string_literal(dt, c) | Format a DateTime object as something MySQL will actually accept. |
def _asciify_list(data):
ret = []
for item in data:
if isinstance(item, unicode):
item = _remove_accents(item)
item = item.encode('utf-8')
elif isinstance(item, list):
item = _asciify_list(item)
elif isinstance(item, dict):
item = _asciify_... | Ascii-fies list values |
def copy_directory(src, dest, force=False):
if os.path.exists(dest) and force is True:
shutil.rmtree(dest)
try:
shutil.copytree(src, dest)
except OSError as e:
if e.errno == errno.ENOTDIR:
shutil.copy(src, dest)
else:
bot.error('Directory not copied. E... | Copy an entire directory recursively |
def supernodes(self, reordered = True):
if reordered:
return [list(self.snode[self.snptr[k]:self.snptr[k+1]]) for k in range(self.Nsn)]
else:
return [list(self.__p[self.snode[self.snptr[k]:self.snptr[k+1]]]) for k in range(self.Nsn)] | Returns a list of supernode sets |
def _disallow_state(self, state):
disallow_methods = (self._is_duplicate_board,
self._is_impossible_by_count)
for disallow_method in disallow_methods:
if disallow_method(state):
return True
return False | Disallow states that are not useful to continue simulating. |
def find_atomics(formula: Formula) -> Set[PLAtomic]:
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
else:
res.add(f)
return res | Finds all the atomic formulas |
def ae_core_density(self):
mesh, values, attrib = self._parse_radfunc("ae_core_density")
return RadialFunction(mesh, values) | The all-electron radial density. |
def auto_start_vm(self):
if self.enable:
try:
yield from self.start()
except GNS3VMError as e:
try:
yield from self._controller.add_compute(compute_id="vm",
name="GNS3 VM ({})"... | Auto start the GNS3 VM if require |
def organization_inspect_template_path(cls, organization, inspect_template):
return google.api_core.path_template.expand(
"organizations/{organization}/inspectTemplates/{inspect_template}",
organization=organization,
inspect_template=inspect_template,
) | Return a fully-qualified organization_inspect_template string. |
async def on_raw(self, message):
self.logger.debug('<< %s', message._raw)
if not message._valid:
self.logger.warning('Encountered strictly invalid IRC message from server: %s',
message._raw)
if isinstance(message.command, int):
cmd = str(me... | Handle a single message. |
def real(self):
return matrix(self.tt.real(), n=self.n, m=self.m) | Return real part of a matrix. |
def _extrapolation(self, extrapolate):
modes = ['extrapolate',
'raise',
'const',
'border']
if extrapolate not in modes:
msg = 'invalid extrapolation mode {}'.format(extrapolate)
raise ValueError(msg)
if extrapolate == 'ra... | Check permited values of extrapolation. |
def subclasses(cls):
seen = set()
queue = set([cls])
while queue:
c = queue.pop()
seen.add(c)
sc = c.__subclasses__()
for c in sc:
if c not in seen:
queue.add(c)
seen.remove(cls)
return seen | Return a set of all Ent subclasses, recursively. |
def saveDbf(self, target):
if not hasattr(target, "write"):
target = os.path.splitext(target)[0] + '.dbf'
self.dbf = self.__getFileObj(target)
self.__dbfHeader()
self.__dbfRecords() | Save a dbf file. |
def execute_command(self, request, command, frame):
return Response(frame.console.eval(command), mimetype="text/html") | Execute a command in a console. |
def add_config_path(path):
if not os.path.isfile(path):
warnings.warn("Config file does not exist: {path}".format(path=path))
return False
_base, ext = os.path.splitext(path)
if ext and ext[1:] in PARSERS:
parser = ext[1:]
else:
parser = PARSER
parser_class = PARSERS[... | Select config parser by file extension and add path into parser. |
def copy(self, existing_inputs):
return PPOPolicyGraph(
self.observation_space,
self.action_space,
self.config,
existing_inputs=existing_inputs) | Creates a copy of self using existing input placeholders. |
def __setup_dfs_data(graph, adj):
dfs_data = __get_dfs_data(graph, adj)
dfs_data['graph'] = graph
dfs_data['adj'] = adj
L1, L2 = __low_point_dfs(dfs_data)
dfs_data['lowpoint_1_lookup'] = L1
dfs_data['lowpoint_2_lookup'] = L2
edge_weights = __calculate_edge_weights(dfs_data)
dfs_data['edg... | Sets up the dfs_data object, for consistency. |
def resolve_addresses(user, useralias, to, cc, bcc):
addresses = {"recipients": []}
if to is not None:
make_addr_alias_target(to, addresses, "To")
elif cc is not None and bcc is not None:
make_addr_alias_target([user, useralias], addresses, "To")
else:
addresses["recipients"].app... | Handle the targets addresses, adding aliases when defined |
def print_object(self, tobj):
if tobj.death:
self.stream.write('%-32s ( free ) %-35s\n' % (
trunc(tobj.name, 32, left=1), trunc(tobj.repr, 35)))
else:
self.stream.write('%-32s 0x%08x %-35s\n' % (
trunc(tobj.name, 32, left=1),
tobj... | Print the gathered information of object `tobj` in human-readable format. |
def selection_pos(self):
buff = self._vim.current.buffer
beg = buff.mark('<')
end = buff.mark('>')
return beg, end | Return start and end positions of the visual selection respectively. |
def bundles():
for bundle in sorted(bundles_module.bundles.keys()):
if bundle.startswith('.'):
continue
try:
ingestions = list(
map(text_type, bundles_module.ingestions_for_bundle(bundle))
)
except OSError as e:
if e.errno != er... | List all of the available data bundles. |
def mark_as_required(self):
if self not in tf.get_collection(bookkeeper.GraphKeys.MARKED_LOSSES):
tf.add_to_collection(bookkeeper.GraphKeys.MARKED_LOSSES, self) | Adds this loss to the MARKED_LOSSES collection. |
def fix_flags(self, flags):
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but not both.')
if not (flags.logdir or flags.event_file)... | Fixes standard TensorBoard CLI flags to parser. |
def entropy(string):
entropy = 0
for number in range(256):
result = float(string.encode('utf-8').count(
chr(number))) / len(string.encode('utf-8'))
if result != 0:
entropy = entropy - result * math.log(result, 2)
return entropy | Calculate the entropy of a string. |
def url_report(self, scan_url, apikey):
url = self.base_url + "url/report"
params = {"apikey": apikey, 'resource': scan_url}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, params=params, headers=self.headers)
if response.st... | Send URLS for list of past malicous associations |
def _get_framed(self, buf, offset, insert_payload):
header_offset = offset + self._header_len
self.length = insert_payload(buf, header_offset, self.payload)
struct.pack_into(self._header_fmt,
buf,
offset,
self.preamble,
self... | Returns the framed message and updates the CRC. |
def check(self, data):
if isinstance(data, Iterable):
data = "".join(str(x) for x in data)
try:
data = str(data)
except UnicodeDecodeError:
return False
return bool(data and self.__regexp.match(data)) | returns True if any match any regexp |
def Get(self):
args = user_pb2.ApiGetClientApprovalArgs(
client_id=self.client_id,
approval_id=self.approval_id,
username=self.username)
result = self._context.SendRequest("GetClientApproval", args)
return ClientApproval(
data=result, username=self._context.username, context=... | Fetch and return a proper ClientApproval object. |
def index(self):
c.pynipap_version = pynipap.__version__
try:
c.nipapd_version = pynipap.nipapd_version()
except:
c.nipapd_version = 'unknown'
c.nipap_db_version = pynipap.nipap_db_version()
return render('/version.html') | Display NIPAP version info |
def open_recruitment(self, n=1):
logger.info("Multi recruitment running for {} participants".format(n))
recruitments = []
messages = {}
remaining = n
for recruiter, count in self.recruiters(n):
if not count:
break
if recruiter.nickname in m... | Return initial experiment URL list. |
def datetime(self):
date_string = '%s %s %s' % (self._day,
self._date,
self._year)
return datetime.strptime(date_string, '%a %B %d %Y') | Returns a datetime object representing the date the game was played. |
def fixed(self):
decision = False
for record in self.history:
if record["when"] < self.options.since.date:
continue
if not decision and record["when"] < self.options.until.date:
for change in record["changes"]:
if (change["field... | Moved to MODIFIED and not later moved to ASSIGNED |
def delete(self, *args, **kwargs):
super(UpdateCountsMixin, self).delete(*args, **kwargs)
self.update_count() | custom delete method to update counts |
def manifest_path_is_old(self, path):
mtime = os.path.getmtime(path)
return (time.time() - mtime) > 24*60*60 | return true if path is more than a day old |
def to_add(self):
kwd = {
'pager': '',
}
self.render('misc/entity/entity_add.html',
cfg=config.CMS_CFG,
kwd=kwd,
userinfo=self.userinfo) | To add the entity. |
def setNewPassword(self, url, username, password):
self.br.add_password(url, username, password) | Public method to manually set the credentials for a url in the browser. |
def _build_dependent_model_list(self, obj_schema):
dep_models_list = []
if obj_schema:
obj_schema['type'] = obj_schema.get('type', 'object')
if obj_schema['type'] == 'array':
dep_models_list.extend(self._build_dependent_model_list(obj_schema.get('items', {})))
els... | Helper function to build the list of models the given object schema is referencing. |
def _begin_request(self):
headers = self.m2req.headers
self._request = HTTPRequest(connection=self,
method=headers.get("METHOD"),
uri=self.m2req.path,
version=headers.get("VERSION"),
headers=headers,
remote_ip=headers.get("x-forwarded-for"))
... | Actually start executing this request. |
def _send_request(self):
if isinstance(self._worker, str):
classname = self._worker
else:
classname = '%s.%s' % (self._worker.__module__,
self._worker.__name__)
self.request_id = str(uuid.uuid4())
self.send({'request_id': self.re... | Sends the request to the backend. |
def checkVersion(self):
r = self.doQuery('version')
if r.status_code == 200:
data = r.json()
if data['result'] == 'Ok' and data['version'] == self.PI_API_VERSION and data['protocol'] == self.PI_API_NAME:
return True
return False | Check if the server use the same version of our protocol |
def next(self):
if self._order_by == 'oldest':
return self.newer
if self._order_by == 'newest':
return self.older
return None | Gets the next page, respecting sort order |
def transformation(func):
@wraps(func)
def func_as_transformation(*args, **kwargs):
if hasattr(args[0], 'history'):
history = args[0].history
else:
history = []
image = func(*args, **kwargs)
image = Image.from_array(image, log_in_history=False)
ima... | Function decorator to turn another function into a transformation. |
def rows(self, offs):
lkey = s_common.int64en(offs)
for lkey, byts in self.slab.scanByRange(lkey, db=self.db):
indx = s_common.int64un(lkey)
yield indx, byts | Iterate over raw indx, bytes tuples from a given offset. |
def profile_dir(name):
if name:
possible_path = Path(name)
if possible_path.exists():
return possible_path
profiles = list(read_profiles())
try:
if name:
profile = next(p for p in profiles if p.name == name)
else:
profile = next(p for p in ... | Return path to FF profile for a given profile name or path. |
def assign_contributor_permissions(obj, contributor=None):
for permission in get_all_perms(obj):
assign_perm(permission, contributor if contributor else obj.contributor, obj) | Assign all permissions to object's contributor. |
def create_table(self, model_class):
if model_class.is_system_model():
raise DatabaseException("You can't create system table")
if getattr(model_class, 'engine') is None:
raise DatabaseException("%s class must define an engine" % model_class.__name__)
self._send(model_cla... | Creates a table for the given model class, if it does not exist already. |
def imdecode(image_path):
import os
assert os.path.exists(image_path), image_path + ' not found'
im = cv2.imread(image_path)
return im | Return BGR image read by opencv |
def timeit_profile(stmt, number, repeat, setup,
profiler_factory, pickle_protocol, dump_filename, mono,
**_ignored):
del _ignored
globals_ = {}
exec_(setup, globals_)
if number is None:
dummy_profiler = profiler_factory()
dummy_profiler.start()
... | Profile a Python statement like timeit. |
def action_set(values):
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd) | Sets the values to be returned after the action finishes |
def filter(self, intersects):
try:
crs = self.crs
vector = intersects.geometry if isinstance(intersects, GeoFeature) else intersects
prepared_shape = prep(vector.get_shape(crs))
hits = []
for feature in self:
target_shape = feature.geom... | Filter results that intersect a given GeoFeature or Vector. |
def dpsi2_dmuS(self, dL_dpsi2, Z, mu, S, target_mu, target_S):
self._psi_computations(Z, mu, S)
tmp = (self.inv_lengthscale2 * self._psi2[:, :, :, None]) / self._psi2_denom
target_mu += -2.*(dL_dpsi2[:, :, :, None] * tmp * self._psi2_mudist).sum(1).sum(1)
target_S += (dL_dpsi2[:, :, :, N... | Think N,num_inducing,num_inducing,input_dim |
def locate_path(dname, recurse_down=True):
tried_fpaths = []
root_dir = os.getcwd()
while root_dir is not None:
dpath = join(root_dir, dname)
if exists(dpath):
return dpath
else:
tried_fpaths.append(dpath)
_new_root = dirname(root_dir)
if _new_... | Search for a path |
def userinfo_claims(self, access_token, scope_request, claims_request):
id_token = oidc.userinfo(access_token, scope_request, claims_request)
return id_token.claims | Return the claims for the requested parameters. |
def validate(text, file, schema_type):
content = None
if text:
print('Validating text input...')
content = text
if file:
print('Validating file input...')
content = file.read()
if content is None:
click.secho('Please give either text input or a file path. See help... | Validate JSON input using dependencies-schema |
def _copy(self):
ins = copy.copy(self)
ins._fire_page_number(self.page_number + 1)
return ins | needs to update page numbers |
def _read_interleaved(self, f, data_objects):
log.debug("Reading interleaved data point by point")
object_data = {}
points_added = {}
for obj in data_objects:
object_data[obj.path] = obj._new_segment_data()
points_added[obj.path] = 0
while any([points_adde... | Read interleaved data that doesn't have a numpy type |
def request_length(self):
remainder = self.stop_at - self.offset
return self.chunk_size if remainder > self.chunk_size else remainder | Return length of next chunk upload. |
def _query(options, collection_name, num_to_skip,
num_to_return, query, field_selector, opts, check_keys):
encoded = _dict_to_bson(query, check_keys, opts)
if field_selector:
efs = _dict_to_bson(field_selector, False, opts)
else:
efs = b""
max_bson_size = max(len(encoded), len... | Get an OP_QUERY message. |
def _characterize_header(self, header, hgroups):
out = []
for h in [header[g[0]] for g in hgroups]:
this_ctype = None
for ctype, names in self._col_types.items():
if h.startswith(names):
this_ctype = ctype
break
... | Characterize header groups into different data types. |
def update(self, permission):
self.needs.update(permission.needs)
self.excludes.update(permission.excludes) | In-place update of permissions. |
def profiles(self):
selected_profiles = []
for config in self.included_profiles:
profile_selected = False
profile_name = config.get('profile_name')
if profile_name == self.args.profile:
profile_selected = True
elif config.get('group') is no... | Return all selected profiles. |
def compute_transitive_deps_by_target(self, targets):
sorted_targets = reversed(sort_targets(targets))
transitive_deps_by_target = defaultdict(set)
for target in sorted_targets:
transitive_deps = set()
for dep in target.dependencies:
transitive_deps.update(transitive_deps_by_target.get(d... | Map from target to all the targets it depends on, transitively. |
def which(component, path_str):
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(component)
if fpath:
if is_exe(component):
return component
else:
for path in path_str.split(os.pathsep):
exe_file = ... | helper method having same behaviour as "which" os command. |
def sharedFiles(self):
'iterate over shared files and get their public URI'
for f in self.sharing.files.iterchildren():
yield (f.attrib['name'], f.attrib['uuid'],
'https://www.jottacloud.com/p/%s/%s' % (self.jfs.username, f.publicURI.text)) | iterate over shared files and get their public URI |
def new_game(self):
self.game = self.game_class(self, self.screen)
self.save() | Creates a new game of 2048. |
def to_esc(self):
chunks = chunked(self.stream, 2)
return ''.join(r'\x' + ''.join(pair) for pair in chunks) | Convert to escape string. |
def find_release(package, releases, dependencies=None):
dependencies = dependencies if dependencies is not None else {}
for release in releases:
url = release['url']
old_priority = dependencies.get(package, {}).get('priority', 0)
for suffix, priority in SUFFIXES.items():
if u... | Return the best release. |
def getpreferredencoding():
_encoding = locale.getpreferredencoding(False)
if six.PY2 and not sys.platform == "win32":
_default_encoding = locale.getdefaultlocale()[1]
if _default_encoding is not None:
_encoding = _default_encoding
return _encoding | Determine the proper output encoding for terminal rendering |
def _mark_master_dead(self, master):
if self._syndics[master].done():
syndic = self._syndics[master].result()
self._syndics[master] = syndic.reconnect()
else:
log.info(
'Attempting to mark %s as dead, although it is already '
'marked de... | Mark a master as dead. This will start the sign-in routine |
def update(self, milliseconds):
self.__sort_up()
for obj in self.__up_objects:
obj.update(milliseconds) | Updates all of the objects in our world. |
def _find_devices_mac(self):
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) | Find devices on Mac. |
def list_eids(self):
entities = self.list()
return sorted([int(eid) for eid in entities]) | Returns a list of all known eids |
def _calculate_cluster_distance(end_iter):
out = []
sizes = []
for x in end_iter:
out.append(x)
sizes.append(x.end1 - x.start1)
sizes.append(x.end2 - x.start2)
distance = sum(sizes) // len(sizes)
return distance, out | Compute allowed distance for clustering based on end confidence intervals. |
def state_pop(self):
"Restore the state of the output functions saved by state_push."
for of in self.output_fns:
if hasattr(of,'state_pop'):
of.state_pop()
super(PatternGenerator, self).state_pop() | Restore the state of the output functions saved by state_push. |
def upsert(cls, name, **fields):
instance = cls.get(name)
if instance:
instance._set_fields(fields)
else:
instance = cls(name=name, **fields)
instance = failsafe_add(cls.query.session, instance, name=name)
return instance | Insert or update an instance |
def url_to_attrs_dict(url, url_attr):
result = dict()
if isinstance(url, six.string_types):
url_value = url
else:
try:
url_value = url["url"]
except TypeError:
raise BootstrapError(
'Function "url_to_attrs_dict" expects a string or a dict with ... | Sanitize url dict as used in django-bootstrap3 settings. |
def _reinsert_root_tag_prefix(v):
if hasattr(v, 'original_prefix'):
original_prefix = v.original_prefix
del v.original_prefix
v.tag = ''.join(('{', v.nsmap[original_prefix], '}VOEvent'))
return | Returns namespace prefix to root tag, if it had one. |
def pubkey(self, identity, ecdh=False):
with self.device:
pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
return formats.decompress_pubkey(
pubkey=pubkey, curve_name=identity.curve_name) | Return public key as VerifyingKey object. |
def generate_image_from_url(url=None, timeout=30):
file_name = posixpath.basename(url)
img_tmp = NamedTemporaryFile(delete=True)
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status()
except Exception as e:
return None, None
img_tmp.write(response.cont... | Downloads and saves a image from url into a file. |
def _add_observation_to_means(self, xj, yj):
self._mean_x_in_window = ((self.window_size * self._mean_x_in_window + xj) /
(self.window_size + 1.0))
self._mean_y_in_window = ((self.window_size * self._mean_y_in_window + yj) /
(self.windo... | Update the means without recalculating for the addition of one observation. |
def sign_nonce(key, nonce):
return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest() | sign the server nonce from the WWW-Authenticate header with an authKey |
def flux_expr(self, reaction):
if isinstance(reaction, dict):
return self._v.expr(iteritems(reaction))
return self._v(reaction) | Get LP expression representing the reaction flux. |
def _nonblocking_read(self):
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
return 0
if data:
self.unprocessed_bytes.... | Returns the number of characters read and adds them to self.unprocessed_bytes |
def cancel(ctx, orders, account):
print_tx(ctx.bitshares.cancel(orders, account=account)) | Cancel one or multiple orders |
def datagramReceived(self, data):
try:
obj = json.loads(data)
except ValueError, e:
log.err(e, 'Invalid JSON in stream: %r' % data)
return
if u'text' in obj:
obj = Status.fromDict(obj)
else:
log.msg('Unsupported object %r' % obj... | Decode the JSON-encoded datagram and call the callback. |
def class_in_progress(stack=None):
if stack is None:
stack = inspect.stack()
for frame in stack:
statement_list = frame[4]
if statement_list is None:
continue
if statement_list[0].strip().startswith('class '):
return True
return False | True if currently inside a class definition, else False. |
def check_gcdt_update():
try:
inst_version, latest_version = get_package_versions('gcdt')
if inst_version < latest_version:
log.warn('Please consider an update to gcdt version: %s' %
latest_version)
except GracefulExit:
raise
except Except... | Check whether a newer gcdt is available and output a warning. |
def perform_srl(responses, prompt):
predictor = Predictor.from_path("https://s3-us-west-2.amazonaws.com/allennlp/models/srl-model-2018.05.25.tar.gz")
sentences = [{"sentence": prompt + " " + response} for response in responses]
output = predictor.predict_batch_json(sentences)
full_output = [{"sentence":... | Perform semantic role labeling on a list of responses, given a prompt. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.