language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def ListProfilers(self):
"""Lists information about the available profilers."""
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=['Name', 'Description'],
title='Profilers')
profilers_information = sorted(
profiling.ProfilingArgumentsHelper.PROFILERS_INFORMATION.items())
for name, description in profilers_information:
table_view.AddRow([name, description])
table_view.Write(self._output_writer) |
java | public void setIPRanges(java.util.Collection<IPRange> iPRanges) {
if (iPRanges == null) {
this.iPRanges = null;
return;
}
this.iPRanges = new com.amazonaws.internal.SdkInternalList<IPRange>(iPRanges);
} |
java | public Node getNamedItemNS(String namespaceURI, String localName)
{
Node retNode = null;
for (int n = dtm.getFirstAttribute(element); n != DTM.NULL;
n = dtm.getNextAttribute(n))
{
if (localName.equals(dtm.getLocalName(n)))
{
String nsURI = dtm.getNamespaceURI(n);
if ((namespaceURI == null && nsURI == null)
|| (namespaceURI != null && namespaceURI.equals(nsURI)))
{
retNode = dtm.getNode(n);
break;
}
}
}
return retNode;
} |
java | protected Statement methodBlock(final FrameworkMethod method) {
Object test;
try {
test = new ReflectiveCallable() {
@Override
protected Object runReflectiveCall() throws Throwable {
return createTest(method);
}
}.run();
} catch (Throwable e) {
return new Fail(e);
}
Statement statement = methodInvoker(method, test);
statement = possiblyExpectingExceptions(method, test, statement);
statement = withPotentialTimeout(method, test, statement);
statement = withBefores(method, test, statement);
statement = withAfters(method, test, statement);
statement = withRules(method, test, statement);
statement = withInterruptIsolation(statement);
return statement;
} |
python | def create_kubernetes_role(self, name, bound_service_account_names, bound_service_account_namespaces, ttl="",
max_ttl="", period="", policies=None, mount_point='kubernetes'):
"""POST /auth/<mount_point>/role/:name
:param name: Name of the role.
:type name: str.
:param bound_service_account_names: List of service account names able to access this role. If set to "*" all
names are allowed, both this and bound_service_account_namespaces can not be "*".
:type bound_service_account_names: list.
:param bound_service_account_namespaces: List of namespaces allowed to access this role. If set to "*" all
namespaces are allowed, both this and bound_service_account_names can not be set to "*".
:type bound_service_account_namespaces: list.
:param ttl: The TTL period of tokens issued using this role in seconds.
:type ttl: str.
:param max_ttl: The maximum allowed lifetime of tokens issued in seconds using this role.
:type max_ttl: str.
:param period: If set, indicates that the token generated using this role should never expire.
The token should be renewed within the duration specified by this value. At each renewal, the token's TTL will
be set to the value of this parameter.
:type period: str.
:param policies: Policies to be set on tokens issued using this role
:type policies: list.
:param mount_point: The "path" the k8s auth backend was mounted on. Vault currently defaults to "kubernetes".
:type mount_point: str.
:return: Will be an empty body with a 204 status code upon success
:rtype: requests.Response.
"""
if bound_service_account_names == '*' and bound_service_account_namespaces == '*':
error_message = 'bound_service_account_names and bound_service_account_namespaces can not both be set to "*"'
raise exceptions.ParamValidationError(error_message)
params = {
'bound_service_account_names': bound_service_account_names,
'bound_service_account_namespaces': bound_service_account_namespaces,
'ttl': ttl,
'max_ttl': max_ttl,
'period': period,
'policies': policies,
}
url = 'v1/auth/{0}/role/{1}'.format(mount_point, name)
return self._adapter.post(url, json=params) |
python | def get_obj_attrs(obj):
""" Return a dictionary built from the attributes of the given object.
"""
pr = {}
if obj is not None:
if isinstance(obj, numpy.core.records.record):
for name in obj.dtype.names:
pr[name] = getattr(obj, name)
elif hasattr(obj, '__dict__') and obj.__dict__:
pr = obj.__dict__
elif hasattr(obj, '__slots__'):
for slot in obj.__slots__:
if hasattr(obj, slot):
pr[slot] = getattr(obj, slot)
elif isinstance(obj, dict):
pr = obj.copy()
else:
for name in dir(obj):
try:
value = getattr(obj, name)
if not name.startswith('__') and not inspect.ismethod(value):
pr[name] = value
except:
continue
return pr |
java | public static ProviderInfo parseProviderInfo(String originUrl) {
String url = originUrl;
String host = null;
int port = 80;
String path = null;
String schema = null;
int i = url.indexOf("://"); // seperator between schema and body
if (i > 0) {
schema = url.substring(0, i); // http
url = url.substring(i + 3); // 127.0.0.1:8080/xxx/yyy?a=1&b=2&[c]=[ccc]
}
Map<String, String> parameters = new HashMap<String, String>();
i = url.indexOf('?'); // seperator between body and parameters
if (i >= 0) {
String[] parts = url.substring(i + 1).split("\\&"); //a=1&b=2&[c]=[ccc]
for (String part : parts) {
part = part.trim();
if (part.length() > 0) {
int j = part.indexOf('=');
if (j >= 0) {
parameters.put(part.substring(0, j), part.substring(j + 1));
} else {
parameters.put(part, part);
}
}
}
url = url.substring(0, i); // 127.0.0.1:8080/xxx/yyy
}
i = url.indexOf('/');
if (i >= 0) {
path = url.substring(i + 1); // xxx/yyy
url = url.substring(0, i); // 127.0.0.1:8080
}
i = url.indexOf(':');
if (i >= 0 && i < url.length() - 1) {
port = Integer.parseInt(url.substring(i + 1)); // 8080
url = url.substring(0, i); // 127.0.0.1
}
if (url.length() > 0) {
host = url; // 127.0.0.1
}
ProviderInfo providerInfo = new ProviderInfo();
providerInfo.setOriginUrl(originUrl);
providerInfo.setHost(host);
if (port != 80) {
providerInfo.setPort(port);
}
if (path != null) {
providerInfo.setPath(path);
}
if (schema != null) {
providerInfo.setProtocolType(schema);
}
// 解析特殊属性
// p=1
String protocolStr = getValue(parameters, RPC_REMOTING_PROTOCOL);
if (schema == null && protocolStr != null) {
// 1->bolt 13->tr
if ((RemotingConstants.PROTOCOL_BOLT + "").equals(protocolStr)) {
protocolStr = PROTOCOL_TYPE_BOLT;
} else if ((RemotingConstants.PROTOCOL_TR + "").equals(protocolStr)) {
protocolStr = PROTOCOL_TYPE_TR;
}
try {
providerInfo.setProtocolType(protocolStr);
} catch (Exception e) {
LOGGER.error("protocol is invalid : {}", originUrl);
}
}
// TODO SOFAVERSION v=4.0
// timeout
String timeoutStr = getValue(parameters, ATTR_TIMEOUT, TIMEOUT);
if (timeoutStr != null) {
removeOldKeys(parameters, ATTR_TIMEOUT, TIMEOUT);
try {// 加入动态
providerInfo.setDynamicAttr(ATTR_TIMEOUT, Integer.parseInt(timeoutStr));
} catch (Exception e) {
LOGGER.error("timeout is invalid : {}", originUrl);
}
}
// serializeType 使用字符传递
String serializationStr = getValue(parameters, ATTR_SERIALIZATION,
SERIALIZE_TYPE_KEY);
if (serializationStr != null) {
removeOldKeys(parameters, ATTR_SERIALIZATION, SERIALIZE_TYPE_KEY);
// 1 -> hessian 2->java 4->hessian2 11->protobuf
if ((RemotingConstants.SERIALIZE_CODE_HESSIAN + "").equals(serializationStr)) {
serializationStr = SERIALIZE_HESSIAN;
} else if ((RemotingConstants.SERIALIZE_CODE_JAVA + "").equals(serializationStr)) {
serializationStr = SERIALIZE_JAVA;
} else if ((RemotingConstants.SERIALIZE_CODE_HESSIAN2 + "").equals(serializationStr)) {
serializationStr = SERIALIZE_HESSIAN2;
} else if ((RemotingConstants.SERIALIZE_CODE_PROTOBUF + "").equals(serializationStr)) {
serializationStr = SERIALIZE_PROTOBUF;
}
providerInfo.setSerializationType(serializationStr);
}
// appName
String appNameStr = getValue(parameters, ATTR_APP_NAME, APP_NAME,
SofaRegistryConstants.SELF_APP_NAME);
if (appNameStr != null) {
removeOldKeys(parameters, APP_NAME, SofaRegistryConstants.SELF_APP_NAME);
providerInfo.setStaticAttr(ATTR_APP_NAME, appNameStr);
}
// connections
String connections = getValue(parameters, ATTR_CONNECTIONS, SofaRegistryConstants.CONNECTI_NUM);
if (connections != null) {
removeOldKeys(parameters, SofaRegistryConstants.CONNECTI_NUM);
providerInfo.setStaticAttr(ATTR_CONNECTIONS, connections);
}
//rpc version
String rpcVersion = getValue(parameters, ATTR_RPC_VERSION);
providerInfo.setRpcVersion(CommonUtils.parseInt(rpcVersion, providerInfo.getRpcVersion()));
// weight
String weightStr = getValue(parameters, ATTR_WEIGHT, WEIGHT_KEY);
if (weightStr != null) {
removeOldKeys(parameters, ATTR_WEIGHT, WEIGHT_KEY);
try {
int weight = Integer.parseInt(weightStr);
providerInfo.setWeight(weight);
providerInfo.setStaticAttr(ATTR_WEIGHT, weightStr);
} catch (Exception e) {
LOGGER.error("weight is invalid : {}", originUrl);
}
}
// warmupTime
String warmupTimeStr = getValue(parameters, ATTR_WARMUP_TIME, SofaRegistryConstants.WARMUP_TIME_KEY);
int warmupTime = 0;
if (warmupTimeStr != null) {
removeOldKeys(parameters, ATTR_WARMUP_TIME, SofaRegistryConstants.WARMUP_TIME_KEY);
try {
warmupTime = Integer.parseInt(warmupTimeStr);
providerInfo.setStaticAttr(ATTR_WARMUP_TIME, warmupTimeStr);
} catch (Exception e) {
LOGGER.error("warmupTime is invalid : {}", originUrl);
}
}
// warmupWeight
String warmupWeightStr = getValue(parameters, ATTR_WARMUP_WEIGHT,
SofaRegistryConstants.WARMUP_WEIGHT_KEY);
int warmupWeight = 0;
if (warmupWeightStr != null) {
removeOldKeys(parameters, ATTR_WARMUP_WEIGHT, SofaRegistryConstants.WARMUP_WEIGHT_KEY);
try {
warmupWeight = Integer.parseInt(warmupWeightStr);
providerInfo.setStaticAttr(ATTR_WARMUP_WEIGHT, warmupWeightStr);
} catch (Exception e) {
LOGGER.error("warmupWeight is invalid : {}", originUrl);
}
}
// startTime
String startTimeStr = getValue(parameters, ATTR_START_TIME);
long startTime = 0L;
if (startTimeStr != null) {
try {
startTime = Long.parseLong(startTimeStr);
} catch (Exception e) {
LOGGER.error("startTime is invalid : {}", originUrl);
}
}
if (startTime == 0) {
startTime = System.currentTimeMillis();
}
// 设置预热状态
if (StringUtils.isNotBlank(warmupTimeStr) && StringUtils.isNotBlank(warmupWeightStr)) {
if (warmupTime > 0) {
providerInfo.setStatus(ProviderStatus.WARMING_UP);
providerInfo.setDynamicAttr(ATTR_WARMUP_WEIGHT, warmupWeight);
providerInfo.setDynamicAttr(ATTR_WARM_UP_END_TIME, startTime + warmupTime);
}
}
// 解析hostMachineName
String hostMachineName = getValue(parameters, HOST_MACHINE_KEY);
if (StringUtils.isNotBlank(hostMachineName)) {
providerInfo.setDynamicAttr(ATTR_HOST_MACHINE, hostMachineName);
}
// 解析方法参数
List<String> methodKeys = new ArrayList<String>();
Map<String, Object> methodParameters = new HashMap<String, Object>();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (entry.getKey().startsWith("[") && entry.getKey().endsWith("]") && entry.getValue().startsWith("[") &&
entry.getValue().endsWith("]")) { // 认为是方法配置
String key = entry.getKey();
methodKeys.add(key);
String methodName = key.substring(1, key.length() - 1);
parseMethodInfo(methodParameters, methodName, entry.getValue());
}
}
for (String methodKey : methodKeys) {
parameters.remove(methodKey);
}
providerInfo.getStaticAttrs().putAll(parameters);
providerInfo.getDynamicAttrs().putAll(methodParameters);
providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "sofa");
return providerInfo;
} |
java | @Override
synchronized public void write(final byte data[], final int off,
final int len) throws IOException {
// TODO: Ideally we'd make sure to fill up each message as much as
// we can, but this will work for now!
final byte[] encoded = CommonUtils.encode(this.key, data, off, len);
os.write(encoded);
} |
python | def get_time_remaining_estimate(self):
"""
Looks through all power sources and returns total time remaining estimate
or TIME_REMAINING_UNLIMITED if ac power supply is online.
"""
all_energy_now = []
all_power_now = []
try:
type = self.power_source_type()
if type == common.POWER_TYPE_AC:
if self.is_ac_online(supply_path):
return common.TIME_REMAINING_UNLIMITED
elif type == common.POWER_TYPE_BATTERY:
if self.is_battery_present() and self.is_battery_discharging():
energy_full, energy_now, power_now = self.get_battery_state()
all_energy_now.append(energy_now)
all_power_now.append(power_now)
else:
warnings.warn("UPS is not supported.")
except (RuntimeError, IOError) as e:
warnings.warn("Unable to read system power information!", category=RuntimeWarning)
if len(all_energy_now) > 0:
try:
return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])
except ZeroDivisionError as e:
warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning)
return common.TIME_REMAINING_UNKNOWN
else:
return common.TIME_REMAINING_UNKNOWN |
python | def set_color(
fg=Color.normal,
bg=Color.normal,
fg_dark=False,
bg_dark=False,
underlined=False,
):
"""Set the console color.
>>> set_color(Color.red, Color.blue)
>>> set_color('red', 'blue')
>>> set_color() # returns back to normal
"""
_set_color(fg, bg, fg_dark, bg_dark, underlined) |
python | def work(self):
"""
A list of :class:`Employment` instances describing the user's work history.
Each structure has attributes ``employer``, ``position``, ``started_at`` and ``ended_at``.
``employer`` and ``position`` reference ``Page`` instances, while ``started_at`` and ``ended_at``
are datetime objects.
"""
employments = []
for work in self.cache['work']:
employment = Employment(
employer = work.get('employer'),
position = work.get('position'),
started_at = work.get('start_date'),
ended_at = work.get('end_date')
)
employments.append(employment)
return employments |
python | def get_flash(self, format_ = "nl"):
"""
return a string representations of the flash
"""
flash = [self.flash.read(i) for i in range(self.flash.size)]
return self._format_mem(flash, format_) |
java | public JvmOperation getJvmOperation(IMethod method, XtendTypeDeclaration context)
throws JavaModelException {
if (!method.isConstructor() && !method.isLambdaMethod() && !method.isMainMethod()) {
final JvmType type = this.typeReferences.findDeclaredType(
method.getDeclaringType().getFullyQualifiedName(),
context);
return getJvmOperation(method, type);
}
return null;
} |
java | public static ProgressLayout wrap(final View targetView){
if(targetView==null){
throw new IllegalArgumentException();
}
final ProgressLayout progressLayout = new ProgressLayout(targetView.getContext());
progressLayout.attachTo(targetView);
return progressLayout;
} |
python | def first(self):
"""
Return the first result of this Query or None if the result
doesn't contain any row.
"""
results = self.rpc_model.search_read(
self.domain, None, 1, self._order_by, self.fields,
context=self.context
)
return results and results[0] or None |
java | public List<T> apply(List<T> selectedCandidates, Random rng)
{
return new ArrayList<T>(selectedCandidates);
} |
java | public ProviderGroup add(ProviderInfo providerInfo) {
if (providerInfo == null) {
return this;
}
ConcurrentHashSet<ProviderInfo> tmp = new ConcurrentHashSet<ProviderInfo>(providerInfos);
tmp.add(providerInfo); // 排重
this.providerInfos = new ArrayList<ProviderInfo>(tmp);
return this;
} |
python | def replace_template(self, template_content, team_context, template_id):
"""ReplaceTemplate.
[Preview API] Replace template contents
:param :class:`<WorkItemTemplate> <azure.devops.v5_1.work_item_tracking.models.WorkItemTemplate>` template_content: Template contents to replace with
:param :class:`<TeamContext> <azure.devops.v5_1.work_item_tracking.models.TeamContext>` team_context: The team context for the operation
:param str template_id: Template id
:rtype: :class:`<WorkItemTemplate> <azure.devops.v5_1.work-item-tracking.models.WorkItemTemplate>`
"""
project = None
team = None
if team_context is not None:
if team_context.project_id:
project = team_context.project_id
else:
project = team_context.project
if team_context.team_id:
team = team_context.team_id
else:
team = team_context.team
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'string')
if team is not None:
route_values['team'] = self._serialize.url('team', team, 'string')
if template_id is not None:
route_values['templateId'] = self._serialize.url('template_id', template_id, 'str')
content = self._serialize.body(template_content, 'WorkItemTemplate')
response = self._send(http_method='PUT',
location_id='fb10264a-8836-48a0-8033-1b0ccd2748d5',
version='5.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('WorkItemTemplate', response) |
java | public ApiSuccessResponse stopMonitoring(StopMonitoringData stopMonitoringData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = stopMonitoringWithHttpInfo(stopMonitoringData);
return resp.getData();
} |
java | public void info(Object message) {
if (repository.isDisabled(Level.INFO_INT))
return;
if (Level.INFO.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.INFO, message, null);
} |
python | def _get_reporoot():
"""Returns the absolute path to the repo root directory on the current
system.
"""
from os import path
import acorn
medpath = path.abspath(acorn.__file__)
return path.dirname(path.dirname(medpath)) |
java | public void onConfigurationChanged() {
final Collection<PropertyWidget<?>> widgets = getWidgets();
if (logger.isDebugEnabled()) {
final StringBuilder sb = new StringBuilder();
sb.append("id=");
sb.append(System.identityHashCode(this));
sb.append(" - onConfigurationChanged() - notifying widgets:");
sb.append(widgets.size());
for (final PropertyWidget<?> widget : widgets) {
final String propertyName = widget.getPropertyDescriptor().getName();
final String propertyWidgetClassName = widget.getClass().getSimpleName();
sb.append("\n - ");
sb.append(propertyName);
sb.append(": ");
sb.append(propertyWidgetClassName);
}
logger.debug(sb.toString());
}
for (final PropertyWidget<?> widget : widgets) {
@SuppressWarnings("unchecked") final PropertyWidget<Object> objectWidget = (PropertyWidget<Object>) widget;
final ConfiguredPropertyDescriptor propertyDescriptor = objectWidget.getPropertyDescriptor();
final Object value = _componentBuilder.getConfiguredProperty(propertyDescriptor);
objectWidget.onValueTouched(value);
}
} |
java | protected <T, A> void handleRequest(final Channel channel, final DataInput message, final ManagementProtocolHeader header, ActiveRequest<T, A> activeRequest) {
handleMessage(channel, message, header, activeRequest.context, activeRequest.handler);
} |
java | public static String loadString(String file) throws IOException {
StringBuilder sb = new StringBuilder();
UnicodeReader reader = new UnicodeReader(new FileInputStream(file), "utf8");
int n;
char[] cs = new char[256];
while ((n = reader.read(cs)) != -1) {
sb.append(Arrays.copyOfRange(cs, 0, n));
}
return sb.toString();
} |
java | public Object invoke(MethodInvocation invocation) throws Throwable {
ProxyMethodInvocation pmi = (ProxyMethodInvocation) invocation;
TargetMetaRequest targetMetaRequest = targetMetaRequestsHolder.getTargetMetaRequest();
TargetMetaDef targetMetaDef = targetMetaRequest.getTargetMetaDef();
if (targetMetaDef.isEJB())
return invocation.proceed();
if (!isStateful(targetMetaDef)) {
// Debug.logVerbose("[JdonFramework] target service is not Stateful: "
// + targetMetaDef.getClassName() +
// " StatefulInterceptor unactiive", module);
return invocation.proceed();
}
Debug.logVerbose("[JdonFramework] enter StatefulInterceptor", module);
Object result = null;
try {
ComponentVisitor cm = targetMetaRequest.getComponentVisitor();
targetMetaRequest.setVisitableName(ComponentKeys.TARGETSERVICE_FACTORY);
Debug.logVerbose(ComponentKeys.TARGETSERVICE_FACTORY + " in action (Stateful)", module);
Object targetObjRef = cm.visit();
pmi.setThis(targetObjRef);
result = invocation.proceed();
} catch (Exception ex) {
Debug.logError("[JdonFramework]StatefulInterceptor error: " + ex, module);
}
return result;
} |
python | def islice_extended(iterable, *args):
"""An extension of :func:`itertools.islice` that supports negative values
for *stop*, *start*, and *step*.
>>> iterable = iter('abcdefgh')
>>> list(islice_extended(iterable, -4, -1))
['e', 'f', 'g']
Slices with negative values require some caching of *iterable*, but this
function takes care to minimize the amount of memory required.
For example, you can use a negative step with an infinite iterator:
>>> from itertools import count
>>> list(islice_extended(count(), 110, 99, -2))
[110, 108, 106, 104, 102, 100]
"""
s = slice(*args)
start = s.start
stop = s.stop
if s.step == 0:
raise ValueError('step argument must be a non-zero integer or None.')
step = s.step or 1
it = iter(iterable)
if step > 0:
start = 0 if (start is None) else start
if (start < 0):
# Consume all but the last -start items
cache = deque(enumerate(it, 1), maxlen=-start)
len_iter = cache[-1][0] if cache else 0
# Adjust start to be positive
i = max(len_iter + start, 0)
# Adjust stop to be positive
if stop is None:
j = len_iter
elif stop >= 0:
j = min(stop, len_iter)
else:
j = max(len_iter + stop, 0)
# Slice the cache
n = j - i
if n <= 0:
return
for index, item in islice(cache, 0, n, step):
yield item
elif (stop is not None) and (stop < 0):
# Advance to the start position
next(islice(it, start, start), None)
# When stop is negative, we have to carry -stop items while
# iterating
cache = deque(islice(it, -stop), maxlen=-stop)
for index, item in enumerate(it):
cached_item = cache.popleft()
if index % step == 0:
yield cached_item
cache.append(item)
else:
# When both start and stop are positive we have the normal case
yield from islice(it, start, stop, step)
else:
start = -1 if (start is None) else start
if (stop is not None) and (stop < 0):
# Consume all but the last items
n = -stop - 1
cache = deque(enumerate(it, 1), maxlen=n)
len_iter = cache[-1][0] if cache else 0
# If start and stop are both negative they are comparable and
# we can just slice. Otherwise we can adjust start to be negative
# and then slice.
if start < 0:
i, j = start, stop
else:
i, j = min(start - len_iter, -1), None
for index, item in list(cache)[i:j:step]:
yield item
else:
# Advance to the stop position
if stop is not None:
m = stop + 1
next(islice(it, m, m), None)
# stop is positive, so if start is negative they are not comparable
# and we need the rest of the items.
if start < 0:
i = start
n = None
# stop is None and start is positive, so we just need items up to
# the start index.
elif stop is None:
i = None
n = start + 1
# Both stop and start are positive, so they are comparable.
else:
i = None
n = start - stop
if n <= 0:
return
cache = list(islice(it, n))
yield from cache[i::step] |
python | def _generate_examples(self, archive):
"""Yields examples."""
prefix_len = len("SUN397")
with tf.Graph().as_default():
with utils.nogpu_session() as sess:
for filepath, fobj in archive:
if (filepath.endswith(".jpg") and
filepath not in _SUN397_IGNORE_IMAGES):
# Note: all files in the tar.gz are in SUN397/...
filename = filepath[prefix_len:]
# Example:
# From filename: /c/car_interior/backseat/sun_aenygxwhhmjtisnf.jpg
# To class: /c/car_interior/backseat
label = "/".join(filename.split("/")[:-1])
image = _process_image_file(fobj, sess, filepath)
yield {
"file_name": filename,
"image": image,
"label": label,
} |
python | def initialize_request(self, request, *args, **kargs):
"""
Override DRF initialize_request() method to swap request.GET
(which is aliased by request.query_params) with a mutable instance
of QueryParams, and to convert request MergeDict to a subclass of dict
for consistency (MergeDict is not a subclass of dict)
"""
def handle_encodings(request):
"""
WSGIRequest does not support Unicode values in the query string.
WSGIRequest handling has a history of drifting behavior between
combinations of Python versions, Django versions and DRF versions.
Django changed its QUERY_STRING handling here:
https://goo.gl/WThXo6. DRF 3.4.7 changed its behavior here:
https://goo.gl/0ojIIO.
"""
try:
return QueryParams(request.GET)
except UnicodeEncodeError:
pass
s = request.environ.get('QUERY_STRING', '')
try:
s = s.encode('utf-8')
except UnicodeDecodeError:
pass
return QueryParams(s)
request.GET = handle_encodings(request)
request = super(WithDynamicViewSetMixin, self).initialize_request(
request, *args, **kargs
)
try:
# Django<1.9, DRF<3.2
# MergeDict doesn't have the same API as dict.
# Django has deprecated MergeDict and DRF is moving away from
# using it - thus, were comfortable replacing it with a QueryDict
# This will allow the data property to have normal dict methods.
from django.utils.datastructures import MergeDict
if isinstance(request._full_data, MergeDict):
data_as_dict = request.data.dicts[0]
for d in request.data.dicts[1:]:
data_as_dict.update(d)
request._full_data = data_as_dict
except:
pass
return request |
python | def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Group object for each one, initializing them
one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a MambuGroup just
created.
.. todo:: pass a valid (perhaps default) urlfunc, and its
corresponding id to entid to each MambuGroup, telling
MambuStruct not to connect() by default. It's desirable to
connect at any other further moment to refresh some element in
the list.
"""
for n,c in enumerate(self.attrs):
# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!
try:
params = self.params
except AttributeError as aerr:
params = {}
kwargs.update(params)
try:
group = self.mambugroupclass(urlfunc=None, entid=None, *args, **kwargs)
except AttributeError as ae:
self.mambugroupclass = MambuGroup
group = self.mambugroupclass(urlfunc=None, entid=None, *args, **kwargs)
group.init(c, *args, **kwargs)
self.attrs[n] = group |
python | def tracebacks(score_matrix, traceback_matrix, idx):
"""Calculate the tracebacks for `traceback_matrix` starting at index `idx`.
Returns: An iterable of tracebacks where each traceback is sequence of
(index, direction) tuples. Each `index` is an index into
`traceback_matrix`. `direction` indicates the direction into which the
traceback "entered" the index.
"""
return filter(lambda tb: tb != (),
_tracebacks(score_matrix,
traceback_matrix,
idx)) |
java | private void handleAsyncComplete(boolean forceQueue, TCPReadCompletedCallback inCallback) {
boolean fireHere = true;
if (forceQueue) {
// Complete must be returned on a separate thread.
// Reuse queuedWork object (performance), but reset the error parameters.
queuedWork.setCompleteParameters(getConnLink().getVirtualConnection(), this, inCallback);
EventEngine events = SSLChannelProvider.getEventService();
if (null == events) {
Exception e = new Exception("missing event service");
FFDCFilter.processException(e, getClass().getName(), "471", this);
// fall-thru below and use callback here regardless
} else {
// fire an event to continue this queued work
Event event = events.createEvent(SSLEventHandler.TOPIC_QUEUED_WORK);
event.setProperty(SSLEventHandler.KEY_RUNNABLE, this.queuedWork);
events.postEvent(event);
fireHere = false;
}
}
if (fireHere) {
// Call the callback right here.
inCallback.complete(getConnLink().getVirtualConnection(), this);
}
} |
java | public static int getRelativeX(int x, Element target) {
return (x - target.getAbsoluteLeft()) + /* target.getScrollLeft() + */target.getOwnerDocument().getScrollLeft();
} |
java | public void initialize(Context context, String appGUID, String pushClientSecret,MFPPushNotificationOptions options) {
try {
if (MFPPushUtils.validateString(pushClientSecret) && MFPPushUtils.validateString(appGUID)) {
// Get the applicationId and backend route from core
clientSecret = pushClientSecret;
applicationId = appGUID;
appContext = context.getApplicationContext();
isInitialized = true;
validateAndroidContext();
//Storing the messages url and the client secret.
//This is because when the app is not running and notification is dismissed/cleared,
//there wont be applicationId and clientSecret details available to
//MFPPushNotificationDismissHandler.
SharedPreferences sharedPreferences = appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
MFPPushUtils.storeContentInSharedPreferences(sharedPreferences, MFPPush.PREFS_MESSAGES_URL, buildMessagesURL());
MFPPushUtils.storeContentInSharedPreferences(sharedPreferences, MFPPush.PREFS_MESSAGES_URL_CLIENT_SECRET, clientSecret);
MFPPushUtils.storeContentInSharedPreferences(sharedPreferences, PREFS_BMS_REGION, BMSClient.getInstance().getBluemixRegionSuffix());
if (options != null){
setNotificationOptions(context,options);
this.regId = options.getDeviceid();
}
} else {
logger.error("MFPPush:initialize() - An error occured while initializing MFPPush service. Add a valid ClientSecret and push service instance ID Value");
throw new MFPPushException("MFPPush:initialize() - An error occured while initializing MFPPush service. Add a valid ClientSecret and push service instance ID Value", INITIALISATION_ERROR);
}
} catch (Exception e) {
logger.error("MFPPush:initialize() - An error occured while initializing MFPPush service.");
throw new RuntimeException(e);
}
} |
java | public void addTrace(final S state, final Word<I> input, final Word<O> output) {
this.addTrace(this.nodeToObservationMap.get(state), input, output);
} |
python | def __get_subscript(self, name, ctx=None):
"""
Returns `<data_var>["<name>"]`
"""
assert isinstance(name, string_types), name
return ast.Subscript(
value=ast.Name(id=self.data_var, ctx=ast.Load()),
slice=ast.Index(value=ast.Str(s=name)),
ctx=ctx) |
java | public static Record
newRecord(Name name, int type, int dclass, long ttl, int length, byte [] data) {
if (!name.isAbsolute())
throw new RelativeNameException(name);
Type.check(type);
DClass.check(dclass);
TTL.check(ttl);
DNSInput in;
if (data != null)
in = new DNSInput(data);
else
in = null;
try {
return newRecord(name, type, dclass, ttl, length, in);
}
catch (IOException e) {
return null;
}
} |
java | public String getTypeGenericExtends(int typeParamIndex, String[] typeParamNames) {
String genericClause = typeGenericExtends[typeParamIndex];
genericClause = genericClause.replace("<" + typeGenericName[typeParamIndex] + ">", "<" + typeParamNames[typeParamIndex] + ">");
for (int i = 0; i < typeGenericName.length; i++) {
genericClause = genericClause.replace("<" + typeGenericName[i] + ">", "<" + typeParamNames[i] + ">");
genericClause = genericClause.replace(" extends " + typeGenericName[i] + ">", " extends " + typeParamNames[i] + ">");
genericClause = genericClause.replace(" super " + typeGenericName[i] + ">", " super " + typeParamNames[i] + ">");
}
return genericClause;
} |
python | def _update_port_status_cache(self, device, device_bound=True):
"""Update the ports status cache."""
with self._cache_lock:
if device_bound:
self._bound_ports.add(device)
self._unbound_ports.discard(device)
else:
self._bound_ports.discard(device)
self._unbound_ports.add(device) |
python | def grad(self, x):
r"""Compute the gradient of a signal defined on the vertices.
The gradient :math:`y` of a signal :math:`x` is defined as
.. math:: y = \nabla_\mathcal{G} x = D^\top x,
where :math:`D` is the differential operator :attr:`D`.
The value of the gradient on the edge :math:`e_k = (v_i, v_j)` from
:math:`v_i` to :math:`v_j` with weight :math:`W[i, j]` is
.. math:: y[k] = D[i, k] x[i] + D[j, k] x[j]
= \sqrt{\frac{W[i, j]}{2}} (x[j] - x[i])
for the combinatorial Laplacian, and
.. math:: y[k] = \sqrt{\frac{W[i, j]}{2}} \left(
\frac{x[j]}{\sqrt{d[j]}} - \frac{x[i]}{\sqrt{d[i]}}
\right)
for the normalized Laplacian.
For undirected graphs, only half the edges are kept and the
:math:`1/\sqrt{2}` factor disappears from the above equations. See
:meth:`compute_differential_operator` for details.
Parameters
----------
x : array_like
Signal of length :attr:`n_vertices` living on the vertices.
Returns
-------
y : ndarray
Gradient signal of length :attr:`n_edges` living on the edges.
See Also
--------
compute_differential_operator
div : compute the divergence of an edge signal
dirichlet_energy : compute the norm of the gradient
Examples
--------
Non-directed graph and combinatorial Laplacian:
>>> graph = graphs.Path(4, directed=False, lap_type='combinatorial')
>>> graph.compute_differential_operator()
>>> graph.grad([0, 2, 4, 2])
array([ 2., 2., -2.])
Directed graph and combinatorial Laplacian:
>>> graph = graphs.Path(4, directed=True, lap_type='combinatorial')
>>> graph.compute_differential_operator()
>>> graph.grad([0, 2, 4, 2])
array([ 1.41421356, 1.41421356, -1.41421356])
Non-directed graph and normalized Laplacian:
>>> graph = graphs.Path(4, directed=False, lap_type='normalized')
>>> graph.compute_differential_operator()
>>> graph.grad([0, 2, 4, 2])
array([ 1.41421356, 1.41421356, -0.82842712])
Directed graph and normalized Laplacian:
>>> graph = graphs.Path(4, directed=True, lap_type='normalized')
>>> graph.compute_differential_operator()
>>> graph.grad([0, 2, 4, 2])
array([ 1.41421356, 1.41421356, -0.82842712])
"""
x = self._check_signal(x)
return self.D.T.dot(x) |
java | @Override
public DeregisterJobDefinitionResult deregisterJobDefinition(DeregisterJobDefinitionRequest request) {
request = beforeClientExecution(request);
return executeDeregisterJobDefinition(request);
} |
python | def build_base_parameters(request):
"""Build the list of parameters to forward from the post and get parameters"""
getParameters = {}
postParameters = {}
files = {}
# Copy GET parameters, excluding ebuio_*
for v in request.GET:
if v[:6] != 'ebuio_':
val = request.GET.getlist(v)
if len(val) == 1:
getParameters[v] = val[0]
else:
getParameters[v] = val
# If using post, copy post parameters and files. Excluding ebuio_*
if request.method == 'POST':
for v in request.POST:
if v[:6] != 'ebuio_':
val = request.POST.getlist(v)
if len(val) == 1:
postParameters[v] = val[0]
else:
postParameters[v] = val
for v in request.FILES:
if v[:6] != 'ebuio_':
files[v] = request.FILES[v] # .chunks()
return (getParameters, postParameters, files) |
python | def index(self, item, minindex=0, maxindex=None):
"""Provide an index of first occurence of item in the list. (or raise
a ValueError if item not present)
If item is not a string, will raise a TypeError.
minindex and maxindex are also optional arguments
s.index(x[, i[, j]]) return smallest k such that s[k] == x and i <= k < j
"""
if maxindex is None:
maxindex = len(self)
minindex = max(0, minindex) - 1
maxindex = min(len(self), maxindex)
if not isinstance(item, str):
raise TypeError(
'Members of this object must be strings. '
'You supplied \"%s\"' % type(item))
index = minindex
while index < maxindex:
index += 1
if item.lower() == self[index].lower():
return index
raise ValueError(': list.index(x): x not in list') |
java | public static ByteArrayEntity createExceptionByteArray(String name, byte[] byteArray, ResourceType type) {
ByteArrayEntity result = null;
if (byteArray != null) {
result = new ByteArrayEntity(name, byteArray, type);
Context.getCommandContext()
.getByteArrayManager()
.insertByteArray(result);
}
return result;
} |
java | private HashMap readFault()
throws IOException
{
HashMap map = new HashMap();
int code = read();
for (; code > 0 && code != 'z'; code = read()) {
_peek = code;
Object key = readObject();
Object value = readObject();
if (key != null && value != null)
map.put(key, value);
}
if (code != 'z')
throw expect("fault", code);
return map;
} |
python | def ver_dec_content(parts, sign_key=None, enc_key=None, sign_alg='SHA256'):
"""
Verifies the value of a cookie
:param parts: The parts of the payload
:param sign_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance
:param enc_key: A :py:class:`cryptojwt.jwk.hmac.SYMKey` instance
:param sign_alg: Which signing algorithm to was used
:return: A tuple with basic information and a timestamp
"""
if parts is None:
return None
elif len(parts) == 3:
# verify the cookie signature
timestamp, load, b64_mac = parts
mac = base64.b64decode(b64_mac)
verifier = HMACSigner(algorithm=sign_alg)
if verifier.verify(load.encode('utf-8') + timestamp.encode('utf-8'),
mac, sign_key.key):
return load, timestamp
else:
raise VerificationError()
elif len(parts) == 4:
b_timestamp = parts[0]
iv = base64.b64decode(parts[1])
ciphertext = base64.b64decode(parts[2])
tag = base64.b64decode(parts[3])
decrypter = AES_GCMEncrypter(key=enc_key.key)
msg = decrypter.decrypt(ciphertext, iv, tag=tag)
p = lv_unpack(msg.decode('utf-8'))
load = p[0]
timestamp = p[1]
if len(p) == 3:
verifier = HMACSigner(algorithm=sign_alg)
if verifier.verify(load.encode('utf-8') + timestamp.encode('utf-8'),
base64.b64decode(p[2]), sign_key.key):
return load, timestamp
else:
return load, timestamp
return None |
python | def get_elem_type(elem):
""" Get elem type of soup selection
:param elem: a soup element
"""
elem_type = None
if isinstance(elem, list):
if elem[0].get("type") == "radio":
elem_type = "radio"
else:
raise ValueError(u"Unknown element type: {}".format(elem))
elif elem.name == "select":
elem_type = "select"
elif elem.name == "input":
elem_type = elem.get("type")
else:
raise ValueError(u"Unknown element type: {}".format(elem))
# To be removed
assert elem_type is not None
return elem_type |
python | def save_as_png(self, filename, width=300, height=250, render_time=1):
"""Open saved html file in an virtual browser and save a screen shot to PNG format."""
self.driver.set_window_size(width, height)
self.driver.get('file://{path}/{filename}'.format(
path=os.getcwd(), filename=filename + ".html"))
time.sleep(render_time)
self.driver.save_screenshot(filename + ".png") |
python | def truthtable2expr(tt, conj=False):
"""Convert a truth table into an expression."""
if conj:
outer, inner = (And, Or)
nums = tt.pcdata.iter_zeros()
else:
outer, inner = (Or, And)
nums = tt.pcdata.iter_ones()
inputs = [exprvar(v.names, v.indices) for v in tt.inputs]
terms = [boolfunc.num2term(num, inputs, conj) for num in nums]
return outer(*[inner(*term) for term in terms]) |
java | @Override
public void writePage(int pageID, P page) {
try {
countWrite();
byte[] array = pageToByteArray(page);
long offset = ((long) (header.getReservedPages() + pageID)) * (long) pageSize;
assert offset >= 0 : header.getReservedPages() + " " + pageID + " " + pageSize + " " + offset;
file.seek(offset);
file.write(array);
page.setDirty(false);
}
catch(IOException e) {
throw new RuntimeException("Error writing to page file.", e);
}
} |
java | @Override
public void saveDocument(IProject project, File projectRoot, String name, boolean modelOnly)
throws IOException
{
String document = readFile("latex/document.tex");
String documentFileName = name;// + ".tex";
File latexRoot = makeOutputFolder(project);
StringBuilder sb = new StringBuilder();
String title = // "Coverage Report: " +
projectRoot.getName().replace('\\', '/').substring(0, projectRoot.getName().length());
for (String path : includes)
{
String includeName = path;
includeName = includeName.substring(0, includeName.lastIndexOf('.'));
includeName = includeName.substring(0, includeName.lastIndexOf('.'));
String tmp = includeName.replace('\\', '/');
includeName = tmp.substring(tmp.lastIndexOf('/') + 1);
if(modelOnly){
sb.append("\n" + "\\section{" + latexQuote(includeName) + "}");
}
if (path.contains(latexRoot.getAbsolutePath()))
{
path = path.substring(latexRoot.getAbsolutePath().length());
// sb.append("\n" + "\\input{" + (".." + path).replace('\\',
// '/')
// + "}");
sb.append("\n" + "\\input{"
+ path.replace('\\', '/').substring(1, path.length())
+ "}");
} else
{
sb.append("\n" + "\\input{" + path.replace('\\', '/') + "}");
}
}
document = document.replace(TITLE, latexQuote(title)).replace(PROJECT_INCLUDE_MODEL_FILES, sb.toString());
writeFile(outputFolder, documentFileName, document);
} |
java | public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars cachedEnvironment = this.cachedEnvironment;
if (cachedEnvironment != null) {
return new EnvVars(cachedEnvironment);
}
cachedEnvironment = EnvVars.getRemote(getChannel());
this.cachedEnvironment = cachedEnvironment;
return new EnvVars(cachedEnvironment);
} |
python | def path(self, filename):
'''
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
to save to.
:raises OperationNotSupported: when the backenddoesn't support direct file access
'''
if not self.backend.root:
raise OperationNotSupported(
'Direct file access is not supported by ' +
self.backend.__class__.__name__
)
return os.path.join(self.backend.root, filename) |
python | def create_index(self, cls_or_collection,
params=None, fields=None, ephemeral=False, unique=False):
"""Create new index on the given collection/class with given parameters.
:param cls_or_collection:
The name of the collection or the class for which to create an
index
:param params: The parameters of the index
:param ephemeral: Whether to create a persistent or an ephemeral index
:param unique: Whether the indexed field(s) must be unique
`params` expects either a dictionary of parameters or a string value.
In the latter case, it will interpret the string as the name of the key
for which an index is to be created.
If `ephemeral = True`, the index will be created only in memory and
will not be written to disk when :py:meth:`.commit` is called. This is
useful for optimizing query performance.
..notice::
By default, BlitzDB will create ephemeral indexes for all keys over
which you perform queries, so after you've run a query on a given
key for the first time, the second run will usually be much faster.
**Specifying keys**
Keys can be specified just like in MongoDB, using a dot ('.') to
specify nested keys.
.. code-block:: python
actor = Actor({'name' : 'Charlie Chaplin',
'foo' : {'value' : 'bar'}})
If you want to create an index on `actor['foo']['value']` , you can
just say
.. code-block:: python
backend.create_index(Actor,'foo.value')
.. warning::
Transcendental indexes (i.e. indexes transcending the boundaries of
referenced objects) are currently not supported by Blitz, which
means you can't create an index on an attribute value of a document
that is embedded in another document.
"""
if params:
return self.create_indexes(cls_or_collection, [params],
ephemeral=ephemeral, unique=unique)
elif fields:
params = []
if len(fields.items()) > 1:
raise ValueError("File backend currently does not support multi-key indexes, sorry :/")
return self.create_indexes(cls_or_collection, [{'key': list(fields.keys())[0]}],
ephemeral=ephemeral, unique=unique)
else:
raise AttributeError('You must either specify params or fields!') |
python | def receiveManagementEvent(self, action, varBind, **context):
"""Apply mass operation on extending table's row.
SNMP SMI provides a way to extend already existing SMI table with
another table. Whenever a mass operation on parent table's column
is performed (e.g. row creation or destruction), this operation
has to be propagated over all the extending tables.
This method gets invoked on the extending :py:class:`MibTableRow`
object whenever row modification is performed on the parent table.
Parameters
----------
action: :py:class:`str` any of :py:class:`MibInstrumController`'s states
to apply on extending table's row.
varBind: :py:class:`~pysnmp.smi.rfc1902.ObjectType` object representing
new :py:class:`RowStatus` Managed Object Instance value being set
on parent table row
Other Parameters
----------------
\*\*context:
Query parameters:
* `cbFun` (callable) - user-supplied callable that is invoked once
the requested operation has been applied on all columns of the
extending table or an error occurs
Notes
-----
The callback functions (e.g. `cbFun`) expects two parameters: `varBind`
and `**context`.
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
baseIndices, val = varBind
# The default implementation supports one-to-one rows dependency
instId = ()
# Resolve indices intersection
for impliedFlag, modName, symName in self._indexNames:
mibObj, = mibBuilder.importSymbols(modName, symName)
parentIndices = []
for name, syntax in baseIndices:
if name == mibObj.name:
instId += self.valueToOid(syntax, impliedFlag, parentIndices)
parentIndices.append(syntax)
if instId:
debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context) |
java | public void putCustomQueryParameter(String name, String value) {
if (customQueryParameters == null) {
customQueryParameters = new HashMap<String, List<String>>();
}
List<String> paramList = customQueryParameters.get(name);
if (paramList == null) {
paramList = new LinkedList<String>();
customQueryParameters.put(name, paramList);
}
paramList.add(value);
} |
java | public ArrayList<String> directories_availableZipCodes_GET(OvhNumberCountryEnum country, String number) throws IOException {
String qPath = "/telephony/directories/availableZipCodes";
StringBuilder sb = path(qPath);
query(sb, "country", country);
query(sb, "number", number);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} |
python | def get_speakers(self, **kwargs):
"""
Gets the info of BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
GET /vtep/speakers
======= ================
Example::
$ curl -X GET http://localhost:8080/vtep/speakers |
python -m json.tool
::
{
"172.17.0.1": {
"EvpnSpeaker": {
"as_number": 65000,
"dpid": 1,
"neighbors": {
"172.17.0.2": {
"EvpnNeighbor": {
"address": "172.17.0.2",
"remote_as": 65000,
"state": "up"
}
}
},
"router_id": "172.17.0.1"
}
}
}
"""
try:
body = self.vtep_app.get_speaker()
except BGPSpeakerNotFound as e:
return e.to_response(status=404)
return Response(content_type='application/json',
body=json.dumps(body)) |
python | def listPrimaryDsTypes(self, primary_ds_type="", dataset=""):
"""
API to list primary dataset types
:param primary_ds_type: List that primary dataset type (Optional)
:type primary_ds_type: str
:param dataset: List the primary dataset type for that dataset (Optional)
:type dataset: str
:returns: List of dictionaries containing the following keys (primary_ds_type_id, data_type)
:rtype: list of dicts
"""
if primary_ds_type:
primary_ds_type = primary_ds_type.replace("*", "%")
if dataset:
dataset = dataset.replace("*", "%")
try:
return self.dbsPrimaryDataset.listPrimaryDSTypes(primary_ds_type, dataset)
except dbsException as de:
dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.message)
except Exception as ex:
sError = "DBSReaderModel/listPrimaryDsTypes. %s\n. Exception trace: \n %s" \
% (ex, traceback.format_exc())
dbsExceptionHandler('dbsException-server-error', dbsExceptionCode['dbsException-server-error'], self.logger.exception, sError) |
java | public static void openDialog(
String title,
String hookUri,
List<String> uploadedFiles,
final CloseHandler<PopupPanel> closeHandler) {
if (hookUri.startsWith("#")) {
List<CmsUUID> resourceIds = new ArrayList<CmsUUID>();
if (uploadedFiles != null) {
for (String id : uploadedFiles) {
resourceIds.add(new CmsUUID(id));
}
}
CmsEmbeddedDialogHandler handler = new CmsEmbeddedDialogHandler(new I_CmsActionHandler() {
public void leavePage(String targetUri) {
// TODO Auto-generated method stub
}
public void onSiteOrProjectChange(String sitePath, String serverLink) {
// TODO Auto-generated method stub
}
public void refreshResource(CmsUUID structureId) {
closeHandler.onClose(null);
}
});
String dialogId = hookUri.substring(1);
handler.openDialog(dialogId, CmsGwtConstants.CONTEXT_TYPE_FILE_TABLE, resourceIds);
} else {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(I_CmsUploadConstants.PARAM_RESOURCES, Joiner.on(",").join(uploadedFiles));
CmsPopup popup = CmsFrameDialog.showFrameDialog(
title,
CmsCoreProvider.get().link(hookUri),
parameters,
closeHandler);
popup.setHeight(DIALOG_HEIGHT);
popup.setWidth(CmsPopup.DEFAULT_WIDTH);
popup.center();
}
} |
python | def corr(self, col1, col2, method=None):
"""
Calculates the correlation of two columns of a DataFrame as a double value.
Currently only supports the Pearson Correlation Coefficient.
:func:`DataFrame.corr` and :func:`DataFrameStatFunctions.corr` are aliases of each other.
:param col1: The name of the first column
:param col2: The name of the second column
:param method: The correlation method. Currently only supports "pearson"
"""
if not isinstance(col1, basestring):
raise ValueError("col1 should be a string.")
if not isinstance(col2, basestring):
raise ValueError("col2 should be a string.")
if not method:
method = "pearson"
if not method == "pearson":
raise ValueError("Currently only the calculation of the Pearson Correlation " +
"coefficient is supported.")
return self._jdf.stat().corr(col1, col2, method) |
python | def _type_insert(self, handle, key, value):
'''
Insert the value into the series.
'''
if value!=0:
if isinstance(value,float):
handle.incrbyfloat(key, value)
else:
handle.incr(key,value) |
python | def flush(self):
"""Flush pool contents."""
# Write data to in-memory buffer first.
buf = cStringIO.StringIO()
with records.RecordsWriter(buf) as w:
for record in self._buffer:
w.write(record)
w._pad_block()
str_buf = buf.getvalue()
buf.close()
if not self._exclusive and len(str_buf) > _FILE_POOL_MAX_SIZE:
# Shouldn't really happen because of flush size.
raise errors.Error(
"Buffer too big. Can't write more than %s bytes in one request: "
"risk of writes interleaving. Got: %s" %
(_FILE_POOL_MAX_SIZE, len(str_buf)))
# Write data to file.
start_time = time.time()
self._write(str_buf)
if self._ctx:
operation.counters.Increment(
COUNTER_IO_WRITE_BYTES, len(str_buf))(self._ctx)
operation.counters.Increment(
COUNTER_IO_WRITE_MSEC,
int((time.time() - start_time) * 1000))(self._ctx)
# reset buffer
self._buffer = []
self._size = 0
gc.collect() |
java | protected void generateNumericConstants(IStyleAppendable it) {
appendComment(it, "numerical constants"); //$NON-NLS-1$
appendMatch(it, "sarlNumber", "[0-9][0-9]*\\.[0-9]\\+([eE][0-9]\\+)\\?[fFdD]\\?"); //$NON-NLS-1$ //$NON-NLS-2$
appendMatch(it, "sarlNumber", "0[xX][0-9a-fA-F]\\+"); //$NON-NLS-1$ //$NON-NLS-2$
appendMatch(it, "sarlNumber", "[0-9]\\+[lL]\\?"); //$NON-NLS-1$ //$NON-NLS-2$
appendCluster(it, "sarlNumber"); //$NON-NLS-1$
hilight("sarlNumber", VimSyntaxGroup.CONSTANT); //$NON-NLS-1$
it.newLine();
} |
java | public void setVpcAttachments(java.util.Collection<VpcAttachment> vpcAttachments) {
if (vpcAttachments == null) {
this.vpcAttachments = null;
return;
}
this.vpcAttachments = new com.amazonaws.internal.SdkInternalList<VpcAttachment>(vpcAttachments);
} |
java | public boolean isSameOrSubTypeOf(ClassDescriptorDef type, String baseType, boolean checkActualClasses) throws ClassNotFoundException
{
if (type.getQualifiedName().equals(baseType.replace('$', '.')))
{
return true;
}
else if (type.getOriginalClass() != null)
{
return isSameOrSubTypeOf(type.getOriginalClass(), baseType, checkActualClasses);
}
else
{
return checkActualClasses ? isSameOrSubTypeOf(type.getName(), baseType) : false;
}
} |
java | public ByteBuffer getKey(int index) throws IOException {
if (index >= structure.keySizes.size()) {
throw new IOException("Index " + index + " is out of range.");
}
int length = structure.keySizes.get(index);
return ByteBuffer.wrap(key, structure.keyByteOffsets.get(index), length).asReadOnlyBuffer();
} |
java | public static IEntityGroup findGroup(String key) throws GroupsException {
LOGGER.trace("Invoking findGroup for key='{}'", key);
return instance().ifindGroup(key);
} |
java | protected Collection<Class<?>> discoverClasses(String... packageNames) {
log.debug("Discovering annotated controller in package(s) '{}'", Arrays.toString(packageNames));
Collection<Class<?>> classes = ClassUtil.getAnnotatedClasses(Path.class, packageNames);
return classes;
} |
java | public static FloatMatrix solvePositive(FloatMatrix A, FloatMatrix B) {
A.assertSquare();
FloatMatrix X = B.dup();
SimpleBlas.posv('U', A.dup(), X);
return X;
} |
java | @JmxOperation(description = "Retrieve operation status")
public String getStatus(int id) {
try {
return getOperationStatus(id).toString();
} catch(VoldemortException e) {
return "No operation with id " + id + " found";
}
} |
java | public DeviceSharingId deleteSharingForDevice(String deviceId, String shareId) throws ApiException {
ApiResponse<DeviceSharingId> resp = deleteSharingForDeviceWithHttpInfo(deviceId, shareId);
return resp.getData();
} |
python | def clear_validation(self, cert):
"""
Clears the record that a certificate has been validated
:param cert:
An ans1crypto.x509.Certificate object
"""
if cert.signature in self._validate_map:
del self._validate_map[cert.signature] |
java | public static IntSupplier topAlignedTo(IPositioned other, int offset)
{
checkNotNull(other);
return () -> {
return other.position().y() + offset;
};
} |
python | def plot_median_freq_evol(time_signal, signal, time_median_freq, median_freq, activations_begin,
activations_end, sample_rate, file_name=None):
"""
-----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Description
-----------
Function intended to generate a Bokeh figure with 2x1 format, where each muscular activation
period is identified through a colored box and the plot that shows the median frequency
evolution is also presented.
In the first cell is presented the EMG signal, highlighting each muscular activation.
The second cell has the same time scale as the first one (the two plots are synchronized), being
plotted the evolution time series of EMG median frequency.
Per muscular activation period is extracted a Median Power Frequency value (sample), so, our
window is a muscular activation period.
Median power frequency is a commonly used parameter for evaluating muscular fatigue.
It is widely accepted that this parameter decreases as fatigue sets in.
Applied in the Notebook "Fatigue Evaluation - Evolution of Median Power Frequency".
----------
Parameters
----------
time_signal : list
List with the time axis samples of EMG signal.
signal : list
List with EMG signal to present.
time_median_freq : list
List with the time axis samples of the median frequency evolution time-series.
median_freq : list
List with the Median Frequency samples.
activations_begin : list
List with the samples where each muscular activation period starts.
activations_end : list
List with the samples where each muscular activation period ends.
sample_rate : int
Sampling rate of acquisition.
file_name : str
Path containing the destination folder where the Bokeh figure will be stored.
"""
# Generation of the HTML file where the plot will be stored.
#file_name = _generate_bokeh_file(file_name)
list_figures_1 = plot([list(time_signal), list(time_median_freq)],
[list(signal), list(median_freq)],
title=["EMG Acquisition highlighting muscular activations",
"Median Frequency Evolution"], grid_plot=True,
grid_lines=2, grid_columns=1, open_signals_style=True,
x_axis_label="Time (s)",
yAxisLabel=["Raw Data", "Median Frequency (Hz)"],
x_range=[0, 125], get_fig_list=True, show_plot=False)
# Highlighting of each processing window
for activation in range(0, len(activations_begin)):
color = opensignals_color_pallet()
box_annotation = BoxAnnotation(left=activations_begin[activation] / sample_rate,
right=activations_end[activation] / sample_rate,
fill_color=color, fill_alpha=0.1)
box_annotation_copy = BoxAnnotation(left=activations_begin[activation] / sample_rate,
right=activations_end[activation] / sample_rate,
fill_color=color, fill_alpha=0.1)
list_figures_1[0].add_layout(box_annotation)
list_figures_1[1].add_layout(box_annotation_copy)
gridplot_1 = gridplot([[list_figures_1[0]], [list_figures_1[1]]],
**opensignals_kwargs("gridplot"))
show(gridplot_1) |
python | def is_noncontinuable(self):
"""
@see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx}
@rtype: bool
@return: C{True} if the exception is noncontinuable,
C{False} otherwise.
Attempting to continue a noncontinuable exception results in an
EXCEPTION_NONCONTINUABLE_EXCEPTION exception to be raised.
"""
return bool( self.raw.u.Exception.ExceptionRecord.ExceptionFlags & \
win32.EXCEPTION_NONCONTINUABLE ) |
python | def do_gate(self, gate: Gate):
"""
Perform a gate.
:return: ``self`` to support method chaining.
"""
unitary = lifted_gate(gate=gate, n_qubits=self.n_qubits)
self.wf = unitary.dot(self.wf)
return self |
python | def workflow_set_visibility(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/setVisibility API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Visibility#API-method%3A-%2Fclass-xxxx%2FsetVisibility
"""
return DXHTTPRequest('/%s/setVisibility' % object_id, input_params, always_retry=always_retry, **kwargs) |
java | public boolean isMethodAllowed(String method) {
return HttpMethod.isValidMethod(method) && (allowedMethods.isEmpty() || allowedMethods.contains(method));
} |
python | def nodeid(self, iv, quantifier=False):
"""
Return the nodeid of the predication selected by *iv*.
Args:
iv: the intrinsic variable of the predication to select
quantifier: if `True`, treat *iv* as a bound variable and
find its quantifier; otherwise the non-quantifier will
be returned
"""
return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None) |
java | public static String join(String joinChar, String... args) {
String next = ""; //$NON-NLS-1$
StringBuilder result = new StringBuilder(length(args) + (args.length - 1));
for (String arg : args) {
result.append(next);
result.append(arg);
next = joinChar;
}
return result.toString();
} |
python | def execute_with_scope(expr, scope, aggcontext=None, clients=None, **kwargs):
"""Execute an expression `expr`, with data provided in `scope`.
Parameters
----------
expr : ibis.expr.types.Expr
The expression to execute.
scope : collections.Mapping
A dictionary mapping :class:`~ibis.expr.operations.Node` subclass
instances to concrete data such as a pandas DataFrame.
aggcontext : Optional[ibis.pandas.aggcontext.AggregationContext]
Returns
-------
result : scalar, pd.Series, pd.DataFrame
"""
op = expr.op()
# Call pre_execute, to allow clients to intercept the expression before
# computing anything *and* before associating leaf nodes with data. This
# allows clients to provide their own data for each leaf.
if clients is None:
clients = list(find_backends(expr))
if aggcontext is None:
aggcontext = agg_ctx.Summarize()
pre_executed_scope = pre_execute(
op, *clients, scope=scope, aggcontext=aggcontext, **kwargs
)
new_scope = toolz.merge(scope, pre_executed_scope)
result = execute_until_in_scope(
expr,
new_scope,
aggcontext=aggcontext,
clients=clients,
# XXX: we *explicitly* pass in scope and not new_scope here so that
# post_execute sees the scope of execute_with_scope, not the scope of
# execute_until_in_scope
post_execute_=functools.partial(
post_execute,
scope=scope,
aggcontext=aggcontext,
clients=clients,
**kwargs,
),
**kwargs,
)
return result |
python | def get(self, eid):
"""
Returns a dict with the complete record of the entity with the given eID
"""
data = self._http_req('connections/%u' % eid)
self.debug(0x01, data['decoded'])
return data['decoded'] |
java | public void execute() throws Exception {
String site1 = getSecureBaseUrl(sites.get(0));
String site2 = getSecureBaseUrl(sites.get(1));
if(site1.equalsIgnoreCase(site2)) {
System.err.println("Cannot clone a site into itself.");
System.exit(1);
}
try{
System.out.println("Getting status of ["+site1+"]");
Status site1Status = StatusCommand.getSiteStatus(site1, token);
System.out.println("Getting status of ["+site2+"]");
Status site2Status = StatusCommand.getSiteStatus(site2, token);
if(site1Status != null && site2Status != null) {
String repo = site1Status.getRepo();
String revision = site1Status.getRevision();
String branch = site1Status.getBranch();
if(site2Status.getRepo().equals(repo) && site2Status.getBranch().equals(branch) && site2Status.getRevision().equals(revision)) {
System.err.println("Source [" + site1 + "] is on the same content repo, branch, and revision as the target [" + site2 + "].");
checkSendUpdateConfigMessage(site1, site2, site1Status, site2Status);
System.exit(1);
}
System.out.println("Sending update message to ["+site2+"]");
UpdateCommand.sendUpdateMessage(site2, repo, branch, revision, "Cloned from ["+site1+"]: " + comment, token);
checkSendUpdateConfigMessage(site1, site2, site1Status, site2Status);
} else {
System.err.println("Failed to get status from source and/or target.");
System.exit(1);
}
} catch(Exception e) {
e.printStackTrace();
System.err.println("Failed to clone ["+site1+"] to ["+site2+"]: "+e.getMessage());
}
} |
java | protected static CmsTreeItem getLastOpenedItem(CmsTreeItem item, int stopLevel, boolean requiresDropEnabled) {
if (stopLevel != -1) {
// stop level is set
int currentLevel = getPathLevel(item.getPath());
if (currentLevel > stopLevel) {
// we are past the stop level, prevent further checks
stopLevel = -1;
} else if (currentLevel == stopLevel) {
// matches stop level
return item;
}
}
if (item.getChildCount() > 0) {
int childIndex = item.getChildCount() - 1;
CmsTreeItem child = item.getChild(childIndex);
if (requiresDropEnabled) {
while (!child.isDropEnabled()) {
childIndex--;
if (childIndex < 0) {
return item;
}
child = item.getChild(childIndex);
}
}
if (child.isOpen()) {
return CmsTreeItem.getLastOpenedItem(child, stopLevel, requiresDropEnabled);
}
}
return item;
} |
python | def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01):
"""Enables SWO output on the target device.
Configures the output protocol, the SWO output speed, and enables any
ITM & stimulus ports.
This is equivalent to calling ``.swo_start()``.
Note:
If SWO is already enabled, it will first stop SWO before enabling it
again.
Args:
self (JLink): the ``JLink`` instance
cpu_speed (int): the target CPU frequency in Hz
swo_speed (int): the frequency in Hz used by the target to communicate
port_mask (int): port mask specifying which stimulus ports to enable
Returns:
``None``
Raises:
JLinkException: on error
"""
if self.swo_enabled():
self.swo_stop()
res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed,
swo_speed,
enums.JLinkSWOInterfaces.UART,
port_mask)
if res != 0:
raise errors.JLinkException(res)
self._swo_enabled = True
return None |
python | def decompress(self, value: LocalizedValue) -> List[str]:
"""Decompresses the specified value so
it can be spread over the internal widgets.
Arguments:
value:
The :see:LocalizedValue to display in this
widget.
Returns:
All values to display in the inner widgets.
"""
result = []
for lang_code, _ in settings.LANGUAGES:
if value:
result.append(value.get(lang_code))
else:
result.append(None)
return result |
java | public @NotNull OptionalInt findOptionalInt(@NotNull SqlQuery query) {
Optional<Integer> value = findOptional(Integer.class, query);
return value.isPresent() ? OptionalInt.of(value.get()) : OptionalInt.empty();
} |
java | static <T> void crossover(
final MSeq<T> that,
final MSeq<T> other,
final int index
) {
assert index >= 0 :
format(
"Crossover index must be within [0, %d) but was %d",
that.length(), index
);
that.swap(index, min(that.length(), other.length()), other, index);
} |
python | def _set_label(label, mark, dim, **kwargs):
"""Helper function to set labels for an axis
"""
if mark is None:
mark = _context['last_mark']
if mark is None:
return {}
fig = kwargs.get('figure', current_figure())
scales = mark.scales
scale_metadata = mark.scales_metadata.get(dim, {})
scale = scales.get(dim, None)
if scale is None:
return
dimension = scale_metadata.get('dimension', scales[dim])
axis = _fetch_axis(fig, dimension, scales[dim])
if axis is not None:
_apply_properties(axis, {'label': label}) |
java | private boolean validate(CmsFavoriteEntry entry) {
try {
String siteRoot = entry.getSiteRoot();
if (!m_okSiteRoots.contains(siteRoot)) {
m_rootCms.readResource(siteRoot);
m_okSiteRoots.add(siteRoot);
}
CmsUUID project = entry.getProjectId();
if (!m_okProjects.contains(project)) {
m_cms.readProject(project);
m_okProjects.add(project);
}
for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {
if ((id != null) && !m_okStructureIds.contains(id)) {
m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());
m_okStructureIds.add(id);
}
}
return true;
} catch (Exception e) {
LOG.info("Favorite entry validation failed: " + e.getLocalizedMessage(), e);
return false;
}
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.BEGIN_SEGMENT__SEGNAME:
setSEGNAME(SEGNAME_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
python | def on_hazard_exposure_bookmark_toggled(self, enabled):
"""Update the UI when the user toggles the bookmarks radiobutton.
:param enabled: The status of the radiobutton.
:type enabled: bool
"""
if enabled:
self.bookmarks_index_changed()
else:
self.ok_button.setEnabled(True)
self._populate_coordinates() |
python | def get_present_children(self, parent, locator, params=None, timeout=None, visible=False):
"""
Get child-elements both present in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param parent: parent-element
:param locator: locator tuple
:param params: (optional) locator params
:param timeout: (optional) time to wait for element (default: self._explicit_wait)
:param visible: (optional) if the element should also be visible (default: False)
:return: WebElement instance
"""
return self.get_present_elements(locator, params, timeout, visible, parent=parent) |
java | @Override
public com.liferay.commerce.product.model.CPDisplayLayout createCPDisplayLayout(
long CPDisplayLayoutId) {
return _cpDisplayLayoutLocalService.createCPDisplayLayout(CPDisplayLayoutId);
} |
python | def xpathNextDescendant(self, ctxt):
"""Traversal function for the "descendant" direction the
descendant axis contains the descendants of the context
node in document order; a descendant is a child or a child
of a child and so on. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.xmlXPathNextDescendant(ctxt__o, self._o)
if ret is None:raise xpathError('xmlXPathNextDescendant() failed')
__tmp = xmlNode(_obj=ret)
return __tmp |
java | public Point fromTransferObject(PointTo input, CrsId crsId) {
if (input == null) { return null; }
crsId = getCrsId(input, crsId);
isValid(input);
return createPoint(input.getCoordinates(), crsId);
} |
python | async def create_object(model, **data):
"""Create object asynchronously.
:param model: mode class
:param data: data for initializing object
:return: new object saved to database
"""
# NOTE! Here are internals involved:
#
# - obj._data
# - obj._get_pk_value()
# - obj._set_pk_value()
# - obj._prepare_instance()
#
warnings.warn("create_object() is deprecated, Manager.create() "
"should be used instead",
DeprecationWarning)
obj = model(**data)
pk = await insert(model.insert(**dict(obj.__data__)))
if obj._pk is None:
obj._pk = pk
return obj |
java | private void init(Context context, AttributeSet attrs, int defStyle)
{
// Initialize paint objects
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
paintSelectorBorder = new Paint();
paintSelectorBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
// Check if border and/or border is enabled
hasBorder = attributes.getBoolean(R.styleable.CircularImageView_border, false);
hasSelector = attributes.getBoolean(R.styleable.CircularImageView_selector, false);
// Set border properties if enabled
if(hasBorder) {
int defaultBorderSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
}
// Set selector properties if enabled
if(hasSelector) {
int defaultSelectorSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setSelectorColor(attributes.getColor(R.styleable.CircularImageView_selector_color, Color.TRANSPARENT));
setSelectorStrokeWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_selector_stroke_width, defaultSelectorSize));
setSelectorStrokeColor(attributes.getColor(R.styleable.CircularImageView_selector_stroke_color, Color.BLUE));
}
// Add shadow if enabled
if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
// We no longer need our attributes TypedArray, give it back to cache
attributes.recycle();
} |
python | def simple_write(filename, group, times, features,
properties=None, item='item', mode='a'):
"""Simplified version of `write()` when there is only one item."""
write(filename, group, [item], [times], [features], mode=mode,
properties=[properties] if properties is not None else None) |
python | def get_field_setup_query(query, model, column_name):
"""
Help function for SQLA filters, checks for dot notation on column names.
If it exists, will join the query with the model
from the first part of the field name.
example:
Contact.created_by: if created_by is a User model,
it will be joined to the query.
"""
if not hasattr(model, column_name):
# it's an inner obj attr
rel_model = getattr(model, column_name.split(".")[0]).mapper.class_
query = query.join(rel_model)
return query, getattr(rel_model, column_name.split(".")[1])
else:
return query, getattr(model, column_name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.