language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public String getName()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getName");
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "No implementation");
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
S... |
python | def scenario1_man():
"""
for loop in range(1, 50):
do_action(my_char, mining)
for loop in range(1, 50):
do_action(my_char, herb)
"""
for loop in range(1, 50):
do_action(my_char, rest)
do_action(my_char, think)
do_action(my_char, study)
do_action(my_char, tinker) |
python | def warn_attribs(loc,
node,
recognised_attribs,
reqd_attribs=None):
'''
Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with som... |
python | def create_backup(name):
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if success... |
java | private String
sanitize(String str) {
if (wordcase == CASE_UPPER)
return str.toUpperCase();
else if (wordcase == CASE_LOWER)
return str.toLowerCase();
return str;
} |
java | public void setSymbolType(final SymbolType SYMBOL_TYPE) {
symbolType = SYMBOL_TYPE;
init(getInnerBounds().width, getInnerBounds().height);
repaint(getInnerBounds());
} |
java | public void processLine(String line) throws CLIException {
if (lineProcessor != null) {
String out = lineProcessor.processLine(line);
if (out != null) {
output.output(out, outputConverter);
return;
} else {
// Exit from sub-shel... |
java | @Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public SpanContext injectExtract(Data data) throws SpanContextParseException {
Map<String, String> carrier = new HashMap<String, String>();
data.textFormatBase.inject(data.spanContext, carrier);
return data.textFormatBase... |
python | def ConsumeByteString(self):
"""Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed.
"""
the_list = [self._ConsumeSingleByteString()]
while self.token and self.token[0] in _QUOTES:
the_list.appen... |
python | def random(target, element, seed=None, num_range=[0, 1]):
r"""
Create an array of random numbers of a specified size.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides acc... |
java | public static void writeClass(String fileName, byte[] bytes) throws IOException {
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) {
out.write(bytes);
}
} |
python | def from_semiaxes(cls,axes):
"""
Get axis-aligned elliptical conic from axis lenths
This can be converted into a hyperbola by getting the dual conic
"""
ax = list(1/N.array(axes)**2)
#ax[-1] *= -1 # Not sure what is going on here...
arr = N.diag(ax + [-1])
... |
java | private static List<Map<String, Object>> handleResultSetToMapList(ResultSet result,
List<Map<String, Object>> listProperties)
throws SQLException {
// 存放记录的信息
Map<String, Object> property = null;
// 获取结果集中的列名
... |
python | def propagate(cls, date):
"""Compute the position of the sun at a given date
Args:
date (~beyond.utils.date.Date)
Return:
~beyond.orbits.orbit.Orbit: Position of the sun in MOD frame
Example:
.. code-block:: python
from beyond.util... |
python | def fluid_synth_write_s16_stereo(synth, len):
"""Return generated samples in stereo 16-bit format.
Return value is a Numpy array of samples.
"""
import numpy
buf = create_string_buffer(len * 4)
fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2)
return numpy.fromstring(buf[:], dtype=num... |
python | def image(self, captcha_str):
"""Generate a greyscale captcha image representing number string
Parameters
----------
captcha_str: str
string a characters for captcha image
Returns
-------
numpy.ndarray
Generated greyscale image in np.ndar... |
java | public void setApplicationsInfo(java.util.Collection<ApplicationInfo> applicationsInfo) {
if (applicationsInfo == null) {
this.applicationsInfo = null;
return;
}
this.applicationsInfo = new com.amazonaws.internal.SdkInternalList<ApplicationInfo>(applicationsInfo);
} |
java | public void organizationName_service_exchangeService_protocol_PUT(String organizationName, String exchangeService, OvhExchangeServiceProtocol body) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/protocol";
StringBuilder sb = path(qPath, organizationName, exchangeSe... |
python | def _build_command(self):
"""
Command to start the uBridge hypervisor process.
(to be passed to subprocess.Popen())
"""
command = [self._path]
command.extend(["-H", "{}:{}".format(self._host, self._port)])
if log.getEffectiveLevel() == logging.DEBUG:
... |
java | public java.util.List<NodeGroupMember> getNodeGroupMembers() {
if (nodeGroupMembers == null) {
nodeGroupMembers = new com.amazonaws.internal.SdkInternalList<NodeGroupMember>();
}
return nodeGroupMembers;
} |
python | def enable_events(self, event_callback=None) -> None:
"""Enable events for stream."""
self.event = EventManager(event_callback)
self.stream.event = self.event |
python | def routes(name, **kwargs):
'''
Manage network interface static routes.
name
Interface name to apply the route to.
kwargs
Named routes
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'Interface {0} routes are up to date.'.form... |
java | public boolean validateAccount(String token) throws DAOException {
Query q = new QueryBuilder().select().from(Credentials.class).where("validation", OPERAND.EQ, token).build();
TransientObject to = ObjectUtils.get1stOrNull(dao.query(q));
if (to != null) {
ServerCrede... |
python | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]... |
python | def expand_variable_dicts(
list_of_variable_dicts: 'List[Union[Dataset, OrderedDict]]',
) -> 'List[Mapping[Any, Variable]]':
"""Given a list of dicts with xarray object values, expand the values.
Parameters
----------
list_of_variable_dicts : list of dict or Dataset objects
Each value for t... |
python | def _finiCoXact(self):
'''
Note:
This method may raise a MapFullError
'''
assert s_glob.iAmLoop()
[scan.bump() for scan in self.scans]
# Readonly or self.xact has already been closed
if self.xact is None:
return
self.xact.commit... |
java | public void marshall(LayerVersionContentOutput layerVersionContentOutput, ProtocolMarshaller protocolMarshaller) {
if (layerVersionContentOutput == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(laye... |
python | def delete_answer(self, answer_id):
"""Deletes the ``Answer`` identified by the given ``Id``.
arg: answer_id (osid.id.Id): the ``Id`` of the ``Answer`` to
delete
raise: NotFound - an ``Answer`` was not found identified by the
given ``Id``
raise: Null... |
java | public static final Function<Float,Float> roundFloat(final int scale, final RoundingMode roundingMode) {
return new RoundFloat(scale, roundingMode);
} |
java | @SuppressWarnings("checkstyle:npathcomplexity")
void publishPartitionRuntimeState() {
if (!partitionStateManager.isInitialized()) {
// do not send partition state until initialized!
return;
}
if (!node.isMaster()) {
return;
}
if (!areMigr... |
java | private static AccessInfo getAccessInfo
(Class desiredClass,
int dataType, String dataTypeName, int columnSize, int decimalDigits)
{
if (!desiredClass.isPrimitive()) {
TypeDesc desiredType = TypeDesc.forClass(desiredClass);
if (desiredType.toPrimitiveType() != ... |
python | def proofMethods():
"""
Run the full protocol including proof generation and verification.
"""
r, x = blind(m)
y,kw,tTilde = eval(w,t,x,msk,s)
# Proof in Gt/Gt
pi = proveGt(x, tTilde, kw, y)
verifyGt(x, tTilde, y, pi, errorOnFail=True)
# Proof in G1/Gt
pi = proveG1(x, tTilde, k... |
python | def update_assessment_offered(self, assessment_offered_form):
"""Updates an existing assessment offered.
arg: assessment_offered_form
(osid.assessment.AssessmentOfferedForm): the form
containing the elements to be updated
raise: IllegalState - ``assessment_of... |
python | def main():
''' ChirpText Tools main function '''
app = CLIApp(desc='ChirpText Tools', logger=__name__, show_version=show_version)
# add tasks
vocab_task = app.add_task('vocab', func=gen_vocab)
vocab_task.add_argument('input', help='Input file')
vocab_task.add_argument('--output', help='Output f... |
python | def delete_asset(self, asset_id=None):
"""Deletes an ``Asset``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
remove
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to comp... |
python | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
... |
java | public static FunctionSQL newSQLFunction(String token,
CompileContext context) {
int id = regularFuncMap.get(token, -1);
if (id == -1) {
id = valueFuncMap.get(token, -1);
}
if (id == -1) {
return null;
}
FunctionSQL function = new F... |
java | public static String toLog(XmlTag data) {
if (data.channels == null) {
return data.getName() + "(" + data.getOwner() + ")";
} else {
return data.getName() + "(" + data.getOwner() + ")" + (data.channels);
}
} |
java | private void init(JSONTokener x) {
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
retur... |
java | private void encodeHandle(final FacesContext context, final SlideOut slideOut) throws IOException {
final ResponseWriter writer = context.getResponseWriter();
String styleClass = SlideOut.HANDLE_CLASS;
if (slideOut.getHandleStyleClass() != null) {
styleClass = styleClass + " " + sli... |
python | def feature_selection(df, labels, n_features, method='chi2'):
"""
Reduces the number of features in the imput dataframe.
Ex: labels = gs.meta['biospecimen_sample__sample_type_id'].apply(int).apply(lambda x: 0 if x < 10 else 1)
chi2_fs(gs.data, labels, 50)
:param df: The inpu... |
python | def getTerminalSize():
"""
returns (lines:int, cols:int)
"""
def ioctl_GWINSZ(fd):
# These two imports are only present on POSIX systems, so they must be
# guarded by a try block.
import fcntl
import termios
return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOC... |
java | protected void updateCurrentFolder(Collection<CmsUUID> removeIds) {
m_fileTable.update(removeIds, true);
CmsObject cms = A_CmsUI.getCmsObject();
try {
// current folder may be filtered, so we clear the filters and restore them later
// to make updates work for filtered o... |
java | public <T> DynamicType.Builder<T> rebase(TypeDescription type, ClassFileLocator classFileLocator) {
return rebase(type, classFileLocator, MethodNameTransformer.Suffixing.withRandomSuffix());
} |
python | def add_unique_runid(testcase, run_id=None):
"""Adds run id to the test description.
The `run_id` runs makes the descriptions unique between imports and force Polarion
to update every testcase every time.
"""
testcase["description"] = '{}<br id="{}"/>'.format(
testcase.get("description") or... |
java | private Object readValue(String value, Class<?> type) {
if (StringUtils.isEmpty(value)) {
return null;
}
if (byte.class.equals(type) || Byte.class.equals(type)) {
return Byte.valueOf(value);
} else if (short.class.equals(type) || Short.class.equals(type)) {
... |
python | def set_kwargs(self, code):
"""Sets widget from kwargs string
Parameters
----------
code: String
\tCode representation of kwargs value
"""
kwargs = {}
kwarglist = list(parse_dict_strings(code[1:-1]))
for kwarg, val in zip(kwarglist[::2], kwarg... |
python | def getattr(self, tid, fh=None):
"""
File attributes.
Parameters
----------
tid : str
Path to file. Original `path` argument is converted to tuple identifier by ``_pathdec`` decorator.
fh : int
File descriptor. Unnecessary, therefore ignored.
... |
java | public static <E> Queue<E> createConcurrentStack() {
return (Queue<E>) Collections.asLifoQueue(QueueUtil.newConcurrentNonBlockingDeque());
} |
python | def bltfrm(frmcls, outCell=None):
"""
Return a SPICE set containing the frame IDs of all built-in frames
of a specified class.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html
:param frmcls: Frame class.
:type frmcls: int
:param outCell: Optional SpiceInt Cell that is ... |
java | private static Timespan truncateDurationToUnit(long durationInMillis, TimeUnit timeUnit) {
Timespan res;
if (durationInMillis >= timeUnit.getMillisecondsCount()) {
res = new Timespan(durationInMillis / timeUnit.getMillisecondsCount(),
timeUnit);
} else {
... |
python | def set_fortpy_templates(obj, fortpy_templates=None):
"""Sets the directory path for the fortpy templates. If no directory
is specified, use the default one that shipped with the package.
"""
#If they didn't specify a custom templates directory, use the default
#one that shipped with the package.
... |
python | def tuple_sealer(fields, defaults):
"""
This sealer returns an equivalent of a ``namedtuple``.
"""
baseclass_name = 'FieldsBase_for__{0}'.format('__'.join(fields))
global_namespace, local_namespace = make_init_func(
fields, defaults, baseclass_name,
header_name='__new__',
hea... |
python | def rebuildPolygons(self, path):
"""
Rebuilds the polygons that will be used on this path.
:param path | <QPainterPath>
:return <list> [ <QPolygonF>, .. ]
"""
output = []
# create the input arrow
if self.showInputArrow():
... |
java | public static String escapeSqlLikePattern(String pattern, char escapeChar) {
char[] special = new char[] {escapeChar, '%', '_'};
String result = pattern;
for (char charToEscape : special) {
result = result.replaceAll("" + charToEscape, "" + escapeChar + charToEscape);
}
... |
java | public static int scopeString2Int(boolean ignoreScope, String type) {
type = StringUtil.toLowerCase(type);
char c = type.charAt(0);
// ignore scope only handles only reconize local,arguments as scope, the rest is ignored
if (ignoreScope) {
if ('a' == c) {
if ("arguments".equals(type)) return Scope.SCOPE_ARG... |
python | def oscltx(state, et, mu):
"""
Determine the set of osculating conic orbital elements that
corresponds to the state (position, velocity) of a body at some
epoch. In additional to the classical elements, return the true
anomaly, semi-major axis, and period, if applicable.
https://naif.jp... |
java | @Override
public ListenableFuture<Table> getTableAsync(GetTableRequest request) {
return createUnaryListener(request, getTableRpc, request.getName()).getAsyncResult();
} |
python | def extant_file(file):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(file):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: file does not exist
raise argparse.ArgumentTypeError("{0} ... |
python | def add_image(self, filename, *, width=NoEscape(r'0.8\textwidth'),
placement=NoEscape(r'\centering')):
"""Add an image to the figure.
Args
----
filename: str
Filename of the image.
width: str
The width of the image
placement: str... |
python | def process_multientry(entry_list, prod_comp, coeff_threshold=1e-4):
"""
Static method for finding a multientry based on
a list of entries and a product composition.
Essentially checks to see if a valid aqueous
reaction exists between the entries and the
product compositi... |
java | @Override
public void mark (@Nonnegative final int nReadAheadLimit) throws IOException
{
ValueEnforcer.isGE0 (nReadAheadLimit, "ReadAheadLimit");
_ensureOpen ();
m_nReadAheadLimit = nReadAheadLimit;
m_nMarkedChar = m_nNextCharIndex;
m_bMarkedSkipLF = m_bSkipLF;
} |
python | def match_rules_context(tree, rules, parent_context={}):
"""Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched... |
python | def hide(self):
""" Ensure the widget is hidden.
Calling this method will also set the widget visibility to False.
"""
self.visible = False
if self.proxy_is_active:
self.proxy.ensure_hidden() |
java | private static Properties convertDeprecatedProperties(Properties props) {
if (props.containsKey(RETENTION_DATE_TIME_PATTERN_KEY)) {
props.setProperty(org.apache.gobblin.data.management.version.finder.DateTimeDatasetVersionFinder.DATE_TIME_PATTERN_KEY, props.getProperty(RETENTION_DATE_TIME_PATTERN_KEY));
... |
python | def parse(bin_payload, recipient, update_hash ):
"""
# NOTE: first three bytes were stripped
"""
fqn = bin_payload
if not is_name_valid( fqn ):
log.warning("Name '%s' is invalid" % fqn)
return None
return {
'opcode': 'NAME_IMPORT',
'name': fqn,
're... |
java | public void write(String s, int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
int b = off, t = off + len;
while (b < t) {
int d = min(nChars - nextChar, t - b);
s.getChars(b, b + d, cb, nextChar);
b += ... |
python | def merge_leading_dims(array_or_tensor, n_dims=2):
"""Merge the first dimensions of a tensor.
Args:
array_or_tensor: Tensor to have its first dimensions merged. Can also
be an array or numerical value, which will be converted to a tensor
for batch application, if needed.
n_dims: Number of d... |
java | public static long[] nandI(long[] v, long[] o) {
int i = 0;
for(; i < o.length; i++) {
v[i] &= ~o[i];
}
return v;
} |
python | def rename(self, new_name):
"""Rename project and rename its root path accordingly."""
old_name = self.name
self.name = new_name
pypath = self.relative_pythonpath # ??
self.root_path = self.root_path[:-len(old_name)]+new_name
self.relative_pythonpath = pypath # ??... |
python | def make_break(lineno, p):
""" Checks if --enable-break is set, and if so, calls
BREAK keyboard interruption for this line if it has not been already
checked """
global last_brk_linenum
if not OPTIONS.enableBreak.value or lineno == last_brk_linenum or is_null(p):
return None
last_brk_l... |
python | def string_component_transform_factory(alg):
"""
Create a function to either transform a string or convert to a number.
Parameters
----------
alg : ns enum
Indicate how to format the *str*.
Returns
-------
func : callable
A function to be used as the *component_transfor... |
python | def blat(self, db=None, sequence=None, seq_type="DNA"):
"""
make a request to the genome-browsers BLAT interface
sequence is one of None, "mrna", "cds"
returns a list of features that are hits to this sequence.
"""
from . blat_blast import blat, blat_all
assert se... |
java | public <T> T executeSelect(String name, DataObject object, ResultSetWorker<T> worker) throws Exception {
ParametricQuery statement = (ParametricQuery)_statements.get(name);
if (statement != null) {
return statement.executeSelect(DataSourceUtils.getConnection(_dataSource), object, worker);... |
python | def parse_vars_and_interpolations(self, string):
"""Parse a string for variables and interpolations, but don't treat
anything else as Sass syntax. Returns an AST node.
"""
# Shortcut: if there are no #s or $s in the string in the first place,
# it must not have anything of inter... |
java | private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getModifiedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new L... |
java | void addColumn(String columnName)
{
data.add(new ArrayList<String>());
columnNames.add(columnName);
} |
python | def plot_cylinder(ax, start, end, start_radius, end_radius,
color='black', alpha=1., linspace_count=_LINSPACE_COUNT):
'''plot a 3d cylinder'''
assert not np.all(start == end), 'Cylinder must have length'
x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius,
... |
java | public MACAddressSection toEUI64(boolean asMAC) {
int originalSegmentCount = getSegmentCount();
if(!isExtended()) {
MACAddressCreator creator = getAddressCreator(addressSegmentIndex, true);
if(addressSegmentIndex + originalSegmentCount < 3 || addressSegmentIndex > 3) {
return this;
}
//we are... |
java | protected void closeQuietly(Closeable closeable) {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (Exception t) {
HTTP_LOGGER.warn("Unable to close {}: ", closeable, t);
}
} |
python | def change_breakpoint_state(self, bp_number, enabled, condition=None):
""" Change breakpoint status or `condition` expression.
:param bp_number: number of breakpoint to change
:return: None or an error message (string)
"""
if not (0 <= bp_number < len(IKBreakpoint.break... |
java | @EventHandler("change")
private void onChange(ChangeEvent event) {
// When the custom range item is selected, triggers the display of the date range dialog.
if (event.getRelatedTarget() == customItem) {
event.stopPropagation();
DateRangeDialog.show((range) -> {
... |
java | public static boolean hasRegistry(String imageName) {
if (imageName == null) {
throw new NullPointerException("Image name must not be null");
}
Matcher matcher = IMAGE_PATTERN.matcher(imageName);
if (!matcher.matches()) {
throw new IllegalArgumentException(imageN... |
python | def find_proxy(url, host=None):
"""
Finds proxy string for the given url and host. If host is not
defined, it's extracted from the url.
"""
if host is None:
m = _URL_REGEX.match(url)
if not m:
raise URLError(url)
if len(m.groups()) is 1:
host = m.groups()[0]
else:
raise URLEr... |
java | private void initializeDefaultTenant() {
DBService dbService = DBService.instance();
dbService.createNamespace();
dbService.createStoreIfAbsent(SchemaService.APPS_STORE_NAME, false);
dbService.createStoreIfAbsent(TaskManagerService.TASKS_STORE_NAME, false);
dbService.createStoreI... |
python | def edit_task(self, task_name, **kwargs):
""" Change the name of a Task owned by this Job.
This will affect the historical data available for this
Task, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} editing task {1}'.format(self.name, task_name))
... |
java | public com.sun.javadoc.Type superclassType() {
if (asClassDoc().isInterface()) {
return null;
}
Type sup = env.types.supertype(type);
return TypeMaker.getType(env,
(sup != type) ? sup : env.syms.objectType);
} |
python | def getlevel(self, threshold):
"""
Retrieve all clusters up to a specific level threshold. This
level-threshold represents the maximum distance between two clusters.
So the lower you set this threshold, the more clusters you will
receive and the higher you set it, you will receiv... |
python | def comment_marker(self, value):
"""
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... |
python | def get_hosts_files(option):
"""
Find out the location of the `hosts` file. This looks in multiple places
such as the `-i` option, current dir and ansible configuration files. The
first match is returned as a list.
"""
if option is not None:
return option.split(',')
# Use hosts file... |
python | def makedirs_perms(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=True):
'''
Set owner and permissions for each directory created.
Args:
path (str):
The full pat... |
python | def saveWallet(self, wallet, fpath):
"""Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fp... |
python | def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
) |
python | def get_extra_functions(self) -> Dict[str, Callable]:
"""Get a list of additional features
Returns:
Dict[str, Callable]: A dict of methods marked as additional features.
Method can be called with ``get_extra_functions()["methodName"]()``.
"""
methods = {}
... |
java | public static void updateInstrumentation(CollectorConfiguration config) throws Exception {
List<String> scripts = new ArrayList<String>();
List<String> scriptNames = new ArrayList<String>();
Map<String, Instrumentation> instrumentTypes=config.getInstrumentation();
for (Map.Entry<String,... |
python | def command(self, cmd, type=None):
"""
通过hunter调用gm指令,可调用hunter指令库中定义的所有指令,也可以调用text类型的gm指令
gm指令相关功能请参考safaia GM指令扩展模块
:param cmd: 指令
:param type: 语言,默认text
:return: None
"""
type = type or 'text'
self.hunter.script(cmd, lang=type) |
python | def log_request(self, handler):
"""
Override base method to log requests to JSON UDP collector and emit
a metric.
"""
packet = {'method': handler.request.method,
'uri': handler.request.uri,
'remote_ip': handler.request.remote_ip,
... |
python | def get_lastblock(cls, impl, working_dir):
"""
What was the last block processed?
Return the number on success
Return None on failure to read
"""
if not cls.db_exists(impl, working_dir):
return None
con = cls.db_open(impl, working_dir)
query =... |
python | def delete_route(route_table_id=None, destination_cidr_block=None,
route_table_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Deletes a route.
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16'... |
python | def port_profile_qos_profile_qos_cos_traffic_class(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.