language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def add_sort(self, field, ascending=True):
"""Sort the search results by a certain field.
If this method is called multiple times, the later sort fields are given lower priority,
and will only be considered when the eariler fields have the same value.
Arguments:
field (str): The field to sort by.
The field must be namespaced according to Elasticsearch rules
using the dot syntax.
For example, ``"mdf.source_name"`` is the ``source_name`` field
of the ``mdf`` dictionary.
ascending (bool): If ``True``, the results will be sorted in ascending order.
If ``False``, the results will be sorted in descending order.
**Default**: ``True``.
Returns:
SearchHelper: Self
"""
# No-op on blank field
if not field:
return self
self._add_sort(field, ascending=ascending)
return self |
python | def _parse_arguments():
"""Return a parser context result."""
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() |
python | def _to_java_object_rdd(rdd):
""" Return an JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer()))
return rdd.ctx._jvm.org.apache.spark.ml.python.MLSerDe.pythonToJava(rdd._jrdd, True) |
python | def open_magnet(self):
"""Open magnet according to os."""
if sys.platform.startswith('linux'):
subprocess.Popen(['xdg-open', self.magnet],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
elif sys.platform.startswith('win32'):
os.startfile(self.magnet)
elif sys.platform.startswith('cygwin'):
os.startfile(self.magnet)
elif sys.platform.startswith('darwin'):
subprocess.Popen(['open', self.magnet],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
subprocess.Popen(['xdg-open', self.magnet],
stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
python | def _mean_prediction(self, mu, Y, h, t_z):
""" Creates a h-step ahead mean prediction
Parameters
----------
mu : np.ndarray
The past predicted values
Y : np.ndarray
The past data
h : int
How many steps ahead for the prediction
t_z : np.ndarray
A vector of (transformed) latent variables
Returns
----------
h-length vector of mean predictions
"""
# Create arrays to iteratre over
Y_exp = Y.copy()
# Loop over h time periods
for t in range(0,h):
new_value = self.predict_new(Y_exp[-self.ar:][::-1], self.latent_variables.get_z_values())
Y_exp = np.append(Y_exp, [self.link(new_value)])
return Y_exp |
python | def execute_policy(self, scaling_group, policy):
"""
Executes the specified policy for the scaling group.
"""
return self._manager.execute_policy(scaling_group=scaling_group,
policy=policy) |
python | def init():
"""
Execute init tasks for all components (virtualenv, pip).
"""
print(yellow("# Setting up environment...\n", True))
virtualenv.init()
virtualenv.update_requirements()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your virtual environment.")) |
java | private boolean isCsvField(final String field, final ValidationContext<Object> validationContext) {
return validationContext.getBeanMapping().getColumnMapping(field).isPresent();
} |
python | def softmax_last_timestep_class_label_top(body_output,
targets,
model_hparams,
vocab_size):
"""Loss for class label."""
del targets # unused arg
with tf.variable_scope(
"softmax_last_timestep_onehot_class_label_modality_%d_%d" % (
vocab_size, model_hparams.hidden_size)):
x = body_output
x = tf.expand_dims(x[:, -1], 1) # Pick the last timestep
return tf.layers.dense(x, vocab_size) |
python | def get_repositories_and_digests(self):
"""
Returns a map of images to their repositories and a map of media types to each digest
it creates a map of images to digests, which is need to create the image->repository
map and uses the same loop structure as media_types->digest, but the image->digest
map isn't needed after we have the image->repository map and can be discarded.
"""
digests = {} # image -> digests
typed_digests = {} # media_type -> digests
for registry in self.workflow.push_conf.docker_registries:
for image in self.workflow.tag_conf.images:
image_str = image.to_str()
if image_str in registry.digests:
image_digests = registry.digests[image_str]
if self.report_multiple_digests and get_pulp(self.workflow, None):
digest_list = [digest for digest in (image_digests.v1,
image_digests.v2)
if digest]
else:
digest_list = [self.select_digest(image_digests)]
digests[image.to_str(registry=False)] = digest_list
for digest_version in image_digests.content_type:
if digest_version not in image_digests:
continue
if not get_pulp(self.workflow, None) and digest_version == 'v1':
continue
digest_type = get_manifest_media_type(digest_version)
typed_digests[digest_type] = image_digests[digest_version]
if self.workflow.push_conf.pulp_registries:
# If pulp was used, only report pulp images
registries = self.workflow.push_conf.pulp_registries
else:
# Otherwise report all the images we pushed
registries = self.workflow.push_conf.all_registries
repositories = []
for registry in registries:
image = self.pullspec_image.copy()
image.registry = registry.uri
pullspec = image.to_str()
repositories.append(pullspec)
digest_list = digests.get(image.to_str(registry=False), ())
for digest in digest_list:
digest_pullspec = image.to_str(tag=False) + "@" + digest
repositories.append(digest_pullspec)
return repositories, typed_digests |
python | def setup(self,
np=np,
numpy_version=numpy_version,
StrictVersion=StrictVersion,
new_pandas=new_pandas):
"""Lives in zipline.__init__ for doctests."""
if numpy_version >= StrictVersion('1.14'):
self.old_opts = np.get_printoptions()
np.set_printoptions(legacy='1.13')
else:
self.old_opts = None
if new_pandas:
self.old_err = np.geterr()
# old pandas has numpy compat that sets this
np.seterr(all='ignore')
else:
self.old_err = None |
java | public String setExtensionHandlerClass(String handlerClassName) {
String oldvalue = m_extensionHandlerClass;
m_extensionHandlerClass = handlerClassName;
return oldvalue;
} |
python | def unschedule(self, task_name):
'''
Removes a task from scheduled jobs but it will not kill running tasks
'''
for greenlet in self.waiting[task_name]:
try:
gevent.kill(greenlet)
except BaseException:
pass |
python | def widths_in_range_mm(
self,
minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM,
maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM
):
"""Return list of slitlets which width is within given range
Parameters
----------
minwidth : float
Minimum slit width (mm).
maxwidth : float
Maximum slit width (mm).
Returns
-------
list_ok : list
List of booleans indicating whether the corresponding
slitlet width is within range
"""
list_ok = []
for i in range(EMIR_NBARS):
slitlet_ok = minwidth <= self._csu_bar_slit_width[i] <= maxwidth
if slitlet_ok:
list_ok.append(i + 1)
return list_ok |
java | protected String getStringParameter(String key, JobInstance ji, boolean pop)
{
// First try: parameter name with specific RM key.
String res = ji.getPrms().get(getParameterRoot() + this.key + "." + key);
if (res != null && pop)
{
ji.getPrms().remove(getParameterRoot() + this.key + "." + key);
}
// Second try: parameter name without specific key (used by all RM of this type)
if (res == null)
{
res = ji.getPrms().get(getParameterRoot() + key);
if (res != null && pop)
{
ji.getPrms().remove(getParameterRoot() + key);
}
}
// Third try: just use value from RM configuration (which may be a hard-coded default).
if (res == null)
{
res = this.currentProperties.get(getParameterRoot() + key);
}
// Go. Third try is by convention always supposed to succeed - all keys should have a default value.
return res;
} |
java | @Override
public void createLogoutCookies(HttpServletRequest req, HttpServletResponse res) {
createLogoutCookies(req, res, true);
} |
python | def get_obj(app_label, model_name, object_id):
"""
Function used to get a object
:param app_label: A valid Django Model or a string with format: <app_label>.<model_name>
:param model_name: Key into kwargs that contains de data: new_person
:param object_id:
:return: instance
"""
try:
model = apps.get_model("{}.{}".format(app_label, model_name))
assert is_valid_django_model(model), ("Model {}.{} do not exist.").format(
app_label, model_name
)
obj = get_Object_or_None(model, pk=object_id)
return obj
except model.DoesNotExist:
return None
except LookupError:
pass
except ValidationError as e:
raise ValidationError(e.__str__())
except TypeError as e:
raise TypeError(e.__str__())
except Exception as e:
raise Exception(e.__str__()) |
java | private void instrument(CtClass proxy, final SchemaPropertyRef ref) throws Exception {
final Schema schema = schemas.get(ref.getSchemaName());
checkNotNull(schema, "Schema not found for SchemaPropertyRef ["+ref+"]");
final String fieldName = ref.getFieldName();
// for help on javassist syntax, see chapter around javassist.expr.FieldAccess at
// http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/tutorial/tutorial2.html#before
proxy.instrument(new ExprEditor() {
public void edit(FieldAccess f) throws CannotCompileException {
if (f.getFieldName().equals(ref.getFieldName())) {
StringBuilder code = new StringBuilder();
code.append("{");
code.append("$_=("+schema.getType()+") this."+PROXY_FIELD_NAME+".getObjectReference(\""+fieldName+"\", \""+schema.getName()+"\");");
code.append("}");
f.replace(code.toString());
}
}
});
} |
python | def update_base_dict(self, yamlfile):
"""Update the values in baseline dictionary used to resolve names
"""
self.base_dict.update(**yaml.safe_load(open(yamlfile))) |
java | public boolean getBooleanResult(final CharSequence equation) {
final Element result = new ValueElement(getResult(equation), null, null);
if (result.isBoolean()) {
return result.getBoolean();
} else if (result.isInt()) {
return result.getInt() > 0;
} else if (result.isFloat()) {
return result.getFloat() > 0f;
}
return !isNullOrFalse(result.getString());
} |
java | @Nonnull
public static WebSiteResourceWithCondition createForCSS (@Nonnull final ICSSPathProvider aPP, final boolean bRegular)
{
return createForCSS (aPP.getCSSItemPath (bRegular),
aPP.getConditionalComment (),
aPP.isBundlable (),
aPP.getMediaList ());
} |
python | def has_extensions(self, *exts):
"""Check if file has one of the extensions."""
file_ext = splitext(self.filename)[1]
file_ext = file_ext.lower()
for e in exts:
if file_ext == e:
return True
return False |
java | private byte[] readChunk() throws Exception {
if (isEndOfInput()) {
return EMPTY_BYTE_ARRAY;
}
try {
// transfer to buffer
byte[] tmp = new byte[chunkSize];
int readBytes = in.read(tmp);
if (readBytes <= 0) {
return null;
}
byte[] buffer = new byte[readBytes];
System.arraycopy(tmp, 0, buffer, 0, readBytes);
offset += readBytes;
return buffer;
} catch (IOException e) {
// Close the stream, and propagate the exception.
IOUtils.closeQuietly(in);
throw e;
}
} |
python | def is_progressive(image):
"""
Check to see if an image is progressive.
"""
if not isinstance(image, Image.Image):
# Can only check PIL images for progressive encoding.
return False
return ('progressive' in image.info) or ('progression' in image.info) |
java | public static String resultSetToString(ResultSet resultSet) throws IllegalAccessException {
StringBuilder resultSetStringBuilder = new StringBuilder();
List<String[]> resultSetStringArrayList = resultSetToStringArrayList(resultSet);
List<Integer> maxColumnSizes = getMaxColumnSizes(resultSetStringArrayList);
String rowTemplate = createRowTemplate(maxColumnSizes);
String rowSeparator = createRowSeperator(maxColumnSizes);
resultSetStringBuilder.append(rowSeparator);
for (int i = 0; i < resultSetStringArrayList.size(); i++) {
resultSetStringBuilder
.append(String.format(rowTemplate, (Object[]) resultSetStringArrayList.get(i)))
.append(rowSeparator);
}
return resultSetStringBuilder.toString();
} |
java | public synchronized void closeAll() {
for (Window window : windows) {
try {
window.removeEventListener("close", this);
window.destroy();
} catch (Throwable e) {
}
}
windows.clear();
resetPosition();
} |
java | public static ResourceKey key(Class<?> clazz, String id) {
return new ResourceKey(clazz.getName(), id);
} |
python | def deletion_rate(Nref, Ndeletions, eps=numpy.spacing(1)):
"""Deletion rate
Parameters
----------
Nref : int >=0
Number of entries in the reference.
Ndeletions : int >=0
Number of deletions.
eps : float
eps.
Default value numpy.spacing(1)
Returns
-------
deletion_rate: float
Deletion rate
"""
return float(Ndeletions / (Nref + eps)) |
java | public static String getHeaderName(final String basename, final String filename) {
final String base = basename.replaceAll("\\\\", "/");
final String file = filename.replaceAll("\\\\", "/");
if (!file.startsWith(base)) {
throw new IllegalArgumentException("Error " + file + " does not start with " + base);
}
String header = file.substring(base.length() + 1);
header = header.replaceAll("/", "_");
header = header.replaceAll("\\.class", ".h");
return header;
} |
python | def get_state_machine_m(self, two_factor_check=True):
""" Get respective state machine model
Get a reference of the state machine model the state model belongs to. As long as the root state model
has no direct reference to its state machine model the state machine manager model is checked respective model.
:rtype: rafcon.gui.models.state_machine.StateMachineModel
:return: respective state machine model
"""
from rafcon.gui.singleton import state_machine_manager_model
state_machine = self.state.get_state_machine()
if state_machine:
if state_machine.state_machine_id in state_machine_manager_model.state_machines:
sm_m = state_machine_manager_model.state_machines[state_machine.state_machine_id]
if not two_factor_check or sm_m.get_state_model_by_path(self.state.get_path()) is self:
return sm_m
else:
logger.debug("State model requesting its state machine model parent seems to be obsolete. "
"This is a hint to duplicated models and dirty coding")
return None |
python | def keyPressEvent(self, event):
"""
Processes user input when they enter a key.
:param event | <QKeyEvent>
"""
# emit the return pressed signal for this widget
if event.key() in (Qt.Key_Return, Qt.Key_Enter) and \
event.modifiers() == Qt.ControlModifier:
self.acceptText()
event.accept()
return
elif event.key() == Qt.Key_Tab:
if self.tabsAsSpaces():
count = 4 - (self.textCursor().columnNumber() % 4)
self.insertPlainText(' ' * count)
event.accept()
return
elif event.key() == Qt.Key_V and event.modifiers() == Qt.ControlModifier:
self.paste()
event.accept()
return
super(XTextEdit, self).keyPressEvent(event)
if self.autoResizeToContents():
self.resizeToContents() |
java | public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
if (reachedEOF) {
return -1;
}
// TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream...
while (buffer.hasRemaining()) {
int n;
if (splitRun) {
// Continue run
n = leftOfRun;
splitRun = false;
}
else {
// Start new run
int b = stream.read();
if (b < 0) {
reachedEOF = true;
break;
}
n = (byte) b;
}
// Split run at or before max
if (n >= 0 && n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
else if (n < 0 && -n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
try {
if (n >= 0) {
// Copy next n + 1 bytes literally
readFully(stream, buffer, sample.length * (n + 1));
}
// Allow -128 for compatibility, see above
else if (disableNoOp || n != -128) {
// Replicate the next byte -n + 1 times
for (int s = 0; s < sample.length; s++) {
sample[s] = readByte(stream);
}
for (int i = -n + 1; i > 0; i--) {
buffer.put(sample);
}
}
// else NOOP (-128)
}
catch (IndexOutOfBoundsException e) {
throw new DecodeException("Error in PackBits decompression, data seems corrupt", e);
}
}
return buffer.position();
} |
java | private int compareToLFU( CacheEntry other ) {
int cmp = compareReadCount( other );
if ( cmp != 0 ) {
return cmp;
}
cmp = compareTime( other );
if ( cmp != 0 ) {
return cmp;
}
return compareOrder( other );
} |
java | @Override
public java.util.List<com.liferay.commerce.product.model.CPDefinitionOptionValueRel> getCPDefinitionOptionValueRelsByUuidAndCompanyId(
String uuid, long companyId, int start, int end,
com.liferay.portal.kernel.util.OrderByComparator<com.liferay.commerce.product.model.CPDefinitionOptionValueRel> orderByComparator) {
return _cpDefinitionOptionValueRelLocalService.getCPDefinitionOptionValueRelsByUuidAndCompanyId(uuid,
companyId, start, end, orderByComparator);
} |
python | def max_cation_insertion(self):
"""
Maximum number of cation A that can be inserted while maintaining charge-balance.
No consideration is given to whether there (geometrically speaking) are Li sites to actually accommodate the extra Li.
Returns:
integer amount of cation. Depends on cell size (this is an 'extrinsic' function!)
"""
# how much 'spare charge' is left in the redox metals for reduction?
lowest_oxid = defaultdict(lambda: 2, {'Cu': 1}) # only Cu can go down to 1+
oxid_pot = sum([(spec.oxi_state - min(
e for e in Element(spec.symbol).oxidation_states if e >= lowest_oxid[spec.symbol])) *
self.comp[spec] for spec in self.comp if
is_redox_active_intercalation(Element(spec.symbol))])
return oxid_pot / self.cation_charge |
java | public static RequestQueue newRequestQueue(HttpStack stack) {
File cacheDir = new File("./", DEFAULT_CACHE_DIR);
String userAgent = "volley/0";
if (stack == null) {
stack = new HurlStack();
}
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
return queue;
} |
python | def _build_named_object_id(parameter):
"""
Builds a NamedObjectId. This is a bit more complex than it really
should be. In Python (for convenience) we allow the user to simply address
entries by their alias via the NAMESPACE/NAME convention. Yamcs is not
aware of this convention so we decompose it into distinct namespace and
name fields.
"""
named_object_id = yamcs_pb2.NamedObjectId()
if parameter.startswith('/'):
named_object_id.name = parameter
else:
parts = parameter.split('/', 1)
if len(parts) < 2:
raise ValueError('Failed to process {}. Use fully-qualified '
'XTCE names or, alternatively, an alias in '
'in the format NAMESPACE/NAME'.format(parameter))
named_object_id.namespace = parts[0]
named_object_id.name = parts[1]
return named_object_id |
java | @Override
public DescribeCommandsResult describeCommands(DescribeCommandsRequest request) {
request = beforeClientExecution(request);
return executeDescribeCommands(request);
} |
java | public com.google.api.ads.admanager.axis.v201811.SslManualOverride getSslManualOverride() {
return sslManualOverride;
} |
java | @Override
protected int compare(Integer o1, Integer o2) {
if (o1 < o2) {
return -1;
} else if (o1 > o2) {
return 1;
} else {
return 0;
}
} |
python | def _add_rhoa(df, spacing):
"""a simple wrapper to compute K factors and add rhoa
"""
df['k'] = redaK.compute_K_analytical(df, spacing=spacing)
df['rho_a'] = df['r'] * df['k']
if 'Zt' in df.columns:
df['rho_a_complex'] = df['Zt'] * df['k']
return df |
java | public int consume(Map<String, String> initialVars) {
int result = 0;
for (int i = 0; i < repeatNumber; i++) {
result += super.consume(initialVars);
}
return result;
} |
java | public void build(String input, boolean treatWarningsAsError) throws IOException, ParseException {
build(new InputSource(new StringReader(input)), treatWarningsAsError);
} |
python | async def begin_twophase(self, xid=None):
"""Begin a two-phase or XA transaction and return a transaction
handle.
The returned object is an instance of
TwoPhaseTransaction, which in addition to the
methods provided by Transaction, also provides a
TwoPhaseTransaction.prepare() method.
xid - the two phase transaction id. If not supplied, a
random id will be generated.
"""
if self._transaction is not None:
raise exc.InvalidRequestError(
"Cannot start a two phase transaction when a transaction "
"is already in progress.")
if xid is None:
xid = self._dialect.create_xid()
self._transaction = TwoPhaseTransaction(self, xid)
await self.execute("XA START %s", xid)
return self._transaction |
java | public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final String xml,
final Class<T> clazz) {
return transformSamlObject(configBean, xml.getBytes(StandardCharsets.UTF_8), clazz);
} |
python | def batchcancel_order(self, order_ids: list):
"""
批量撤销订单
:param order_id:
:return:
"""
assert isinstance(order_ids, list)
params = {'order-ids': order_ids}
path = f'/v1/order/orders/batchcancel'
def _wrapper(_func):
@wraps(_func)
def handle():
_func(api_key_post(params, path))
return handle
return _wrapper |
java | @XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "equivalent")
public JAXBElement<RelationsType> createEquivalent(RelationsType value) {
return new JAXBElement<RelationsType>(_Equivalent_QNAME, RelationsType.class, null, value);
} |
java | protected void fireConsumerConnectionEvent(IConsumer consumer, PipeConnectionEvent.EventType type, Map<String, Object> paramMap) {
firePipeConnectionEvent(PipeConnectionEvent.build(this, type, consumer, paramMap));
} |
java | @Override
public int getLastOrderNumber(final NodeData parent) throws RepositoryException
{
if (!this.equals(versionDataManager) && isSystemDescendant(parent.getQPath()))
{
return versionDataManager.getLastOrderNumber(parent);
}
return super.getLastOrderNumber(parent);
} |
python | def makeImages(self):
"""Make spiral images in sectors and steps.
Plain, reversed,
sectorialized, negative sectorialized
outline, outline reversed, lonely
only nodes, only edges, both
"""
# make layout
self.makeLayout()
self.setAgraph()
# make function that accepts a mode, a sector
# and nodes and edges True and False
self.plotGraph()
self.plotGraph("reversed",filename="tgraphR.png")
agents=n.concatenate(self.np.sectorialized_agents__)
for i, sector in enumerate(self.np.sectorialized_agents__):
self.plotGraph("plain", sector,"sector{:02}.png".format(i))
self.plotGraph("reversed",sector,"sector{:02}R.png".format(i))
self.plotGraph("plain", n.setdiff1d(agents,sector),"sector{:02}N.png".format(i))
self.plotGraph("reversed",n.setdiff1d(agents,sector),"sector{:02}RN.png".format(i))
self.plotGraph("plain", [],"BLANK.png") |
python | def connect_post_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs):
"""
connect POST requests to proxy of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.connect_post_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs)
else:
(data) = self.connect_post_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs)
return data |
python | def apps_installation_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/apps#remove-app-installation"
api_path = "/api/v2/apps/installations/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) |
java | public static int getAxisFromStep(
Compiler compiler, int stepOpCodePos)
throws javax.xml.transform.TransformerException
{
int stepType = compiler.getOp(stepOpCodePos);
switch (stepType)
{
case OpCodes.FROM_FOLLOWING :
return Axis.FOLLOWING;
case OpCodes.FROM_FOLLOWING_SIBLINGS :
return Axis.FOLLOWINGSIBLING;
case OpCodes.FROM_PRECEDING :
return Axis.PRECEDING;
case OpCodes.FROM_PRECEDING_SIBLINGS :
return Axis.PRECEDINGSIBLING;
case OpCodes.FROM_PARENT :
return Axis.PARENT;
case OpCodes.FROM_NAMESPACE :
return Axis.NAMESPACE;
case OpCodes.FROM_ANCESTORS :
return Axis.ANCESTOR;
case OpCodes.FROM_ANCESTORS_OR_SELF :
return Axis.ANCESTORORSELF;
case OpCodes.FROM_ATTRIBUTES :
return Axis.ATTRIBUTE;
case OpCodes.FROM_ROOT :
return Axis.ROOT;
case OpCodes.FROM_CHILDREN :
return Axis.CHILD;
case OpCodes.FROM_DESCENDANTS_OR_SELF :
return Axis.DESCENDANTORSELF;
case OpCodes.FROM_DESCENDANTS :
return Axis.DESCENDANT;
case OpCodes.FROM_SELF :
return Axis.SELF;
case OpCodes.OP_EXTFUNCTION :
case OpCodes.OP_FUNCTION :
case OpCodes.OP_GROUP :
case OpCodes.OP_VARIABLE :
return Axis.FILTEREDLIST;
}
throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NULL_ERROR_HANDLER, new Object[]{Integer.toString(stepType)})); //"Programmer's assertion: unknown opcode: "
//+ stepType);
} |
python | def cross_fade(self, seg1, seg2, duration):
"""Add a linear crossfade to the composition between two
segments.
:param seg1: First segment (fading out)
:type seg1: :py:class:`radiotool.composer.Segment`
:param seg2: Second segment (fading in)
:type seg2: :py:class:`radiotool.composer.Segment`
:param duration: Duration of crossfade (in seconds)
"""
if seg1.comp_location + seg1.duration - seg2.comp_location < 2:
dur = int(duration * seg1.track.samplerate)
if dur % 2 == 1:
dur -= 1
if dur / 2 > seg1.duration:
dur = seg1.duration * 2
if dur / 2 > seg2.duration:
dur = seg2.duration * 2
# we're going to compute the crossfade and then create a RawTrack
# for the resulting frames
if seg2.start - (dur / 2) < 0:
diff = seg2.start
seg2.start = 0
seg2.duration -= diff
seg2.comp_location -= diff
dur = 2 * diff
else:
seg2.start -= (dur / 2)
seg2.duration += (dur / 2)
seg2.comp_location -= (dur / 2)
seg1.duration += (dur / 2)
out_frames = seg1.get_frames(channels=self.channels)[-dur:]
seg1.duration -= dur
in_frames = seg2.get_frames(channels=self.channels)[:dur]
seg2.start += dur
seg2.duration -= dur
seg2.comp_location += dur
# compute the crossfade
in_frames = in_frames[:min(map(len, [in_frames, out_frames]))]
out_frames = out_frames[:min(map(len, [in_frames, out_frames]))]
cf_frames = radiotool.utils.linear(out_frames, in_frames)
# cf_frames = equal_power(out_frames, in_frames)
raw_track = RawTrack(cf_frames, name="crossfade",
samplerate=seg1.track.samplerate)
rs_comp_location = (seg1.comp_location + seg1.duration) /\
float(seg1.track.samplerate)
rs_duration = raw_track.duration / float(raw_track.samplerate)
raw_seg = Segment(raw_track, rs_comp_location, 0.0, rs_duration)
# will this fix a bug?
raw_seg.duration = raw_track.duration
raw_seg.comp_location = seg1.comp_location + seg1.duration
self.add_track(raw_track)
self.add_segment(raw_seg)
return raw_seg
else:
print seg1.comp_location + seg1.duration, seg2.comp_location
raise Exception("Segments must be adjacent"
"to add a crossfade ({}, {})".format(
seg1.comp_location + seg1.duration,
seg2.comp_location)) |
python | def _generate(self, func):
"""Generate a population of :math:`\lambda` individuals.
Notes
-----
Individuals are of type *ind_init* from the current strategy.
Parameters
----------
ind_init:
A function object that is able to initialize an
individual from a list.
"""
arz = numpy.random.standard_normal((self.lambda_, self.dim))
arz = self.centroid + self.sigma * numpy.dot(arz, self.BD.T)
self.population = list(map(func, arz))
return |
java | @SuppressWarnings("unchecked")
static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) {
Monitor<T> m;
if (monitor instanceof CompositeMonitor<?>) {
m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor);
} else {
m = MonitorWrapper.create(tags, monitor);
}
return m;
} |
java | private Object getEvent(EventEnvelope eventEnvelope) {
Object event = eventEnvelope.getEvent();
if (event instanceof Data) {
event = eventService.nodeEngine.toObject(event);
}
return event;
} |
java | protected void parseImports() {
List<Element> imports = rootElement.elements("import");
for (Element theImport : imports) {
String importType = theImport.attribute("importType");
XMLImporter importer = this.getImporter(importType, theImport);
if (importer == null) {
addError("Could not import item of type " + importType, theImport);
} else {
importer.importFrom(theImport, this);
}
}
} |
java | private int addIndexedSplits(
List<InputSplit> splits, int i, List<InputSplit> newSplits,
Configuration cfg)
throws IOException
{
final Path file = ((FileSplit)splits.get(i)).getPath();
final BGZFBlockIndex idx = new BGZFBlockIndex(
file.getFileSystem(cfg).open(getIdxPath(file)));
int splitsEnd = splits.size();
for (int j = i; j < splitsEnd; ++j)
if (!file.equals(((FileSplit)splits.get(j)).getPath()))
splitsEnd = j;
for (int j = i; j < splitsEnd; ++j) {
final FileSplit fileSplit = (FileSplit)splits.get(j);
final long start = fileSplit.getStart();
final long end = start + fileSplit.getLength();
final Long blockStart = idx.prevBlock(start);
final Long blockEnd = j == splitsEnd-1 ? idx.prevBlock(end)
: idx.nextBlock(end);
if (blockStart == null)
throw new RuntimeException(
"Internal error or invalid index: no block start for " +start);
if (blockEnd == null)
throw new RuntimeException(
"Internal error or invalid index: no block end for " +end);
newSplits.add(new FileSplit(
file, blockStart, blockEnd - blockStart,
fileSplit.getLocations()));
}
return splitsEnd;
} |
python | def _set_bulk_size(self, bulk_size):
"""
Set the bulk size
:param bulk_size the bulker size
"""
self._bulk_size = bulk_size
self.bulker.bulk_size = bulk_size |
python | def setCompleteRedYellowGreenDefinition(self, tlsID, tls):
"""setCompleteRedYellowGreenDefinition(string, ) -> None
.
"""
length = 1 + 4 + 1 + 4 + \
len(tls._subID) + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 4 # tls parameter
itemNo = 1 + 1 + 1 + 1 + 1
for p in tls._phases:
length += 1 + 4 + 1 + 4 + 1 + 4 + 1 + 4 + len(p._phaseDef)
itemNo += 4
self._connection._beginMessage(
tc.CMD_SET_TL_VARIABLE, tc.TL_COMPLETE_PROGRAM_RYG, tlsID, length)
self._connection._string += struct.pack("!Bi",
tc.TYPE_COMPOUND, itemNo)
# programID
self._connection._packString(tls._subID)
# type
self._connection._string += struct.pack("!Bi", tc.TYPE_INTEGER, 0)
# subitems
self._connection._string += struct.pack("!Bi", tc.TYPE_COMPOUND, 0)
# index
self._connection._string += struct.pack("!Bi",
tc.TYPE_INTEGER, tls._currentPhaseIndex)
# phaseNo
self._connection._string += struct.pack("!Bi",
tc.TYPE_INTEGER, len(tls._phases))
for p in tls._phases:
self._connection._string += struct.pack("!BiBiBi", tc.TYPE_INTEGER,
p._duration, tc.TYPE_INTEGER, p._duration1, tc.TYPE_INTEGER, p._duration2)
self._connection._packString(p._phaseDef)
self._connection._sendExact() |
java | public void set(int idx, char chr)
{
if ( idx < 0 )
throw new IndexOutOfBoundsException("idx < 0");
if ( idx >= count )
throw new IndexOutOfBoundsException("idx >= buffer.length");
buff[idx] = chr;
} |
java | private void appendEntry(Map.Entry<String, EDBObjectEntry> entry, StringBuilder builder) {
if (builder.length() > 2) {
builder.append(",");
}
builder.append(" \"").append(entry.getKey()).append("\"");
builder.append(" : ").append(entry.getValue());
} |
python | def parse_pr_numbers(git_log_lines):
"""
Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number.
"""
prs = []
for line in git_log_lines:
pr_number = parse_pr_number(line)
if pr_number:
prs.append(pr_number)
return prs |
java | public void readChild(Element element, PrintWriter ps, int level,
String name) {
String nbTab = tabMaker(level);
if (element instanceof Resource) {
Resource resource = (Resource) element;
writeBegin(ps, nbTab, name, level, element.getTypeAsString());
for (Resource.Entry entry : resource) {
Property key = entry.getKey();
Element value = entry.getValue();
level++;
readChild(value, ps, level, key.toString());
level--;
}
writeEnd(ps, nbTab, element.getTypeAsString());
} else {
Property elem = (Property) element;
writeProperties(ps, nbTab, name, element.getTypeAsString(),
elem.toString());
}
} |
java | public void changeWorkspaceInURL(String name, boolean changeHistory) {
jcrURL.setWorkspace(name);
if (changeHistory) {
htmlHistory.newItem(jcrURL.toString(), false);
}
} |
python | def get_dialect(self):
"""Returns a new dialect that implements the current selection"""
parameters = {}
for parameter in self.csv_params[2:]:
pname, ptype, plabel, phelp = parameter
widget = self._widget_from_p(pname, ptype)
if ptype is types.StringType or ptype is types.UnicodeType:
parameters[pname] = str(widget.GetValue())
elif ptype is types.BooleanType:
parameters[pname] = widget.GetValue()
elif pname == 'quoting':
choice = self.choices['quoting'][widget.GetSelection()]
parameters[pname] = getattr(csv, choice)
else:
raise TypeError(_("{type} unknown.").format(type=ptype))
has_header = parameters.pop("self.has_header")
try:
csv.register_dialect('user', **parameters)
except TypeError, err:
msg = _("The dialect is invalid. \n "
"\nError message:\n{msg}").format(msg=err)
dlg = wx.MessageDialog(self.parent, msg, style=wx.ID_CANCEL)
dlg.ShowModal()
dlg.Destroy()
raise TypeError(err)
return csv.get_dialect('user'), has_header |
python | def get_xy(artist):
"""
Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections.
"""
xy = None
if hasattr(artist, 'get_offsets'):
xy = artist.get_offsets().T
elif hasattr(artist, 'get_xydata'):
xy = artist.get_xydata().T
return xy |
java | public Set<RGBColor> colours() {
return stream().map(Pixel::toColor).collect(Collectors.toSet());
} |
java | @Programmatic // for use by fixtures
public Gmap3ToDoItem newToDo(
final String description,
final String userName) {
final Gmap3ToDoItem toDoItem = repositoryService.instantiate(Gmap3ToDoItem.class);
toDoItem.setDescription(description);
toDoItem.setOwnedBy(userName);
toDoItem.setLocation(
new Location(51.5172+random(-0.05, +0.05), 0.1182 + random(-0.05, +0.05)));
repositoryService.persistAndFlush(toDoItem);
return toDoItem;
} |
python | def crypto_config_from_table_info(materials_provider, attribute_actions, table_info):
"""Build a crypto config from the provided values and table info.
:returns: crypto config and updated kwargs
:rtype: tuple(CryptoConfig, dict)
"""
ec_kwargs = table_info.encryption_context_values
if table_info.primary_index is not None:
ec_kwargs.update(
{"partition_key_name": table_info.primary_index.partition, "sort_key_name": table_info.primary_index.sort}
)
return CryptoConfig(
materials_provider=materials_provider,
encryption_context=EncryptionContext(**ec_kwargs),
attribute_actions=attribute_actions,
) |
java | public static List<Path> getSubPathList(Path startDirectoryPath,
int maxDepth) {
return getSubPathList(startDirectoryPath, maxDepth,
JMPredicate.getTrue());
} |
java | @Override
public void rename(String oldname, String newname) throws NamingException
{
rename(new CompositeName(oldname), new CompositeName(newname));
} |
python | def log_player_roll(self, player, roll):
"""
:param player: catan.game.Player
:param roll: integer or string, the sum of the dice
"""
self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) |
java | public Boolean setExecutionState(
ExecutionEnvironment.ExecutionState executionState, String topologyName) {
return awaitResult(delegate.setExecutionState(executionState, topologyName));
} |
java | @Override
public void grantLeadership(final UUID leaderSessionID) {
log.info("{} was granted leadership with leaderSessionID={}", getRestBaseUrl(), leaderSessionID);
leaderElectionService.confirmLeaderSessionID(leaderSessionID);
} |
python | def _insert(self, tree):
""" Run an INSERT statement """
tablename = tree.table
count = 0
kwargs = {}
batch = self.connection.batch_write(tablename, **kwargs)
with batch:
for item in iter_insert_items(tree):
batch.put(item)
count += 1
return count |
python | def deleteWebhook(self, hook_id):
"""Remove a webhook."""
path = '/'.join(['notification', 'webhook', hook_id])
return self.rachio.delete(path) |
python | def cart2frac_all(coordinates, lattice_array):
"""Convert all cartesian coordinates to fractional."""
frac_coordinates = deepcopy(coordinates)
for coord in range(frac_coordinates.shape[0]):
frac_coordinates[coord] = fractional_from_cartesian(
frac_coordinates[coord], lattice_array)
return frac_coordinates |
java | public Vector3d origin(Vector3d dest) {
if ((properties & PROPERTY_AFFINE) != 0)
return originAffine(dest);
return originGeneric(dest);
} |
java | public boolean isOpen(String pn) {
return opens.containsKey(pn) && opens.get(pn).isEmpty();
} |
java | protected String nagiosCheckValue(String value, String composeRange) {
List<String> simpleRange = Arrays.asList(composeRange.split(","));
double doubleValue = Double.parseDouble(value);
if (composeRange.isEmpty()) {
return "0";
}
if (simpleRange.size() == 1) {
if (composeRange.endsWith(",")) {
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
} else {
return "0";
}
} else if (valueCheck(doubleValue, simpleRange.get(0))) {
return "2";
} else {
return "0";
}
}
if (valueCheck(doubleValue, simpleRange.get(1))) {
return "2";
}
if (valueCheck(doubleValue, simpleRange.get(0))) {
return "1";
}
return "0";
} |
python | def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes) |
python | def browse_home_listpage_url(self,
state=None,
county=None,
zipcode=None,
street=None,
**kwargs):
"""
Construct an url of home list page by state, county, zipcode, street.
Example:
- https://www.zillow.com/browse/homes/ca/
- https://www.zillow.com/browse/homes/ca/los-angeles-county/
- https://www.zillow.com/browse/homes/ca/los-angeles-county/91001/
- https://www.zillow.com/browse/homes/ca/los-angeles-county/91001/tola-ave_5038895/
"""
url = self.domain_browse_homes
for item in [state, county, zipcode, street]:
if item:
url = url + "/%s" % item
url = url + "/"
return url |
java | public DatabaseAccountListReadOnlyKeysResultInner getReadOnlyKeys(String resourceGroupName, String accountName) {
return getReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
} |
python | def compute_cusum_ts(self, ts):
""" Compute the Cumulative Sum at each point 't' of the time series. """
mean = np.mean(ts)
cusums = np.zeros(len(ts))
cusum[0] = (ts[0] - mean)
for i in np.arange(1, len(ts)):
cusums[i] = cusums[i - 1] + (ts[i] - mean)
assert(np.isclose(cumsum[-1], 0.0))
return cusums |
java | public Collection<Expression> expressions(ExpressionFilter filter) {
return get(Expression.class, (filter != null) ? filter : new ExpressionFilter());
} |
java | public static void writeEscapedAttrValue(Writer w, String value)
throws IOException
{
int i = 0;
int len = value.length();
do {
int start = i;
char c = '\u0000';
for (; i < len; ++i) {
c = value.charAt(i);
if (c == '<' || c == '&' || c == '"') {
break;
}
}
int outLen = i - start;
if (outLen > 0) {
w.write(value, start, outLen);
}
if (i < len) {
if (c == '<') {
w.write("<");
} else if (c == '&') {
w.write("&");
} else if (c == '"') {
w.write(""");
}
}
} while (++i < len);
} |
python | def _example_from_array_spec(self, prop_spec):
"""Get an example from a property specification of an array.
Args:
prop_spec: property specification you want an example of.
Returns:
An example array.
"""
# if items is a list, then each item has its own spec
if isinstance(prop_spec['items'], list):
return [self.get_example_from_prop_spec(item_prop_spec) for item_prop_spec in prop_spec['items']]
# Standard types in array
elif 'type' in prop_spec['items'].keys():
if 'format' in prop_spec['items'].keys() and prop_spec['items']['format'] == 'date-time':
return self._get_example_from_basic_type('datetime')
else:
return self._get_example_from_basic_type(prop_spec['items']['type'])
# Array with definition
elif ('$ref' in prop_spec['items'].keys() or
('schema' in prop_spec and'$ref' in prop_spec['schema']['items'].keys())):
# Get value from definition
definition_name = self.get_definition_name_from_ref(prop_spec['items']['$ref']) or \
self.get_definition_name_from_ref(prop_spec['schema']['items']['$ref'])
if self.build_one_definition_example(definition_name):
example_dict = self.definitions_example[definition_name]
if not isinstance(example_dict, dict):
return [example_dict]
if len(example_dict) == 1:
try: # Python 2.7
res = example_dict[example_dict.keys()[0]]
except TypeError: # Python 3
res = example_dict[list(example_dict)[0]]
return res
else:
return_value = {}
for example_name, example_value in example_dict.items():
return_value[example_name] = example_value
return [return_value]
elif 'properties' in prop_spec['items']:
prop_example = {}
for prop_name, prop_spec in prop_spec['items']['properties'].items():
example = self.get_example_from_prop_spec(prop_spec)
if example is not None:
prop_example[prop_name] = example
return [prop_example] |
java | public static InputArchive fromInputStream(InputStream stream) throws IOException {
if (stream instanceof ObjectInput) {
return new InputArchive((ObjectInput) stream);
} else {
return new InputArchive(new ObjectInputStream(stream));
}
} |
python | def plot(self, figsize=(12, 6), xscale='auto-gps', **kwargs):
"""Plot the data for this `Spectrogram`
Parameters
----------
**kwargs
all keyword arguments are passed along to underlying
functions, see below for references
Returns
-------
plot : `~gwpy.plot.Plot`
the `Plot` containing the data
See Also
--------
matplotlib.pyplot.figure
for documentation of keyword arguments used to create the
figure
matplotlib.figure.Figure.add_subplot
for documentation of keyword arguments used to create the
axes
gwpy.plot.Axes.imshow or gwpy.plot.Axes.pcolormesh
for documentation of keyword arguments used in rendering the
`Spectrogram` data
"""
if 'imshow' in kwargs:
warnings.warn('the imshow keyword for Spectrogram.plot was '
'removed, please pass method=\'imshow\' instead',
DeprecationWarning)
kwargs.setdefault('method', 'imshow' if kwargs.pop('imshow') else
'pcolormesh')
kwargs.update(figsize=figsize, xscale=xscale)
return super(Spectrogram, self).plot(**kwargs) |
java | public List<Node> getConnectedNodes() {
List<Node> nodes = new ArrayList<>();
for (Link l : links) {
if (l.getElement() instanceof Node) {
nodes.add((Node) l.getElement());
}
}
return nodes;
} |
python | def fromString( cls, strdata ):
"""
Restores a color set instance from the inputed string data.
:param strdata | <str>
"""
if ( not strdata ):
return None
from xml.etree import ElementTree
xelem = ElementTree.fromstring(str(strdata))
output = cls(xelem.get('name'), xelem.get('colorGroups').split(','))
for xcolor in xelem:
colorName = xcolor.get('name')
for xcolorval in xcolor:
color = QColor( int(xcolorval.get('red')),
int(xcolorval.get('green')),
int(xcolorval.get('blue')),
int(xcolorval.get('alpha')) )
output.setColor(colorName, color, xcolorval.get('group'))
return output |
java | @SuppressWarnings("static-method")
public Integer findIntValue(JvmAnnotationReference reference) {
assert reference != null;
for (final JvmAnnotationValue value : reference.getValues()) {
if (value instanceof JvmIntAnnotationValue) {
for (final Integer intValue : ((JvmIntAnnotationValue) value).getValues()) {
if (intValue != null) {
return intValue;
}
}
}
}
return null;
} |
java | public static void invertLower( double L[] , int m ) {
for( int i = 0; i < m; i++ ) {
double L_ii = L[ i*m + i ];
for( int j = 0; j < i; j++ ) {
double val = 0;
for( int k = j; k < i; k++ ) {
val += L[ i*m + k] * L[ k*m + j ];
}
L[ i*m + j ] = -val / L_ii;
}
L[ i*m + i ] = 1.0 / L_ii;
}
} |
java | public void rollbackImage(NamespaceInfo nsInfo) throws IOException {
Preconditions.checkState(nsInfo.getLayoutVersion() != 0,
"can't rollback with uninitialized layout version: %s",
nsInfo.toColonSeparatedString());
LOG.info("Rolling back image " + this.getJournalId()
+ " with namespace info: (" + nsInfo.toColonSeparatedString() + ")");
imageStorage.rollback(nsInfo);
} |
java | public static List<StartEndPair> scan(String input, String splitStart,
String splitEnd, boolean useEscaping) {
List<StartEndPair> result = new ArrayList<StartEndPair>();
int fromIndex = 0;
while (true) {
int exprStart = input.indexOf(splitStart, fromIndex);
if (exprStart == -1) {
break;
}
if (useEscaping && Util.isEscaped(input, exprStart)) {
fromIndex = exprStart + splitStart.length();
continue;
}
exprStart += splitStart.length();
int exprEnd = input.indexOf(splitEnd, exprStart);
if (exprEnd == -1) {
break;
}
while (useEscaping && Util.isEscaped(input, exprEnd)) {
exprEnd = input.indexOf(splitEnd, exprEnd + splitEnd.length());
}
fromIndex = exprEnd + splitEnd.length();
StartEndPair startEndPair = new StartEndPair(exprStart, exprEnd);
result.add(startEndPair);
}
return result;
} |
python | def _partialParseTimeStd(self, s, sourceTime):
"""
test if giving C{s} matched CRE_TIMEHMS, used by L{parse()}
@type s: string
@param s: date/time text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: tuple
@return: tuple of remained date/time text, datetime object and
an boolean value to describ if matched or not
"""
parseStr = None
chunk1 = chunk2 = ''
# HH:MM(:SS) time strings
m = self.ptc.CRE_TIMEHMS.search(s)
if m is not None:
if m.group('seconds') is not None:
parseStr = '%s:%s:%s' % (m.group('hours'),
m.group('minutes'),
m.group('seconds'))
chunk1 = s[:m.start('hours')]
chunk2 = s[m.end('seconds'):]
else:
parseStr = '%s:%s' % (m.group('hours'),
m.group('minutes'))
chunk1 = s[:m.start('hours')]
chunk2 = s[m.end('minutes'):]
s = '%s %s' % (chunk1, chunk2)
if parseStr:
debug and log.debug(
'found (hms) [%s][%s][%s]', parseStr, chunk1, chunk2)
sourceTime = self._evalTimeStd(parseStr, sourceTime)
return s, sourceTime, bool(parseStr) |
python | def _delete(self, url):
"""Wrapper around request.delete() to use the API prefix. Returns a JSON response."""
req = self._session.delete(self._api_prefix + url)
return self._action(req) |
java | public static String getString(JSONValue value) {
if (value == null)
return null;
if (!(value instanceof JSONString))
throw new JSONException(NOT_A_STRING);
return ((JSONString)value).toString();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.