language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def get_json_results(self, response):
'''
Parses the request result and returns the JSON object. Handles all errors.
'''
try:
# return the proper JSON object, or error code if request didn't go through.
self.most_recent_json = response.json()
json_results = response.json()
if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota.
raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) )
elif response.status_code in [429]: #429 means try again in x seconds.
message = json_results['message']
try:
# extract time out seconds from response
timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1
print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout))
time.sleep(timeout)
except (AttributeError, ValueError) as e:
if not self.silent_fail:
raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) )
else:
print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"]))
time.sleep(5)
except ValueError as vE:
if not self.silent_fail:
raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text))
else:
print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text))
time.sleep(5)
return json_results |
python | def call(self, **kwargs):
"""Call all the functions that have previously been added to the
dependency graph in topological and lexicographical order, and
then return variables in a ``dict``.
You may provide variable values with keyword arguments. These
values will be written and can satisfy dependencies.
NOTE: This object will be **destroyed** after ``call()`` returns
and should not be used any further.
"""
if not hasattr(self, 'funcs'):
raise StartupError('startup cannot be called again')
for name, var in self.variables.items():
var.name = name
self.variable_values.update(kwargs)
for name in self.variable_values:
self.variables[name].name = name
queue = Closure.sort(self.satisfied)
queue.extend(_write_values(self.variable_values, self.variables))
while queue:
closure = queue.pop(0)
writeto = closure.call()
self.funcs.remove(closure.func)
queue.extend(_notify_reader_writes(writeto))
if self.funcs:
raise StartupError('cannot satisfy dependency for %r' % self.funcs)
values = {
name: var.read_latest() for name, var in self.variables.items()
}
# Call _release() on normal exit only; otherwise keep the dead body for
# forensic analysis.
self._release()
return values |
java | private Set<String> evaluateScope(String scope, CmsXmlContentDefinition definition) {
Set<String> evaluatedScopes = new HashSet<String>();
if (scope.contains("*")) {
// evaluate wildcards to get all allowed permutations of the scope
// a path like Paragraph*/Image should result in Paragraph[0]/Image, Paragraph[1]/Image and Paragraph[2]/Image
// in case max occurrence for Paragraph is 3
String[] pathElements = scope.split("/");
String parentPath = "";
for (int i = 0; i < pathElements.length; i++) {
String elementName = pathElements[i];
boolean hasWildCard = elementName.endsWith("*");
if (hasWildCard) {
elementName = elementName.substring(0, elementName.length() - 1);
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
I_CmsXmlSchemaType type = definition.getSchemaType(parentPath);
Set<String> tempScopes = new HashSet<String>();
if (type.getMaxOccurs() == Integer.MAX_VALUE) {
throw new IllegalStateException(
"Can not use fields with unbounded maxOccurs in scopes for editor change handler.");
}
for (int j = 0; j < type.getMaxOccurs(); j++) {
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName + "[" + (j + 1) + "]");
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName + "[" + (j + 1) + "]"));
}
}
}
evaluatedScopes = tempScopes;
} else {
parentPath = CmsStringUtil.joinPaths(parentPath, elementName);
Set<String> tempScopes = new HashSet<String>();
if (evaluatedScopes.isEmpty()) {
tempScopes.add(elementName);
} else {
for (String evScope : evaluatedScopes) {
tempScopes.add(CmsStringUtil.joinPaths(evScope, elementName));
}
}
evaluatedScopes = tempScopes;
}
}
} else {
evaluatedScopes.add(scope);
}
return evaluatedScopes;
} |
java | public PersistedFace getFace(String personGroupId, UUID personId, UUID persistedFaceId) {
return getFaceWithServiceResponseAsync(personGroupId, personId, persistedFaceId).toBlocking().single().body();
} |
python | def is_installed(self, bug: Bug) -> bool:
"""
Determines whether or not the Docker image for a given bug has been
installed onto this server.
See: `BuildManager.is_installed`
"""
return self.__installation.build.is_installed(bug.image) |
java | public void reset() {
checkPermission();
synchronized (this) {
props = new Hashtable<>();
// Since we are doing a reset we no longer want to initialize
// the global handlers, if they haven't been initialized yet.
initializedGlobalHandlers = true;
}
for (LoggerContext cx : contexts()) {
Enumeration<String> enum_ = cx.getLoggerNames();
while (enum_.hasMoreElements()) {
String name = enum_.nextElement();
Logger logger = cx.findLogger(name);
if (logger != null) {
resetLogger(logger);
}
}
}
} |
python | def WriteFlowResponses(self, responses):
"""Writes FlowMessages and updates corresponding requests."""
status_available = set()
requests_updated = set()
task_ids_by_request = {}
for response in responses:
flow_key = (response.client_id, response.flow_id)
if flow_key not in self.flows:
logging.error("Received response for unknown flow %s, %s.",
response.client_id, response.flow_id)
continue
request_dict = self.flow_requests.get(flow_key, {})
if response.request_id not in request_dict:
logging.error("Received response for unknown request %s, %s, %d.",
response.client_id, response.flow_id, response.request_id)
continue
response_dict = self.flow_responses.setdefault(flow_key, {})
clone = response.Copy()
clone.timestamp = rdfvalue.RDFDatetime.Now()
response_dict.setdefault(response.request_id,
{})[response.response_id] = clone
if isinstance(response, rdf_flow_objects.FlowStatus):
status_available.add(response)
request_key = (response.client_id, response.flow_id, response.request_id)
requests_updated.add(request_key)
try:
task_ids_by_request[request_key] = response.task_id
except AttributeError:
pass
# Every time we get a status we store how many responses are expected.
for status in status_available:
request_dict = self.flow_requests[(status.client_id, status.flow_id)]
request = request_dict[status.request_id]
request.nr_responses_expected = status.response_id
# And we check for all updated requests if we need to process them.
needs_processing = []
for client_id, flow_id, request_id in requests_updated:
flow_key = (client_id, flow_id)
request_dict = self.flow_requests[flow_key]
request = request_dict[request_id]
if request.nr_responses_expected and not request.needs_processing:
response_dict = self.flow_responses.setdefault(flow_key, {})
responses = response_dict.get(request_id, {})
if len(responses) == request.nr_responses_expected:
request.needs_processing = True
self._DeleteClientActionRequest(client_id, flow_id, request_id)
flow = self.flows[flow_key]
if flow.next_request_to_process == request_id:
needs_processing.append(
rdf_flows.FlowProcessingRequest(
client_id=client_id, flow_id=flow_id))
if needs_processing:
self.WriteFlowProcessingRequests(needs_processing) |
java | public synchronized boolean updateNode(int streamID, NODE_STATUS status, WRITE_COUNT_ACTION writeCountAction, H2WriteQEntry entry) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
if (entry == null) {
Tr.debug(tc, "updateNode entry: null" + " streamID: " + streamID + " status: " + status + " writeCountAction: " + writeCountAction);
} else {
Tr.debug(tc, "updateNode entry: " + entry.hashCode() + " streamID: " + streamID + " status: " + status + " writeCountAction: " + writeCountAction);
}
}
Node nodeToUpdate = root.findNode(streamID);
if (nodeToUpdate == null) {
return false;
}
if (entry != null) {
nodeToUpdate.setEntry(entry);
}
// Change status unless told not to
if (status != NODE_STATUS.ACTION_NO_CHANGE) {
if (status == NODE_STATUS.ACTION_RESET_IF_LATCHED) {
if (nodeToUpdate.getStatus() == NODE_STATUS.WRITE_LATCHED) {
nodeToUpdate.setStatus(NODE_STATUS.NOT_REQUESTING);
}
} else {
nodeToUpdate.setStatus(status);
}
}
// Do the count action, unless it is NO_ACTION
if (writeCountAction == WRITE_COUNT_ACTION.INCREMENT) {
nodeToUpdate.incrementWriteCount();
Node parentNode = nodeToUpdate.getParent();
if (parentNode != null) {
parentNode.incrementDependentWriteCount();
// need to re-arrange all nodes at this level because of count change
parentNode.sortDependents();
// special debug - too verbose for big trees
//if ((nodeToUpdate.writeCount % 100) == 0) {
// if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
// Tr.debug(tc, "updateNode after sorting: tree is now:" + getTreeDump());
// }
//}
} else if (writeCountAction == WRITE_COUNT_ACTION.CLEAR) {
nodeToUpdate.setWriteCount(0);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "updateNode exit: node updated to: " + nodeToUpdate.toStringDetails());
}
return true;
} |
python | def createAddress(self, prefix, type, network_id, callback=None, errback=None, **kwargs):
"""
Create a new Address
For the list of keywords available, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addresses.PASSTHRU_FIELDS`
:param str prefix: CIDR prefix of the address to be created
:param str type: Type of address assignement (planned, assignment or host)
:param int network_id: network_id associated with the address
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, id=network_id).load()
address = ns1.ipam.Address(self.config, prefix=prefix, type=type, network=network)
return address.create(callback=callback, errback=errback, **kwargs) |
java | private void processDatabaseMappingCollection(final Object databaseMappingCollection) {
if (databaseMappingCollection == null || !isCastable("java.util.Collection", databaseMappingCollection.getClass())) {
return;
}
final Collection<?> c = (Collection<?>) databaseMappingCollection;
for (Object descriptor : c) {
processDatabaseMappingObject(descriptor);
}
} |
java | public void translate(float x, float y, float z) {
NativeTransform.translate(getNative(), x, y, z);
} |
python | def conditional_expected_number_of_purchases_up_to_time(self, m_periods_in_future, frequency, recency, n_periods):
r"""
Conditional expected purchases in future time period.
The expected number of future transactions across the next m_periods_in_future
transaction opportunities by a customer with purchase history
(x, tx, n).
.. math:: E(X(n_{periods}, n_{periods}+m_{periods_in_future})| \alpha, \beta, \gamma, \delta, frequency, recency, n_{periods})
See (13) in Fader & Hardie 2010.
Parameters
----------
t: array_like
time n_periods (n+t)
Returns
-------
array_like
predicted transactions
"""
x = frequency
tx = recency
n = n_periods
params = self._unload_params("alpha", "beta", "gamma", "delta")
alpha, beta, gamma, delta = params
p1 = 1 / exp(self._loglikelihood(params, x, tx, n))
p2 = exp(betaln(alpha + x + 1, beta + n - x) - betaln(alpha, beta))
p3 = delta / (gamma - 1) * exp(gammaln(gamma + delta) - gammaln(1 + delta))
p4 = exp(gammaln(1 + delta + n) - gammaln(gamma + delta + n))
p5 = exp(gammaln(1 + delta + n + m_periods_in_future) - gammaln(gamma + delta + n + m_periods_in_future))
return p1 * p2 * p3 * (p4 - p5) |
java | public static String removeControlCharacters(String s, boolean removeCR)
{
String ret = s;
if(ret != null)
{
ret = ret.replaceAll("_x000D_","");
if(removeCR)
ret = ret.replaceAll("\r","");
}
return ret;
} |
java | public static ParameterizedType newParameterizedType(
final Class<?> raw, Iterable<? extends Type> typeArgs) {
TypeResolver resolver = new TypeResolver();
final List<TypeVariable<?>> vars = new ArrayList<TypeVariable<?>>();
for (Type arg : typeArgs) {
TypeVariable<?> var = TypeVariableGenerator.freshTypeVariable("T" + vars.size());
vars.add(var);
resolver = resolver.where(var, arg);
}
checkArgument(raw.getTypeParameters().length == vars.size(),
"%s expected %s type parameters, while %s are provied",
raw, raw.getTypeParameters().length, typeArgs);
return (ParameterizedType) resolver.resolveType(new ParameterizedType() {
@Override public Class<?> getRawType() { return raw; }
@Override public Type getOwnerType() { return null; }
@Override public Type[] getActualTypeArguments() { return vars.toArray(new Type[0]); }
});
} |
python | def ddtohms(xsky,ysky,verbose=False,precision=6):
""" Convert sky position(s) from decimal degrees to HMS format. """
xskyh = xsky /15.
xskym = (xskyh - np.floor(xskyh)) * 60.
xskys = (xskym - np.floor(xskym)) * 60.
yskym = (np.abs(ysky) - np.floor(np.abs(ysky))) * 60.
yskys = (yskym - np.floor(yskym)) * 60.
fmt = "%."+repr(precision)+"f"
if isinstance(xskyh,np.ndarray):
rah,dech = [],[]
for i in range(len(xskyh)):
rastr = repr(int(xskyh[i]))+':'+repr(int(xskym[i]))+':'+fmt%(xskys[i])
decstr = repr(int(ysky[i]))+':'+repr(int(yskym[i]))+':'+fmt%(yskys[i])
rah.append(rastr)
dech.append(decstr)
if verbose:
print('RA = ',rastr,', Dec = ',decstr)
else:
rastr = repr(int(xskyh))+':'+repr(int(xskym))+':'+fmt%(xskys)
decstr = repr(int(ysky))+':'+repr(int(yskym))+':'+fmt%(yskys)
rah = rastr
dech = decstr
if verbose:
print('RA = ',rastr,', Dec = ',decstr)
return rah,dech |
java | public static CellConstraints xywh(int col, int row, int colSpan, int rowSpan,
String encodedAlignments) {
return new CellConstraints().xywh(col, row, colSpan, rowSpan, encodedAlignments);
} |
python | def post_build(self, p, pay):
"""Called implicitly before a packet is sent.
"""
p += pay
if self.auxdlen != 0:
print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).")
print(" Subsequent Group Records are lost!")
return p |
python | def get_active_geometry(self):
"""
Get the geometry of the currently active window
Usage: C{window.get_active_geometry()}
@return: a 4-tuple containing the x-origin, y-origin, width and height of the window (in pixels)
@rtype: C{tuple(int, int, int, int)}
"""
active = self.mediator.interface.get_window_title()
result, output = self._run_wmctrl(["-l", "-G"])
matchingLine = None
for line in output.split('\n'):
if active in line[34:].split(' ', 1)[-1]:
matchingLine = line
if matchingLine is not None:
output = matchingLine.split()[2:6]
# return [int(x) for x in output]
return list(map(int, output))
else:
return None |
python | def restart(name):
'''
Restart the named service
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
'''
cmd = '/usr/sbin/svcadm restart {0}'.format(name)
if not __salt__['cmd.retcode'](cmd, python_shell=False):
# calling restart doesn't clear maintenance
# or tell us that the service is in the 'online' state
return start(name)
return False |
python | def subset_sum(x, R):
"""Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})`
"""
k = len(x) // 2 # divide input
Y = [v for v in part_sum(x[:k])]
Z = [R - v for v in part_sum(x[k:])]
Y.sort() # test of intersection between Y and Z
Z.sort()
i = 0
j = 0
while i < len(Y) and j < len(Z):
if Y[i] == Z[j]:
return True
elif Y[i] < Z[j]: # increment index of smallest element
i += 1
else:
j += 1
return False |
java | public void addLine(int startLine, String sourceFile, int repeatCount,
int outputLine, int outputIncrement)
{
_lines.add(new Line(startLine, sourceFile, repeatCount,
outputLine, outputIncrement));
} |
java | @Override
public Client header(String name, Object... values) {
if (values == null) {
throw new IllegalArgumentException();
}
if (HttpHeaders.CONTENT_TYPE.equals(name)) {
if (values.length > 1) {
throw new IllegalArgumentException("Content-Type can have a single value only");
}
type(convertParamValue(values[0], null));
} else {
for (Object o : values) {
possiblyAddHeader(name, convertParamValue(o, null));
}
}
return this;
} |
java | @Override
public IEntityGroup newGroup(Class type, Name serviceName) throws GroupsException {
return getComponentService(serviceName).newGroup(type);
} |
java | @Override
public void handle(StopTransactionRequestedEvent event, CorrelationToken correlationToken) {
LOG.info("OCPP 1.2 StopTransactionRequestedEvent");
if (event.getTransactionId() instanceof NumberedTransactionId) {
NumberedTransactionId transactionId = (NumberedTransactionId) event.getTransactionId();
chargingStationOcpp12Client.stopTransaction(event.getChargingStationId(), transactionId.getNumber());
} else {
LOG.warn("StopTransactionRequestedEvent does not contain a NumberedTransactionId. Event: {}", event);
}
} |
java | @Override
public String getProperty(String name) {
loadProperties();
return properties == null ? null : properties.getProperty(name);
} |
java | public PendingIntent getActionIntent(NotificationEntry entry, NotificationEntry.Action act) {
Intent intent = new Intent(ACTION_ACTION);
intent.putExtra(KEY_ENTRY_ID, entry.ID);
intent.putExtra(KEY_ACTION_ID, entry.mActions.indexOf(act));
return PendingIntent.getBroadcast(mContext, genIdForPendingIntent(), intent, 0);
} |
java | public void waitForReady() {
if (!isLoaded) {
synchronized (LOAD_LOCK) {
if (!isLoaded) {
try {
long start = Runtime.getActorTime();
LOAD_LOCK.wait();
Log.d(TAG, "Waited for startup in " + (Runtime.getActorTime() - start) + " ms");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} |
java | private List<AdvancedModelWrapper> performEOModelUpdate(EngineeringObjectModelWrapper model, EKBCommit commit) {
ModelDiff diff = createModelDiff(model.getUnderlyingModel(), model.getCompleteModelOID(),
edbService, edbConverter);
boolean referencesChanged = diff.isForeignKeyChanged();
boolean valuesChanged = diff.isValueChanged();
// TODO: OPENENGSB-3358, Make it possible to change references and values at the same time. Should be
// no too big deal since we already know at this point which values of the model have been changed and
// what the old and the new value for the changed properties are
if (referencesChanged && valuesChanged) {
throw new EKBException("Engineering Objects may be updated only at "
+ "references or at values not both in the same commit");
}
if (referencesChanged) {
reloadReferencesAndUpdateEO(diff, model);
} else {
return updateReferencedModelsByEO(model);
}
return new ArrayList<AdvancedModelWrapper>();
} |
python | def get_members_by_source(base_url=BASE_URL_API):
"""
Function returns which members have joined each activity.
:param base_url: It is URL: `https://www.openhumans.org/api/public-data`.
"""
url = '{}members-by-source/'.format(base_url)
response = get_page(url)
return response |
java | private List<String> collectProcessResults(Process process, ProcessBuilder builder,
SubProcessIOFiles outPutFiles) throws Exception {
List<String> results = new ArrayList<>();
try {
LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command())));
// If process exit value is not 0 then subprocess failed, record logs
if (process.exitValue() != 0) {
outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
throw new Exception(log);
}
// If no return file then either something went wrong or the binary is setup incorrectly for
// the ret file either way throw error
if (!Files.exists(outPutFiles.resultFile)) {
String log = createLogEntryForProcessFailure(process, builder.command(), outPutFiles);
outPutFiles.copyOutPutFilesToBucket(configuration, FileUtils.toStringParams(builder));
throw new Exception(log);
}
// Everything looks healthy return values
try (Stream<String> lines = Files.lines(outPutFiles.resultFile)) {
for (String line : (Iterable<String>) lines::iterator) {
results.add(line);
}
}
return results;
} catch (Exception ex) {
String log = String.format("Unexpected error runnng process. %s error message was %s",
createLogEntryFromInputs(builder.command()), ex.getMessage());
throw new Exception(log);
}
} |
java | @Override
public EEnum getIfcConstructionEquipmentResourceTypeEnum() {
if (ifcConstructionEquipmentResourceTypeEnumEEnum == null) {
ifcConstructionEquipmentResourceTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE
.getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(943);
}
return ifcConstructionEquipmentResourceTypeEnumEEnum;
} |
python | def assoc(m, *args, **kw):
'''
assoc(m, k1, v1, k2, v2...) yields a map equivalent to m without the arguments k1, k2, etc.
associated with the values v1, v2, etc. If m is a mutable python dictionary, this is
equivalent to using m[k] = v for all the given key-value pairs then returning m itself. If m
is a persistent map, this is equivalent to calling m = m.set(k, v) for all the key-value pairs
then returning m.
Keys given in the arguments list are always associated in order, then keys in the keyword
arguments are associated, meaning that the keyword arguments have precedence.
Note that in addition to key-value pairs in the ordinary arguments list, assoc() also uses the
key-value pairs given as named/keyword arguments.
If m is not a map but is instead a list or persistent vector, this operates as if the
list/vector is a map whose keys are integers. If an item is added beyond the extent of the list
then it is extended by adding None to the list. If negative indices are given, they are always
interpreted relative to the end of the initial input list m and not in terms of the list as it
has grown at the point that the key-value pair is processed.
'''
if len(args) % 2 != 0: raise ValueError('assoc arguments must be given as key-value pairs')
args = (u for it in [zip(args[::2],args[1::2]), six.iteritems(kw)] for u in it)
if is_pmap(m):
for (k,v) in args: m = m.set(k, v)
return m
elif is_map(m):
for (k,v) in args: m[k] = v
return m
elif isinstance(m, tuple_type):
args = list(args)
return m if len(args) == 0 else tuple(assoc(list(m), *args, **kw))
elif isinstance(m, list_type):
n0 = len(m)
n = n0
for (k,v) in args:
if not is_int(k): TypeError('Keys for list args must be integers')
if k < -n: KeyError(k)
if k < 0: k = n0 + k
if k >= n: (n,m) = (k+1, m + [None]*(k - n + 1))
m[k] = v
return m
elif is_nparray(m):
args = list(args)
if len(args) == 0: return m
return np.asarray(assoc(m.tolist(), *[x for u in args for x in u]))
else: raise ValueError('Cannot assoc given type: %s' % type(m)) |
python | def _get_search_result(self, query_url, **query_params):
""" Get search results helper. """
param_q = query_params.get('q')
param_query = query_params.get('query')
# Either q or query parameter is required
if bool(param_q) == bool(param_query):
raise CloudantArgumentError(104, query_params)
# Validate query arguments and values
for key, val in iteritems_(query_params):
if key not in list(SEARCH_INDEX_ARGS.keys()):
raise CloudantArgumentError(105, key)
if not isinstance(val, SEARCH_INDEX_ARGS[key]):
raise CloudantArgumentError(106, key, SEARCH_INDEX_ARGS[key])
# Execute query search
headers = {'Content-Type': 'application/json'}
resp = self.r_session.post(
query_url,
headers=headers,
data=json.dumps(query_params, cls=self.client.encoder)
)
resp.raise_for_status()
return response_to_json_dict(resp) |
python | def _set_hide_intf_loopback_holder(self, v, load=False):
"""
Setter method for hide_intf_loopback_holder, mapped from YANG variable /hide_intf_loopback_holder (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_hide_intf_loopback_holder is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_hide_intf_loopback_holder() directly.
YANG Description: An intermediary node that separates the loopback related
managed objects from rest of the interface types.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=hide_intf_loopback_holder.hide_intf_loopback_holder, is_container='container', presence=False, yang_name="hide-intf-loopback-holder", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'sort-priority': u'RUNNCFG_LEVEL_INTERFACE_LOOPBACK_CONFIG'}}, namespace='urn:brocade.com:mgmt:brocade-intf-loopback', defining_module='brocade-intf-loopback', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """hide_intf_loopback_holder must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=hide_intf_loopback_holder.hide_intf_loopback_holder, is_container='container', presence=False, yang_name="hide-intf-loopback-holder", rest_name="", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-drop-node-name': None, u'sort-priority': u'RUNNCFG_LEVEL_INTERFACE_LOOPBACK_CONFIG'}}, namespace='urn:brocade.com:mgmt:brocade-intf-loopback', defining_module='brocade-intf-loopback', yang_type='container', is_config=True)""",
})
self.__hide_intf_loopback_holder = t
if hasattr(self, '_set'):
self._set() |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'request') and self.request is not None:
_dict['request'] = self.request._to_dict()
if hasattr(self, 'response') and self.response is not None:
_dict['response'] = self.response._to_dict()
if hasattr(self, 'log_id') and self.log_id is not None:
_dict['log_id'] = self.log_id
if hasattr(self,
'request_timestamp') and self.request_timestamp is not None:
_dict['request_timestamp'] = self.request_timestamp
if hasattr(
self,
'response_timestamp') and self.response_timestamp is not None:
_dict['response_timestamp'] = self.response_timestamp
if hasattr(self, 'workspace_id') and self.workspace_id is not None:
_dict['workspace_id'] = self.workspace_id
if hasattr(self, 'language') and self.language is not None:
_dict['language'] = self.language
return _dict |
java | @Override
public void parse(ParseContext context)
throws MonetaryParseException {
if (!context.consume(token)) {
throw new MonetaryParseException(context.getOriginalInput(),
context.getErrorIndex());
}
} |
java | public void marshall(StartTaskExecutionRequest startTaskExecutionRequest, ProtocolMarshaller protocolMarshaller) {
if (startTaskExecutionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startTaskExecutionRequest.getTaskArn(), TASKARN_BINDING);
protocolMarshaller.marshall(startTaskExecutionRequest.getOverrideOptions(), OVERRIDEOPTIONS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public CORSConfigBuilder withAllowedHeaders(Collection<String> headerNames) {
Mutils.notNull("headerNames", headerNames);
this.allowedHeaders = headerNames;
return this;
} |
java | @Override
public final void setup() {
// Setup mandatory environment facets
try {
if (log.isDebugEnabled()) {
log.debug("ToolExecutionEnvironment setup -- Starting.");
}
// Build the ClassLoader as required for the JAXB tools
holder = builder.buildAndSet();
// Redirect the JUL logging handler used by the tools to the Maven log.
loggingHandlerEnvironmentFacet.setup();
// If requested, switch the locale
if (localeFacet != null) {
localeFacet.setup();
}
// Setup optional/extra environment facets
for (EnvironmentFacet current : extraFacets) {
try {
current.setup();
} catch (Exception e) {
throw new IllegalStateException("Could not setup() EnvironmentFacet of type ["
+ current.getClass().getName() + "]", e);
}
}
if (log.isDebugEnabled()) {
log.debug("ToolExecutionEnvironment setup -- Done.");
}
} catch (IllegalStateException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Could not setup mandatory ToolExecutionEnvironment.", e);
}
} |
python | def contains_no(self, prototype):
"""
Ensures no item of :attr:`subject` is of class *prototype*.
"""
for element in self._subject:
self._run(unittest_case.assertNotIsInstance, (element, prototype))
return ChainInspector(self._subject) |
java | private void orderPolicies(PoliciesBean policies) {
int idx = 1;
for (PolicyBean policy : policies.getPolicies()) {
policy.setOrderIndex(idx++);
}
} |
python | def add_record(self, is_sslv2=None, is_tls13=None):
"""
Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out.
"""
if is_sslv2 is None and is_tls13 is None:
v = (self.cur_session.tls_version or
self.cur_session.advertised_tls_version)
if v in [0x0200, 0x0002]:
is_sslv2 = True
elif v >= 0x0304:
is_tls13 = True
if is_sslv2:
self.buffer_out.append(SSLv2(tls_session=self.cur_session))
elif is_tls13:
self.buffer_out.append(TLS13(tls_session=self.cur_session))
else:
self.buffer_out.append(TLS(tls_session=self.cur_session)) |
java | @SafeVarargs
public static ScannerSupplier fromBugCheckerClasses(
Class<? extends BugChecker>... checkerClasses) {
return fromBugCheckerClasses(Arrays.asList(checkerClasses));
} |
python | def collaborators(self):
"""The collaborators for this app."""
return self._h._get_resources(
resource=('apps', self.name, 'collaborators'),
obj=Collaborator, app=self
) |
java | static String getClassSimpleName(String className) {
int lastPeriod = className.lastIndexOf(".");
if (lastPeriod != -1) {
return className.substring(lastPeriod + 1);
}
return className;
} |
java | public X getPrimaryID(T entity) {
if(mappingContext == null || conversionService == null) {
fetchMappingContextAndConversionService();
}
MongoPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(entity.getClass());
MongoPersistentProperty idProperty = persistentEntity.getIdProperty();
if(idProperty == null) {
return null;
}
// X idValue = BeanWrapper.create(entity, conversionService).getProperty(idProperty, this.primaryIDClass);
X idValue = (X) this.mappingContext.getPersistentEntity(this.entityClass).getPropertyAccessor(entity).getProperty(idProperty);
return idValue;
} |
java | @Override
public CPDisplayLayout[] findByUuid_PrevAndNext(long CPDisplayLayoutId,
String uuid, OrderByComparator<CPDisplayLayout> orderByComparator)
throws NoSuchCPDisplayLayoutException {
CPDisplayLayout cpDisplayLayout = findByPrimaryKey(CPDisplayLayoutId);
Session session = null;
try {
session = openSession();
CPDisplayLayout[] array = new CPDisplayLayoutImpl[3];
array[0] = getByUuid_PrevAndNext(session, cpDisplayLayout, uuid,
orderByComparator, true);
array[1] = cpDisplayLayout;
array[2] = getByUuid_PrevAndNext(session, cpDisplayLayout, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} |
java | public void setConfigurations(java.util.Collection<Configuration> configurations) {
if (configurations == null) {
this.configurations = null;
return;
}
this.configurations = new java.util.ArrayList<Configuration>(configurations);
} |
java | public int getTotalLeased(){
int total=0;
for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){
total+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections();
}
return total;
} |
java | private void checkCircularity(State state, Obligation obligation, int basicBlockId)
throws ObligationAcquiredOrReleasedInLoopException {
if (state.getPath().hasComponent(basicBlockId)) {
throw new ObligationAcquiredOrReleasedInLoopException(obligation);
}
} |
java | public float getQuote(String stock_name) throws Exception {
System.out.print("Getting quote for " + stock_name + ": ");
Float retval=stocks.get(stock_name);
if(retval == null) {
System.out.println("not found");
throw new Exception("Stock " + stock_name + " not found");
}
System.out.println(retval.floatValue());
return retval;
} |
python | def save_as_gif(self, gif_path, duration=0.25):
"""Package the selected slices into a single GIF for easy sharing and display (on web etc).
You must install imageio module separately to use this feature.
Parameters
----------
gif_path : str
Output path for the GIF image
duration : float
Duration of display of each frame in GIF, in sec.
"""
import imageio
gif_data = [img for img in self.get_slices()]
# using img.astype(np.uint32) is leaving noticable artefacts,
# depending on imageio inner conversion, which is rescaling okay
# TODO deal with differing sizes of slices, padding with zeros or white??
with warnings.catch_warnings():
# ignoring the warning for conversion to uint8
warnings.simplefilter('ignore')
imageio.mimsave(gif_path, gif_data, duration=duration) |
java | @JsonValue
@Override
public String value() {
return isCuried() ? String.format("%s:%s", curie, localPart) : localPart;
} |
java | @Override
public GenericRecord parse(ByteBuffer bytes)
{
if (bytes.remaining() < 5) {
throw new ParseException("record must have at least 5 bytes carrying version and schemaId");
}
byte version = bytes.get();
if (version != V1) {
throw new ParseException("found record of arbitrary version [%s]", version);
}
int schemaId = bytes.getInt();
Schema schemaObj = schemaObjs.get(schemaId);
if (schemaObj == null) {
throw new ParseException("Failed to find schema for id [%s]", schemaId);
}
DatumReader<GenericRecord> reader = new GenericDatumReader<>(schemaObj);
try (ByteBufferInputStream inputStream = new ByteBufferInputStream(Collections.singletonList(bytes))) {
return reader.read(null, DecoderFactory.get().binaryDecoder(inputStream, null));
}
catch (EOFException eof) {
// waiting for avro v1.9.0 (#AVRO-813)
throw new ParseException(
eof,
"Avro's unnecessary EOFException, detail: [%s]",
"https://issues.apache.org/jira/browse/AVRO-813"
);
}
catch (Exception e) {
throw new ParseException(e, "Fail to decode avro message with schemaId [%s].", schemaId);
}
} |
python | def _get(self, key, parser_result):
""" Given a type and a dict of parser results, return
the items as a list.
"""
try:
list_data = parser_result[key].asList()
if any(isinstance(obj, str) for obj in list_data):
txt_lines = [''.join(list_data)]
else:
txt_lines = [''.join(f) for f in list_data]
except KeyError:
txt_lines = []
return txt_lines |
python | def relative_startup_config_file(self):
"""
Returns the startup-config file relative to the project directory.
It's compatible with pre 1.3 projects.
:returns: path to startup-config file. None if the file doesn't exist
"""
path = os.path.join(self.working_dir, 'startup-config.cfg')
if os.path.exists(path):
return 'startup-config.cfg'
else:
return None |
python | def load(self, text, fieldnames=None):
"""Item from TSV representation."""
lines = text.split('\n')
fieldnames = load_line(lines[0])
values = load_line(lines[1])
self.__dict__ = dict(zip(fieldnames, values)) |
java | public AwsSecurityFindingFilters withResourceAwsIamAccessKeyStatus(StringFilter... resourceAwsIamAccessKeyStatus) {
if (this.resourceAwsIamAccessKeyStatus == null) {
setResourceAwsIamAccessKeyStatus(new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyStatus.length));
}
for (StringFilter ele : resourceAwsIamAccessKeyStatus) {
this.resourceAwsIamAccessKeyStatus.add(ele);
}
return this;
} |
java | private void sendSnapshotTxnId(SnapshotInfo toRestore) {
long txnId = toRestore != null ? toRestore.txnId : 0;
String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}";
LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes");
try {
m_zk.create(VoltZK.restore_snapshot_id, jsonData.getBytes(Constants.UTF8ENCODING),
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
} catch (Exception e) {
VoltDB.crashGlobalVoltDB("Failed to create Zookeeper node: " + e.getMessage(),
false, e);
}
} |
java | private static void setField(final Object instance, final Field field, final Object value)
{
final boolean accessability = field.isAccessible();
try
{
field.setAccessible(true);
field.set(instance, value);
}
catch (Exception e)
{
InjectionException.rethrow(e);
}
finally
{
field.setAccessible(accessability);
}
} |
python | async def loadCoreModule(self, ctor, conf=None):
'''
Load a single cortex module with the given ctor and conf.
Args:
ctor (str): The python module class path
conf (dict):Config dictionary for the module
'''
if conf is None:
conf = {}
modu = self._loadCoreModule(ctor, conf=conf)
try:
await s_coro.ornot(modu.preCoreModule)
except asyncio.CancelledError: # pragma: no cover
raise
except Exception:
logger.exception(f'module preCoreModule failed: {ctor}')
self.modules.pop(ctor, None)
return
mdefs = modu.getModelDefs()
self.model.addDataModels(mdefs)
cmds = modu.getStormCmds()
[self.addStormCmd(c) for c in cmds]
try:
await s_coro.ornot(modu.initCoreModule)
except asyncio.CancelledError: # pragma: no cover
raise
except Exception:
logger.exception(f'module initCoreModule failed: {ctor}')
self.modules.pop(ctor, None)
return
await self.fire('core:module:load', module=ctor)
return modu |
java | protected TreeNode dfs(Object cell, Object parent, Set<Object> visited) {
if (visited == null) {
visited = new HashSet<Object>();
}
TreeNode node = null;
mxIGraphModel model = graph.getModel();
if (cell != null && !visited.contains(cell) && (!isVertexIgnored(cell) || isBoundaryEvent(cell))) {
visited.add(cell);
node = createNode(cell);
TreeNode prev = null;
Object[] out = graph.getEdges(cell, parent, invert, !invert, false);
for (int i = 0; i < out.length; i++) {
Object edge = out[i];
if (!isEdgeIgnored(edge)) {
// Resets the points on the traversed edge
if (resetEdges) {
setEdgePoints(edge, null);
}
// Checks if terminal in same swimlane
Object target = graph.getView().getVisibleTerminal(edge, invert);
TreeNode tmp = dfs(target, parent, visited);
if (tmp != null && model.getGeometry(target) != null) {
if (prev == null) {
node.child = tmp;
} else {
prev.next = tmp;
}
prev = tmp;
}
}
}
}
return node;
} |
java | public void putClientMetrics(ClientMetrics clientMetrics)
throws GalaxyFDSClientException {
URI uri = formatUri(fdsConfig.getBaseUri(), "", (SubResource[]) null);
ContentType contentType = ContentType.APPLICATION_JSON;
HashMap<String, String> params = new HashMap<String, String>();
params.put("clientMetrics", "");
HttpEntity requestEntity = getJsonStringEntity(clientMetrics, contentType);
HttpUriRequest httpRequest = prepareRequestMethod(uri, HttpMethod.PUT,
contentType, null, params, null, requestEntity);
HttpResponse response = executeHttpRequest(httpRequest, Action.PutClientMetrics);
processResponse(response, null, "put client metrics");
} |
java | static void write(List<AccessLogComponent> format, RequestLog log) {
final VirtualHost host = ((ServiceRequestContext) log.context()).virtualHost();
final Logger logger = host.accessLogger();
if (!format.isEmpty() && logger.isInfoEnabled()) {
logger.info(format(format, log));
}
} |
java | public static Dictionary read(InputStream fsaStream, InputStream metadataStream) throws IOException {
return new Dictionary(FSA.read(fsaStream), DictionaryMetadata.read(metadataStream));
} |
java | static <T extends FunctionMeta> Map<T, IDataModel> toMetaFunctions(IDataModel book, Class<T> metaClass) {
return toMetaFunctions(DataModelConverters.toWorkbook(book), metaClass);
} |
java | static File getOutputDirectory(MavenProject rootModule) {
String directoryName = rootModule.getBuild().getDirectory() + "/" + OUTPUT_DIRECTORY;
File directory = new File(directoryName);
directory.mkdirs();
return directory;
} |
java | public void addSummaryLinkComment(AbstractMemberWriter mw, Element member, Content contentTree) {
List<? extends DocTree> tags = utils.getFirstSentenceTrees(member);
addSummaryLinkComment(mw, member, tags, contentTree);
} |
python | def list(self):
"""Lists all sessions in the store.
.. versionadded:: 0.6
"""
before, after = self.filename_template.split('%s', 1)
filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),
re.escape(after)))
result = []
for filename in os.listdir(self.path):
#: this is a session that is still being saved.
if filename.endswith(_fs_transaction_suffix):
continue
match = filename_re.match(filename)
if match is not None:
result.append(match.group(1))
return result |
java | public static Validator<CharSequence> maxLength(@NonNull final Context context,
final int maxLength) {
return new MaxLengthValidator(context, R.string.default_error_message, maxLength);
} |
python | def probably_identical(self):
"""
:returns: Whether or not these two functions are identical.
"""
if len(self._unmatched_blocks_from_a | self._unmatched_blocks_from_b) > 0:
return False
for (a, b) in self._block_matches:
if not self.blocks_probably_identical(a, b):
return False
return True |
python | def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Relation.DoesNotExist:
return
if relation.entities.count() == 0:
relation.delete()
# Wait for partitions to be recreated.
transaction.on_commit(lambda: process_signal(instance.relation_id)) |
java | public com.google.api.ads.adwords.axis.v201809.cm.Bid getFirstPositionCpc() {
return firstPositionCpc;
} |
python | def mark_seen(self):
"""
Mark the selected message or comment as seen.
"""
data = self.get_selected_item()
if data['is_new']:
with self.term.loader('Marking as read'):
data['object'].mark_as_read()
if not self.term.loader.exception:
data['is_new'] = False
else:
with self.term.loader('Marking as unread'):
data['object'].mark_as_unread()
if not self.term.loader.exception:
data['is_new'] = True |
python | def renderbuffer(self, size, components=4, *, samples=0, dtype='f1') -> 'Renderbuffer':
'''
:py:class:`Renderbuffer` objects are OpenGL objects that contain images.
They are created and used specifically with :py:class:`Framebuffer` objects.
Args:
size (tuple): The width and height of the renderbuffer.
components (int): The number of components 1, 2, 3 or 4.
Keyword Args:
samples (int): The number of samples. Value 0 means no multisample format.
dtype (str): Data type.
Returns:
:py:class:`Renderbuffer` object
'''
res = Renderbuffer.__new__(Renderbuffer)
res.mglo, res._glo = self.mglo.renderbuffer(size, components, samples, dtype)
res._size = size
res._components = components
res._samples = samples
res._dtype = dtype
res._depth = False
res.ctx = self
res.extra = None
return res |
python | def SecurityCheck(self, func, request, *args, **kwargs):
"""Wrapping function."""
request.user = u""
authorized = False
try:
auth_type, authorization = request.headers.get("Authorization",
" ").split(" ", 1)
if auth_type == "Basic":
authorization_string = authorization.decode("base64").decode("utf-8")
user, password = authorization_string.split(":", 1)
if data_store.AFF4Enabled():
token = access_control.ACLToken(username=user)
fd = aff4.FACTORY.Open(
"aff4:/users/%s" % user,
aff4_type=aff4_users.GRRUser,
token=token)
crypted_password = fd.Get(fd.Schema.PASSWORD)
if crypted_password and crypted_password.CheckPassword(password):
authorized = True
# The password is ok - update the user
request.user = user
else:
try:
user_obj = data_store.REL_DB.ReadGRRUser(user)
if user_obj.password.CheckPassword(password):
authorized = True
# The password is ok - update the user
request.user = user
except db.UnknownGRRUserError:
pass
except access_control.UnauthorizedAccess as e:
logging.warning("UnauthorizedAccess: %s for %s", e, request)
except (IndexError, KeyError, IOError):
pass
if not authorized:
result = werkzeug_wrappers.Response("Unauthorized", status=401)
result.headers["WWW-Authenticate"] = "Basic realm='Secure Area'"
return result
# Modify this to implement additional checking (e.g. enforce SSL).
return func(request, *args, **kwargs) |
python | def add_field(self, name, data):
"""
Add a new field to the datamat.
Parameters:
name : string
Name of the new field
data : list
Data for the new field, must be same length as all other fields.
"""
if name in self._fields:
raise ValueError
if not len(data) == self._num_fix:
raise ValueError
self._fields.append(name)
self.__dict__[name] = data |
python | def get_cloud_init_mime(cloud_init):
'''
Get a mime multipart encoded string from a cloud-init dict. Currently
supports boothooks, scripts and cloud-config.
CLI Example:
.. code-block:: bash
salt myminion boto.get_cloud_init_mime <cloud init>
'''
if isinstance(cloud_init, six.string_types):
cloud_init = salt.utils.json.loads(cloud_init)
_cloud_init = email.mime.multipart.MIMEMultipart()
if 'boothooks' in cloud_init:
for script_name, script in six.iteritems(cloud_init['boothooks']):
_script = email.mime.text.MIMEText(script, 'cloud-boothook')
_cloud_init.attach(_script)
if 'scripts' in cloud_init:
for script_name, script in six.iteritems(cloud_init['scripts']):
_script = email.mime.text.MIMEText(script, 'x-shellscript')
_cloud_init.attach(_script)
if 'cloud-config' in cloud_init:
cloud_config = cloud_init['cloud-config']
_cloud_config = email.mime.text.MIMEText(
salt.utils.yaml.safe_dump(cloud_config, default_flow_style=False),
'cloud-config')
_cloud_init.attach(_cloud_config)
return _cloud_init.as_string() |
python | def done(self):
"""Returns True if the call was successfully cancelled or finished
running, False otherwise. This function updates the executionQueue
so it receives all the awaiting message."""
# Flush the current future in the local buffer (potential deadlock
# otherwise)
try:
scoop._control.execQueue.remove(self)
scoop._control.execQueue.socket.sendFuture(self)
except ValueError as e:
# Future was not in the local queue, everything is fine
pass
# Process buffers
scoop._control.execQueue.updateQueue()
return self._ended() |
python | def list(self, sleep=1):
'''
List the windows.
Sleep is useful to wait some time before obtaining the new content when something in the
window has changed.
This also sets L{self.windows} as the list of windows.
@type sleep: int
@param sleep: sleep in seconds before proceeding to dump the content
@return: the list of windows
'''
if sleep > 0:
time.sleep(sleep)
if self.useUiAutomator:
raise Exception("Not implemented yet: listing windows with UiAutomator")
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((VIEW_SERVER_HOST, self.localPort))
except socket.error, ex:
raise RuntimeError("ERROR: Connecting to %s:%d: %s" % (VIEW_SERVER_HOST, self.localPort, ex))
s.send('list\r\n')
received = ""
doneRE = re.compile("DONE")
while True:
received += s.recv(1024)
if doneRE.search(received[-7:]):
break
s.close()
if DEBUG:
self.received = received
if DEBUG_RECEIVED:
print >>sys.stderr, "received %d chars" % len(received)
print >>sys.stderr
print >>sys.stderr, received
print >>sys.stderr
self.windows = {}
for line in received.split('\n'):
if not line:
break
if doneRE.search(line):
break
values = line.split()
if len(values) > 1:
package = values[1]
else:
package = "UNKNOWN"
if len(values) > 0:
wid = values[0]
else:
wid = '00000000'
self.windows[int('0x' + wid, 16)] = package
return self.windows |
python | def dump(destination, ms, single=False, pretty_print=False, **kwargs):
"""
Serialize Xmrs objects to the Prolog representation and write to a file.
Args:
destination: filename or file object where data will be written
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object
instead of as an iterator
pretty_print: if `True`, add newlines and indentation
"""
text = dumps(ms,
single=single,
pretty_print=pretty_print,
**kwargs)
if hasattr(destination, 'write'):
print(text, file=destination)
else:
with open(destination, 'w') as fh:
print(text, file=fh) |
java | public synchronized static void read(int fd, Collection<ByteBuffer> collection) throws IOException{
collection.add(ByteBuffer.wrap(read(fd)));
} |
python | def job_info(self, **kwargs):
"""
Get the information about the jobs returned by a particular search.
See the [GetJobs][] documentation for more info.
[GetJobs]: http://casjobs.sdss.org/casjobs/services/jobs.asmx?op=GetJobs
"""
search = ";".join(["%s : %s"%(k, str(kwargs[k])) for k in kwargs])
params = {"owner_wsid": self.userid, "owner_pw": self.password,
"conditions": search, "includeSystem": False}
r = self._send_request("GetJobs", params=params)
results = []
for n in minidom.parseString(r.text).getElementsByTagName("CJJob"):
results.append({})
for e in n.childNodes:
if e.nodeType != e.TEXT_NODE:
results[-1][e.tagName] = e.firstChild.data
return results |
python | def remove(self, id_equipamento, id_egrupo):
"""Remove a associacao de um grupo de equipamento com um equipamento a partir do seu identificador.
:param id_egrupo: Identificador do grupo de equipamento.
:param id_equipamento: Identificador do equipamento.
:return: None
:raise EquipamentoNaoExisteError: Equipamento não cadastrado.
:raise GrupoEquipamentoNaoExisteError: Grupo de equipamento não cadastrado.
:raise InvalidParameterError: O identificador do grupo é nulo ou inválido.
:raise DataBaseError: Falha na networkapi ao acessar o banco de dados.
:raise XMLError: Falha na networkapi ao gerar o XML de resposta.
"""
if not is_valid_int_param(id_egrupo):
raise InvalidParameterError(
u'O identificador do grupo de equipamento é inválido ou não foi informado.')
if not is_valid_int_param(id_equipamento):
raise InvalidParameterError(
u'O identificador do equipamento é inválido ou não foi informado.')
url = 'egrupo/equipamento/' + \
str(id_equipamento) + '/egrupo/' + str(id_egrupo) + '/'
code, xml = self.submit(None, 'GET', url)
return self.response(code, xml) |
java | @Override
public Record nextRecord() {
Record next = sequenceRecordReader.nextRecord();
next.setRecord(transformProcess.execute(next.getRecord()));
return next;
} |
python | def createCertRequest(pkey, digest="sha256"):
"""
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
arguments are:
C - Country name
ST - State or province name
L - Locality name
O - Organization name
OU - Organizational unit name
CN - Common name
emailAddress - E-mail address
Returns: The certificate request in an X509Req object
"""
req = crypto.X509Req()
req.get_subject().C = "FR"
req.get_subject().ST = "IDF"
req.get_subject().L = "Paris"
req.get_subject().O = "RedHat" # noqa
req.get_subject().OU = "DCI"
req.get_subject().CN = "DCI-remoteCI"
req.set_pubkey(pkey)
req.sign(pkey, digest)
return req |
java | private IBatchServiceBase getService(Name serviceType) throws BatchContainerServiceException {
String sourceMethod = "getService";
if (logger.isLoggable(Level.FINE))
logger.entering(sourceClass, sourceMethod + ", serviceType=" + serviceType);
initIfNecessary();
IBatchServiceBase service = new ServiceLoader(serviceType).getService();
if (logger.isLoggable(Level.FINE))
logger.exiting(sourceClass, sourceMethod);
return service;
} |
java | @Override
public void setContentHandler(ContentHandler handler) {
if (handler == null) {
handler = base;
}
contentHandler = handler;
} |
python | def _set_environment_variables(self):
"""Initializes the correct environment variables for spark"""
cmd = []
# special case for driver JVM properties.
self._set_launcher_property("driver-memory", "spark.driver.memory")
self._set_launcher_property("driver-library-path", "spark.driver.extraLibraryPath")
self._set_launcher_property("driver-class-path", "spark.driver.extraClassPath")
self._set_launcher_property("driver-java-options", "spark.driver.extraJavaOptions")
self._set_launcher_property("executor-memory", "spark.executor.memory")
self._set_launcher_property("executor-cores", "spark.executor.cores")
for key, val in self._spark_launcher_args.items():
if val is None:
continue
val = list(as_iterable(val))
if len(val):
if key in self._boolean_args:
cmd.append("--{key}".format(key=key))
else:
sep = self._spark_launcher_arg_sep.get(key, ',')
cmd.append('--{key} {val}'.format(key=key, val=sep.join(str(x) for x in val)))
cmd += ['pyspark-shell']
cmd_line = ' '.join(x for x in cmd if x)
os.environ["PYSPARK_SUBMIT_ARGS"] = cmd_line
log.info("spark-submit arguments: %s", cmd_line) |
python | def add_flooded_field(self, shapefile_path):
"""Create the layer from the local shp adding the flooded field.
.. versionadded:: 3.3
Use this method to add a calculated field to a shapefile. The shapefile
should have a field called 'count' containing the number of flood
reports for the field. The field values will be set to 0 if the count
field is < 1, otherwise it will be set to 1.
:param shapefile_path: Path to the shapefile that will have the flooded
field added.
:type shapefile_path: basestring
:return: A vector layer with the flooded field added.
:rtype: QgsVectorLayer
"""
layer = QgsVectorLayer(
shapefile_path, self.tr('Jakarta Floods'), 'ogr')
# Add a calculated field indicating if a poly is flooded or not
# from qgis.PyQt.QtCore import QVariant
layer.startEditing()
# Add field with integer from 0 to 4 which represents the flood
# class. Its the same as 'state' field except that is being treated
# as a string.
# This is used for cartography
flood_class_field = QgsField('floodclass', QVariant.Int)
layer.addAttribute(flood_class_field)
layer.commitChanges()
layer.startEditing()
flood_class_idx = layer.fields().lookupField('floodclass')
flood_class_expression = QgsExpression('to_int(state)')
context = QgsExpressionContext()
context.setFields(layer.fields())
flood_class_expression.prepare(context)
# Add field with boolean flag to say if the area is flooded
# This is used by the impact function
flooded_field = QgsField('flooded', QVariant.Int)
layer.dataProvider().addAttributes([flooded_field])
layer.commitChanges()
layer.startEditing()
flooded_idx = layer.fields().lookupField('flooded')
flood_flag_expression = QgsExpression('state > 0')
flood_flag_expression.prepare(context)
for feature in layer.getFeatures():
context.setFeature(feature)
feature[flood_class_idx] = flood_class_expression.evaluate(context)
feature[flooded_idx] = flood_flag_expression.evaluate(context)
layer.updateFeature(feature)
layer.commitChanges()
return layer |
java | public Map<String, String> getMetatags() {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : _metatags.entrySet()) {
String key = entry.getKey();
if (!ReservedField.isReservedField(key)) {
result.put(key, entry.getValue());
}
}
return Collections.unmodifiableMap(result);
} |
java | protected String getNonNamespacedNodeName(Node node) {
String name = node.getLocalName();
if (name == null) {
return node.getNodeName();
}
return name;
} |
java | @Override
public SchemaManager getSchemaManager(Map<String, Object> externalProperty)
{
if (schemaManager == null)
{
initializePropertyReader();
schemaManager = new CassandraSchemaManager(ThriftClientFactory.class.getName(), externalProperties,
kunderaMetadata);
}
return schemaManager;
} |
java | @Override
public boolean canRunInOneFragment() {
assert(getScanPartitioning() != null);
assert(m_subqueryStmt != null);
if (getScanPartitioning().getCountOfPartitionedTables() == 0) {
return true;
}
// recursive check for its nested subqueries that require coordination
// of their results.
if (failsSingleFragmentTest()) {
return false;
}
// Tentative assignment in case of early return.
// This gets immediately reset if it passes all the tests.
m_failedSingleFragmentTest = true;
if (m_subqueryStmt instanceof ParsedUnionStmt) {
// Union are just returned
return false;
}
if ( ! (m_subqueryStmt instanceof ParsedSelectStmt)) {
throw new PlanningErrorException("Unsupported subquery found in FROM clause:" +
m_subqueryStmt);
}
ParsedSelectStmt selectStmt = (ParsedSelectStmt)m_subqueryStmt;
// Now If query has LIMIT/OFFSET/DISTINCT on a replicated table column,
// we should get rid of the receive node. I (--paul) don't know what this means.
if (selectStmt.hasLimitOrOffset() || selectStmt.hasDistinctWithGroupBy()) {
return false;
}
// If the query uses the partitioned materialized view table with the
// need to Re-aggregate, then we can not get rid of the receive node.
// This is also caught in StatementPartitioning when analyzing the join criteria,
// because it contains a partitioned view that does not have a partition column.
if (selectStmt.m_mvFixInfo.needed()) {
return false;
}
// Table aggregate cases should not get rid of the receive node
if (selectStmt.hasAggregateOrGroupby()) {
if (!selectStmt.isGrouped()) {
m_tableAggregateSubquery = true;
return false;
}
// For group by queries, there are two cases on group by columns.
// (1) Does not contain a partition column:
// If joined with a partitioned table in the parent query, it will
// violate the partitioned table join criteria.
// Detect case (1) to mark receive node.
if ( ! selectStmt.hasPartitionColumnInGroupby()) {
return false;
}
}
if ( ! selectStmt.hasPartitionColumnInWindowFunctionExpression()) {
return false;
}
// Now. If this sub-query joins with a partitioned table in the parent statement,
// push the join down by removing the send/receive plan node pair.
m_failedSingleFragmentTest = false;
return true;
} |
python | def match(pattern, data, **parse_kwargs):
"""Returns all matched values of pattern in data"""
return [m.value for m in parse(pattern, **parse_kwargs).find(data)] |
python | def set_power(self, power):
"""Send Power command."""
req_url = ENDPOINTS["setPower"].format(self.ip_address, self.zone_id)
params = {"power": "on" if power else "standby"}
return request(req_url, params=params) |
python | def create_datastore_for_topline(self, delete_first=0, path=None):
# type: (int, Optional[str]) -> None
"""For tabular data, create a resource in the HDX datastore which enables data preview in HDX using the built in
YAML definition for a topline. If path is not supplied, the file is first downloaded from HDX.
Args:
delete_first (int): Delete datastore before creation. 0 = No, 1 = Yes, 2 = If no primary key. Defaults to 0.
path (Optional[str]): Local path to file that was uploaded. Defaults to None.
Returns:
None
"""
data = load_yaml(script_dir_plus_file(join('..', 'hdx_datasource_topline.yml'), Resource))
self.create_datastore_from_dict_schema(data, delete_first, path=path) |
python | def make_interface_child(device_name, interface_name, parent_name):
'''
.. versionadded:: 2019.2.0
Set an interface as part of a LAG.
device_name
The name of the device, e.g., ``edge_router``.
interface_name
The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``.
parent_name
The name of the LAG interface, e.g., ``ae13``.
CLI Example:
.. code-block:: bash
salt myminion netbox.make_interface_child xe-1/0/2 ae13
'''
nb_device = get_('dcim', 'devices', name=device_name)
nb_parent = get_('dcim', 'interfaces', device_id=nb_device['id'], name=parent_name)
if nb_device and nb_parent:
return update_interface(device_name, interface_name, lag=nb_parent['id'])
else:
return False |
python | def create_identity_matcher(matcher='default', blacklist=None, sources=None,
strict=True):
"""Create an identity matcher of the given type.
Factory function that creates an identity matcher object of the type
defined on 'matcher' parameter. A blacklist can also be added to
ignore those values while matching.
:param matcher: type of the matcher
:param blacklist: list of entries to ignore while matching
:param sources: only match the identities from these sources
:param strict: strict matching (i.e, well-formed email addresses)
:returns: a identity matcher object of the given type
:raises MatcherNotSupportedError: when the given matcher type is not
supported or available
"""
import sortinghat.matching as matching
if matcher not in matching.SORTINGHAT_IDENTITIES_MATCHERS:
raise MatcherNotSupportedError(matcher=str(matcher))
klass = matching.SORTINGHAT_IDENTITIES_MATCHERS[matcher]
return klass(blacklist=blacklist, sources=sources, strict=strict) |
python | def encrypt(self, keys=None, cek="", iv="", **kwargs):
"""
Encrypt a payload
:param keys: A set of possibly usable keys
:param cek: Content master key
:param iv: Initialization vector
:param kwargs: Extra key word arguments
:return: Encrypted message
"""
_alg = self["alg"]
# Find Usable Keys
if keys:
keys = self.pick_keys(keys, use="enc")
else:
keys = self.pick_keys(self._get_keys(), use="enc")
if not keys:
logger.error(KEY_ERR.format(_alg))
raise NoSuitableEncryptionKey(_alg)
# Determine Encryption Class by Algorithm
if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
encrypter = JWE_RSA(self.msg, **self._dict)
elif _alg.startswith("A") and _alg.endswith("KW"):
encrypter = JWE_SYM(self.msg, **self._dict)
else: # _alg.startswith("ECDH-ES"):
encrypter = JWE_EC(**self._dict)
cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
self.msg, key=keys[0], **self._dict)
kwargs["encrypted_key"] = encrypted_key
kwargs["params"] = params
if cek:
kwargs["cek"] = cek
if iv:
kwargs["iv"] = iv
for key in keys:
if isinstance(key, SYMKey):
_key = key.key
elif isinstance(key, ECKey):
_key = key.public_key()
else: # isinstance(key, RSAKey):
_key = key.public_key()
if key.kid:
encrypter["kid"] = key.kid
try:
token = encrypter.encrypt(key=_key, **kwargs)
self["cek"] = encrypter.cek if 'cek' in encrypter else None
except TypeError as err:
raise err
else:
logger.debug(
"Encrypted message using key with kid={}".format(key.kid))
return token |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.