language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public static Anima open(String url, String user, String pass, Quirks quirks) {
return open(new Sql2o(url, user, pass, quirks));
} |
java | public LauncherTypeEnum getLauncherType() {
return Enums.getIfPresent(LauncherTypeEnum.class,
this.getProp(ConfigurationKeys.JOB_LAUNCHER_TYPE_KEY, JobLauncherFactory.JobLauncherType.LOCAL.name()))
.or(LauncherTypeEnum.LOCAL);
} |
python | def _resize_handler(self, *args, **kwarg): # pylint: disable=unused-argument
"""
Called when a window resize signal is detected
Resets the scroll window
"""
# Make sure only one resize handler is running
try:
assert self.resize_lock
except AssertionError:
self.resize_lock = True
term = self.term
term.clear_cache()
newHeight = term.height
newWidth = term.width
lastHeight = lastWidth = 0
while newHeight != lastHeight or newWidth != lastWidth:
lastHeight = newHeight
lastWidth = newWidth
time.sleep(.2)
term.clear_cache()
newHeight = term.height
newWidth = term.width
if newWidth < self.width:
offset = (self.scroll_offset - 1) * (1 + self.width // newWidth)
term.move_to(0, max(0, newHeight - offset))
self.stream.write(term.clear_eos)
self.width = newWidth
self._set_scroll_area(force=True)
for cter in self.counters:
cter.refresh(flush=False)
self.stream.flush()
self.resize_lock = False |
java | public static String makeClassPath(TopologyAPI.Topology topology, String originalPackageFile) {
String originalPackage = new File(originalPackageFile).getName();
StringBuilder classPathBuilder = new StringBuilder();
// TODO(nbhagat): Take type of package as argument.
if (originalPackage.endsWith(".jar")) {
// Bundled jar
classPathBuilder.append(originalPackage);
} else {
// Bundled tar
String topologyJar = originalPackage.replace(".tar.gz", "").replace(".tar", "") + ".jar";
classPathBuilder.append(String.format("libs/*:%s", topologyJar));
}
String additionalClasspath = TopologyUtils.getAdditionalClassPath(topology);
if (!additionalClasspath.isEmpty()) {
classPathBuilder.append(":");
classPathBuilder.append(TopologyUtils.getAdditionalClassPath(topology));
}
return classPathBuilder.toString();
} |
python | def _normalize_merge_diff(diff):
"""Make compare_config() for merge look similar to replace config diff."""
new_diff = []
for line in diff.splitlines():
# Filter blank lines and prepend +sign
if line.strip():
new_diff.append("+" + line)
if new_diff:
new_diff.insert(
0, "! incremental-diff failed; falling back to echo of merge file"
)
else:
new_diff.append("! No changes specified in merge file.")
return "\n".join(new_diff) |
java | public T process(String[] arguments, T bean) {
return process(Arrays.asList(arguments), bean);
} |
java | public static Class<?> erasure(Type type)
{
if (type instanceof ParameterizedType)
{
return erasure(((ParameterizedType)type).getRawType());
}
if (type instanceof TypeVariable<?>)
{
return erasure(((TypeVariable<?>)type).getBounds()[0]);
}
if (type instanceof WildcardType)
{
return erasure(((WildcardType)type).getUpperBounds()[0]);
}
if (type instanceof GenericArrayType)
{
return Array.newInstance(erasure(((GenericArrayType)type).getGenericComponentType()), 0).getClass();
}
// Only type left is class
return (Class<?>)type;
} |
python | def setup_signals(self, ):
"""Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None
"""
self.duplicate_tb.clicked.connect(self.duplicate)
self.delete_tb.clicked.connect(self.delete)
self.load_tb.clicked.connect(self.load)
self.unload_tb.clicked.connect(self.unload)
self.reference_tb.clicked.connect(self.reference)
self.importtf_tb.clicked.connect(self.import_file)
self.importref_tb.clicked.connect(self.import_reference)
self.replace_tb.clicked.connect(self.replace)
self.imported_tb.clicked.connect(partial(self.toggle_tbstyle, button=self.imported_tb))
self.alien_tb.clicked.connect(partial(self.toggle_tbstyle, button=self.alien_tb)) |
java | public void setResourceEntryList(int i, ResourceEntry v) {
if (ConceptMention_Type.featOkTst && ((ConceptMention_Type)jcasType).casFeat_resourceEntryList == null)
jcasType.jcas.throwFeatMissing("resourceEntryList", "de.julielab.jules.types.ConceptMention");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((ConceptMention_Type)jcasType).casFeatCode_resourceEntryList), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((ConceptMention_Type)jcasType).casFeatCode_resourceEntryList), i, jcasType.ll_cas.ll_getFSRef(v));} |
python | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
prior = self.prior
# filter posterior_predictive and log_likelihood
prior_predictive = self.prior_predictive
if prior_predictive is None:
prior_predictive = []
elif isinstance(prior_predictive, str):
prior_predictive = [prior_predictive]
ignore = prior_predictive + ["lp__"]
data = get_draws(prior, ignore=ignore)
return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims) |
java | protected Enumeration<URL> findResources(String name) throws IOException {
return java.util.Collections.emptyEnumeration();
} |
java | public List<AbstractPatternRule> loadFalseFriendRules(String filename)
throws ParserConfigurationException, SAXException, IOException {
if (motherTongue == null) {
return Collections.emptyList();
}
FalseFriendRuleLoader ruleLoader = new FalseFriendRuleLoader(motherTongue);
try (InputStream is = this.getClass().getResourceAsStream(filename)) {
if (is == null) {
return ruleLoader.getRules(new File(filename), language, motherTongue);
} else {
return ruleLoader.getRules(is, language, motherTongue);
}
}
} |
java | public final void mAUTO_ISO() throws RecognitionException {
try {
int _type = AUTO_ISO;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:603:10: ( ( 'AUTO_ISO' ) )
// druidG.g:603:11: ( 'AUTO_ISO' )
{
// druidG.g:603:11: ( 'AUTO_ISO' )
// druidG.g:603:12: 'AUTO_ISO'
{
match("AUTO_ISO");
}
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} |
java | private static void extractIccData(@NotNull final Metadata metadata, @NotNull SequentialReader reader) throws IOException
{
byte[] buffer = decodeHexCommentBlock(reader);
if (buffer != null)
new IccReader().extract(new ByteArrayReader(buffer), metadata);
} |
java | public void execute(Task task) {
try {
apply(this.task.getDestinationDir(), this.task.getClasspath());
} catch (IOException exception) {
throw new GradleException("Error accessing file system", exception);
}
} |
java | private String getPropertyLabel(PropertyIdValue propertyIdValue) {
PropertyRecord propertyRecord = this.propertyRecords
.get(propertyIdValue);
if (propertyRecord == null || propertyRecord.propertyDocument == null) {
return propertyIdValue.getId();
} else {
return getLabel(propertyIdValue, propertyRecord.propertyDocument);
}
} |
java | @GET
@Produces(MediaType.TEXT_PLAIN)
@Description("Does not do anything. Is only supported for backwards compatibility.")
@Path("/logout")
public Response logout(@Context HttpServletRequest req) {
return Response.ok("You have logged out.").build();
} |
java | private void search(Node node, E q, int k, List<Neighbor<E, E>> neighbors) {
int d = (int) distance.d(node.object, q);
if (d <= k) {
if (node.object != q || !identicalExcluded) {
neighbors.add(new Neighbor<>(node.object, node.object, node.index, d));
}
}
if (node.children != null) {
int start = Math.max(1, d-k);
int end = Math.min(node.children.size(), d+k+1);
for (int i = start; i < end; i++) {
Node child = node.children.get(i);
if (child != null) {
search(child, q, k, neighbors);
}
}
}
} |
python | def _get_regex_pattern(label):
"""Return a regular expression of the label.
This takes care of plural and different kinds of separators.
"""
parts = _split_by_punctuation.split(label)
for index, part in enumerate(parts):
if index % 2 == 0:
# Word
if not parts[index].isdigit() and len(parts[index]) > 1:
parts[index] = _convert_word(parts[index])
else:
# Punctuation
if not parts[index + 1]:
# The separator is not followed by another word. Treat
# it as a symbol.
parts[index] = _convert_punctuation(
parts[index],
current_app.config["CLASSIFIER_SYMBOLS"]
)
else:
parts[index] = _convert_punctuation(
parts[index],
current_app.config["CLASSIFIER_SEPARATORS"]
)
return "".join(parts) |
python | def rank_items(self, userid, user_items, selected_items, recalculate_user=False):
""" Rank given items for a user and returns sorted item list """
# check if selected_items contains itemids that are not in the model(user_items)
if max(selected_items) >= user_items.shape[1] or min(selected_items) < 0:
raise IndexError("Some of selected itemids are not in the model")
# calculate the relevance scores
liked_vector = user_items[userid]
recommendations = liked_vector.dot(self.similarity)
# remove items that are not in the selected_items
best = sorted(zip(recommendations.indices, recommendations.data), key=lambda x: -x[1])
ret = [rec for rec in best if rec[0] in selected_items]
# returned items should be equal to input selected items
for itemid in selected_items:
if itemid not in recommendations.indices:
ret.append((itemid, -1.0))
return ret |
java | private <T> Observable<T> asObservable(Executor<T> transaction) {
return Observable.create(emitter -> storeFactory.execute(new StoreTransaction<ChatStore>() {
@Override
protected void execute(ChatStore store) {
try {
transaction.execute(store, emitter);
} finally {
emitter.onCompleted();
}
}
}), Emitter.BackpressureMode.BUFFER);
} |
python | def _check_positions(self):
'''Checks each bee to see if it abandons its current food source (has
not found a better one in self._limit iterations); if abandoning, it
becomes a scout and generates a new, random food source
'''
self.__verify_ready()
max_trials = 0
scout = None
for bee in self._employers:
if (bee.failed_trials >= max_trials):
max_trials = bee.failed_trials
scout = bee
if scout is not None and scout.failed_trials > self._limit:
self._logger.log(
'debug',
'Sending scout (error of {} with limit of {})'.format(
scout.error, scout.failed_trials
)
)
scout.values = self.__gen_random_values() |
python | def to_otu(self, biom_id=None):
"""Converts a list of objects associated with a classification result into a `dict` resembling
an OTU table.
Parameters
----------
biom_id : `string`, optional
Optionally specify an `id` field for the generated v1 BIOM file.
Returns
-------
otu_table : `OrderedDict`
A BIOM OTU table, returned as a Python OrderedDict (can be dumped to JSON)
"""
otu_format = "Biological Observation Matrix 1.0.0"
# Note: This is exact format URL is required by https://github.com/biocore/biom-format
otu_url = "http://biom-format.org"
otu = OrderedDict(
{
"id": biom_id,
"format": otu_format,
"format_url": otu_url,
"type": "OTU table",
"generated_by": "One Codex API V1",
"date": datetime.now().isoformat(),
"rows": [],
"columns": [],
"matrix_type": "sparse",
"matrix_element_type": "int",
}
)
rows = defaultdict(dict)
tax_ids_to_names = {}
for classification in self._classifications:
col_id = len(otu["columns"]) # 0 index
# Re-encoding the JSON is a bit of a hack, but
# we need a ._to_dict() method that properly
# resolves references and don't have one at the moment
columns_entry = {
"id": str(classification.id),
"sample_id": str(classification.sample.id),
"sample_filename": classification.sample.filename,
"metadata": json.loads(
classification.sample.metadata._to_json(include_references=False)
),
}
otu["columns"].append(columns_entry)
sample_df = classification.table()
for row in sample_df.iterrows():
tax_id = row[1]["tax_id"]
tax_ids_to_names[tax_id] = row[1]["name"]
rows[tax_id][col_id] = int(row[1]["readcount"])
num_rows = len(rows)
num_cols = len(otu["columns"])
otu["shape"] = [num_rows, num_cols]
otu["data"] = []
for present_taxa in sorted(rows):
# add the row entry
row_id = len(otu["rows"])
otu["rows"].append(
{"id": present_taxa, "metadata": {"taxonomy": tax_ids_to_names[present_taxa]}}
)
for sample_with_hit in rows[present_taxa]:
counts = rows[present_taxa][sample_with_hit]
otu["data"].append([row_id, sample_with_hit, counts])
return otu |
java | public static String ENDPOINT_WRONG_PARAMS(Object arg0, Object arg1) {
return localizer.localize(localizableENDPOINT_WRONG_PARAMS(arg0, arg1));
} |
python | def _decode(self):
"""
Convert the characters of character in value of component to standard
value (WFN value).
This function scans the value of component and returns a copy
with all percent-encoded characters decoded.
:exception: ValueError - invalid character in value of component
"""
result = []
idx = 0
s = self._encoded_value
embedded = False
errmsg = []
errmsg.append("Invalid value: ")
while (idx < len(s)):
errmsg.append(s)
errmsg_str = "".join(errmsg)
# Get the idx'th character of s
c = s[idx]
# Deal with dot, hyphen and tilde: decode with quoting
if ((c == '.') or (c == '-') or (c == '~')):
result.append("\\")
result.append(c)
idx += 1
embedded = True # a non-%01 encountered
continue
if (c != '%'):
result.append(c)
idx += 1
embedded = True # a non-%01 encountered
continue
# we get here if we have a substring starting w/ '%'
form = s[idx: idx + 3] # get the three-char sequence
if form == CPEComponent2_3_URI.WILDCARD_ONE:
# If %01 legal at beginning or end
# embedded is false, so must be preceded by %01
# embedded is true, so must be followed by %01
if (((idx == 0) or (idx == (len(s)-3))) or
((not embedded) and (s[idx - 3:idx] == CPEComponent2_3_URI.WILDCARD_ONE)) or
(embedded and (len(s) >= idx + 6) and (s[idx + 3:idx + 6] == CPEComponent2_3_URI.WILDCARD_ONE))):
# A percent-encoded question mark is found
# at the beginning or the end of the string,
# or embedded in sequence as required.
# Decode to unquoted form.
result.append(CPEComponent2_3_WFN.WILDCARD_ONE)
idx += 3
continue
else:
raise ValueError(errmsg_str)
elif form == CPEComponent2_3_URI.WILDCARD_MULTI:
if ((idx == 0) or (idx == (len(s) - 3))):
# Percent-encoded asterisk is at the beginning
# or the end of the string, as required.
# Decode to unquoted form.
result.append(CPEComponent2_3_WFN.WILDCARD_MULTI)
else:
raise ValueError(errmsg_str)
elif form in CPEComponent2_3_URI.pce_char_to_decode.keys():
value = CPEComponent2_3_URI.pce_char_to_decode[form]
result.append(value)
else:
errmsg.append("Invalid percent-encoded character: ")
errmsg.append(s)
raise ValueError("".join(errmsg))
idx += 3
embedded = True # a non-%01 encountered.
self._standard_value = "".join(result) |
python | def generate_device_id(steamid):
"""Generate Android device id
:param steamid: Steam ID
:type steamid: :class:`.SteamID`, :class:`int`
:return: android device id
:rtype: str
"""
h = hexlify(sha1_hash(str(steamid).encode('ascii'))).decode('ascii')
return "android:%s-%s-%s-%s-%s" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32]) |
python | def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
# Either min and max need to be given, or value needs to be given
if value is None:
if min is None or max is None:
raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))
diff = max - min
value = min + (diff / 2)
# Ensure that value has the same type as diff
if not isinstance(value, type(diff)):
value = min + (diff // 2)
else: # value is not None
if not isinstance(value, Real):
raise TypeError('expected a real number, got: %r' % value)
# Infer min/max from value
if value == 0:
# This gives (0, 1) of the correct type
vrange = (value, value + 1)
elif value > 0:
vrange = (-value, 3*value)
else:
vrange = (3*value, -value)
if min is None:
min = vrange[0]
if max is None:
max = vrange[1]
if step is not None:
# ensure value is on a step
tick = int((value - min) / step)
value = min + tick * step
if not min <= value <= max:
raise ValueError('value must be between min and max (min={0}, value={1}, max={2})'.format(min, value, max))
return min, max, value |
python | def name_history(self):
"""A list of user names (as user can change those occasionally).
:rtype: list
"""
history = []
idx = 0
get_history = self._iface.get_name_history
uid = self.user_id
while True:
name = get_history(uid, idx)
if not name:
break
idx += 1
history.append(name)
return history |
python | def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):
# type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset]
"""
Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics.
"""
if not no_warn:
warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning)
fbks = []
datasets = []
try:
datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))
except DatasetBuildError as ex:
fbks.extend(ex.args[2])
# NOTE: the recursive call needs to stay out of the exception handler to avoid showing
# to the user a confusing error message due to exception chaining
for fbk in fbks:
bks = backend_kwargs.copy()
bks['filter_by_keys'] = fbk
datasets.extend(open_datasets(path, backend_kwargs=bks, no_warn=True, **kwargs))
return datasets |
python | def histogram(self, key, **dims):
"""Adds histogram with dimensions to the registry"""
return super(MetricsRegistry, self).histogram(
self.metadata.register(key, **dims)) |
java | protected void _syncProperties(
final T object,
final T p_object
)
{
BeansUtil.copyPropertiesExcept(
p_object,
object,
new String[] { "persistentID" }
);
} |
java | public Matrix4d scaleAround(double factor, double ox, double oy, double oz) {
return scaleAround(factor, factor, factor, ox, oy, oz, this);
} |
java | public String getProperty(final String key) {
if (hasProperty(key)) {
return properties.getProperty(key);
} else {
throw new PropertyLookupException("property not found: " + key);
}
} |
java | public void detach(Object self) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
for (String fieldName : doc.fieldNames()) {
Object value = getValue(self, fieldName, false, null);
if (value instanceof OLazyObjectMultivalueElement)
((OLazyObjectMultivalueElement) value).detach();
OObjectEntitySerializer.setFieldValue(getField(fieldName, self.getClass()), self, value);
}
OObjectEntitySerializer.setIdField(self.getClass(), self, doc.getIdentity());
OObjectEntitySerializer.setVersionField(self.getClass(), self, doc.getVersion());
} |
java | public Optional<V> findOne(final K key) {
return findOne(key, mongoProperties.getDefaultReadTimeout(), TimeUnit.MILLISECONDS);
} |
java | public GitlabAward getAward(GitlabIssue issue, Integer awardId) throws IOException {
String tailUrl = GitlabProject.URL + "/" + issue.getProjectId() + GitlabIssue.URL + "/" + issue.getId()
+ GitlabAward.URL + "/" + awardId;
return retrieve().to(tailUrl, GitlabAward.class);
} |
python | def remove_on_change(self, attr, *callbacks):
''' Remove a callback from this object '''
if len(callbacks) == 0:
raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter")
_callbacks = self._callbacks.setdefault(attr, [])
for callback in callbacks:
_callbacks.remove(callback) |
java | public static String formatLatitude(Locale locale, double latitude, UnitType unit)
{
return format(locale, latitude, unit, NS);
} |
java | public static List<CPInstance> findByC_ST(long CPDefinitionId, int status,
int start, int end) {
return getPersistence().findByC_ST(CPDefinitionId, status, start, end);
} |
python | def sendcontrol(self, char):
'''Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
'''
n, byte = self.ptyproc.sendcontrol(char)
self._log_control(byte)
return n |
java | private byte[] berEncodedValue() {
final ByteBuffer buff = ByteBuffer.allocate(5);
buff.put((byte) 0x30); // (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
buff.put((byte) 0x03); // size
buff.put((byte) 0x02); // 4bytes int tag
buff.put((byte) 0x01); // int size
buff.put(NumberFacility.leftTrim(NumberFacility.getBytes(flags))); // value
return buff.array();
} |
python | def pool(builder, size, timeout=None):
"""Create a pool that imposes a limit on the number of stored
instances.
Args:
builder: a function to build an instance.
size: the size of the pool.
timeout(Optional[float]): the seconds to wait before raising
a ``queue.Empty`` exception if no instances are available
within that time.
Raises:
If ``timeout`` is defined but the request is taking longer
than the specified time, the context manager will raise
a ``queue.Empty`` exception.
Returns:
A context manager that can be used with the ``with``
statement.
"""
lock = threading.Lock()
local_pool = queue.Queue()
current_size = 0
@contextlib.contextmanager
def pooled():
nonlocal current_size
instance = None
# If we still have free slots, then we have room to create new
# instances.
if current_size < size:
with lock:
# We need to check again if we have slots available, since
# the situation might be different after acquiring the lock
if current_size < size:
current_size += 1
instance = builder()
# Watchout: current_size can be equal to size if the previous part of
# the function has been executed, that's why we need to check if the
# instance is None.
if instance is None:
instance = local_pool.get(timeout=timeout)
yield instance
local_pool.put(instance)
return pooled |
python | def request(self, request):
"""Sets the request of this V1beta1CertificateSigningRequestSpec.
Base64-encoded PKCS#10 CSR data # noqa: E501
:param request: The request of this V1beta1CertificateSigningRequestSpec. # noqa: E501
:type: str
"""
if request is None:
raise ValueError("Invalid value for `request`, must not be `None`") # noqa: E501
if request is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request): # noqa: E501
raise ValueError(r"Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501
self._request = request |
python | def when_file_changed(*filenames, **kwargs):
"""
Register the decorated function to run when one or more files have changed.
:param list filenames: The names of one or more files to check for changes
(a callable returning the name is also accepted).
:param str hash_type: The type of hash to use for determining if a file has
changed. Defaults to 'md5'. Must be given as a kwarg.
"""
def _register(action):
handler = Handler.get(action)
handler.add_predicate(partial(any_file_changed, filenames, **kwargs))
return action
return _register |
java | @Override
public List<BaseStyler> getStylers(String... styleClasses) throws VectorPrintException {
if (styleClasses == null || styleClasses.length == 0 || styleClasses[0] == null || styleClasses[0].isEmpty()) {
return Collections.EMPTY_LIST;
}
List<BaseStyler> stylers = new ArrayList<>(styleClasses.length + 4);
preOrPostStyle(PRESTYLERS, stylers, styleClasses);
BaseStyler first = null;
for (String name : styleClasses) {
List<BaseStyler> parameterizables = getParameterizables(name, STYLERPACKAGENAME);
if (first == null && parameterizables.size() > 0) {
first = parameterizables.get(0);
if (first instanceof SimpleColumns || (!(first instanceof Advanced) && first.creates()) || (first instanceof Image && first.getValue(Image.DOSTYLE, Boolean.class))) {
log.warning(String.format("putting %s in front of all stylers because it creates an element", first));
stylers.add(0, first);
for (int i = 1; i < parameterizables.size(); i++) {
stylers.add(parameterizables.get(i));
}
continue;
}
}
stylers.addAll(parameterizables);
}
preOrPostStyle(POSTSTYLERS, stylers, styleClasses);
impdf.clear();
imtiff.clear();
imcol.clear();
debug(stylers, styleClasses);
return stylers;
} |
java | public static String get(final String templateName, final Map<String, Object> data) {
StringWriter writer = new StringWriter();
write(templateName, data, writer);
return writer.toString();
} |
python | def _remove_some_work_units(self, work_spec_name, work_unit_names,
suffix='', priority_min='-inf',
priority_max='+inf'):
'''Remove some units from somewhere.'''
now = time.time()
if work_unit_names is None:
count = 0
while True:
with self.registry.lock(identifier=self.worker_id) as session:
names = session.filter(
WORK_UNITS_ + work_spec_name + suffix,
priority_min=priority_min, priority_max=priority_max,
limit=1000)
if not names: break
count += session.popmany(
WORK_UNITS_ + work_spec_name + suffix, *names)
else:
# TODO: This needs to honor priority_min/priority_max,
# otherwise it gets the wrong answer for "available"/
# "pending" (it will get both states).
with self.registry.lock(identifier=self.worker_id) as session:
count = session.popmany(WORK_UNITS_ + work_spec_name + suffix,
*work_unit_names)
return count |
python | def element_wise(self, other, op):
"""
Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
----------
other : Data or numpy array
Data to apply elementwise operation to
op : function
Binary operator to use for elementwise operations, e.g. add, subtract
"""
if not isscalar(other) and not self.shape == other.shape:
raise ValueError("shapes %s and %s must be equal" % (self.shape, other.shape))
if not isscalar(other) and isinstance(other, Data) and not self.mode == other.mode:
raise NotImplementedError
if isscalar(other):
return self.map(lambda x: op(x, other))
if self.mode == 'local' and isinstance(other, ndarray):
return self._constructor(op(self.values, other)).__finalize__(self)
if self.mode == 'local' and isinstance(other, Data):
return self._constructor(op(self.values, other.values)).__finalize__(self)
if self.mode == 'spark' and isinstance(other, Data):
def func(record):
(k1, x), (k2, y) = record
return k1, op(x, y)
rdd = self.tordd().zip(other.tordd()).map(func)
barray = BoltArraySpark(rdd, shape=self.shape, dtype=self.dtype, split=self.values.split)
return self._constructor(barray).__finalize__(self) |
python | def refresh_client(self):
""" Refreshes the FindMyiPhoneService endpoint,
This ensures that the location data is up-to-date.
"""
req = self.session.post(
self._fmip_refresh_url,
params=self.params,
data=json.dumps(
{
'clientContext': {
'fmly': True,
'shouldLocate': True,
'selectedDevice': 'all',
}
}
)
)
self.response = req.json()
for device_info in self.response['content']:
device_id = device_info['id']
if device_id not in self._devices:
self._devices[device_id] = AppleDevice(
device_info,
self.session,
self.params,
manager=self,
sound_url=self._fmip_sound_url,
lost_url=self._fmip_lost_url,
message_url=self._fmip_message_url,
)
else:
self._devices[device_id].update(device_info)
if not self._devices:
raise PyiCloudNoDevicesException() |
java | public static Builder from(Reader swaggerReader) {
Validate.notNull(swaggerReader, "swaggerReader must not be null");
Swagger swagger;
try {
swagger = new SwaggerParser().parse(IOUtils.toString(swaggerReader));
} catch (IOException e) {
throw new RuntimeException("Swagger source can not be parsed", e);
}
if (swagger == null)
throw new IllegalArgumentException("Swagger source is in a wrong format");
return new Builder(swagger);
} |
java | public ListOrdersRequest withPaymentMethod(String... values) {
List<String> list = getPaymentMethod();
for (String value : values) {
list.add(value);
}
return this;
} |
java | public static void newBuilder(String projectId, String topicId) throws Exception {
ProjectTopicName topic = ProjectTopicName.of(projectId, topicId);
Publisher publisher = Publisher.newBuilder(topic).build();
try {
// ...
} finally {
// When finished with the publisher, make sure to shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
} |
java | @Override
public void actionPerformed(ActionEvent event) {
Object mysource = event.getSource();
if ( ! (mysource instanceof JComboBox )) {
super.actionPerformed(event);
return;
}
@SuppressWarnings("unchecked")
JComboBox<String> source = (JComboBox<String>) event.getSource();
String value = source.getSelectedItem().toString();
evalString("save selection; ");
String selectLigand = "select ligand;wireframe 0.16;spacefill 0.5; color cpk ;";
if ( value.equals("Cartoon")){
String script = "hide null; select all; spacefill off; wireframe off; backbone off;" +
" cartoon on; " +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("Backbone")){
String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" +
" cartoon off; " +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("CPK")){
String script = "hide null; select all; spacefill off; wireframe off; backbone off;" +
" cartoon off; cpk on;" +
" select ligand; wireframe 0.16;spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if (value.equals("Ligands")){
this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;");
} else if (value.equals("Ligands and Pocket")){
this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; ");
} else if ( value.equals("Ball and Stick")){
String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" +
" cartoon off; backbone off; " +
" select ligand; wireframe 0.16; spacefill 0.5; color cpk; " +
" select *.FE; spacefill 0.7; color cpk ; " +
" select *.CU; spacefill 0.7; color cpk ; " +
" select *.ZN; spacefill 0.7; color cpk ; " +
" select all; ";
this.executeCmd(script);
} else if ( value.equals("By Chain")){
jmolColorByChain();
String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; ";
this.executeCmd(script);
} else if ( value.equals("Rainbow")) {
this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; " );
} else if ( value.equals("Secondary Structure")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; " );
} else if ( value.equals("By Element")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; ");
} else if ( value.equals("By Amino Acid")){
this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; " );
} else if ( value.equals("Hydrophobicity") ){
this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; "+ selectLigand+"; select all; ");
} else if ( value.equals("Suggest Domains")){
colorByPDP();
} else if ( value.equals("Show SCOP Domains")){
colorBySCOP();
}
evalString("restore selection; ");
} |
python | def set_xylims(self, lims, axes=None, panel=None):
"""overwrite data for trace t """
if panel is None: panel = self.current_panel
self.panels[panel].set_xylims(lims, axes=axes, **kw) |
java | @Override
public List<Job> parse(String text) throws ParseException {
final List<Job> jobs;
if (StringUtils.isNotBlank(text)) {
text = StringUtils.replace(text, "\n\t", "");
jobs = new LinkedList<Job>();
String separator = "\n";
if (text.indexOf("\r\n") > 0) {
separator = "\r\n";
}
final String[] lines = text.split(separator);
Job job = null;
for (final String line : lines) {
Matcher matcher = PATTERN_JOB.matcher(line);
if (matcher.matches()) {
if (job != null) {
jobs.add(job);
}
job = new Job();
final String id = matcher.group(1).trim();
job.setId(id);
} else if (StringUtils.isNotBlank(line)) {
String[] temp = Utils.splitFirst(line, CHAR_EQUALS);
if (temp.length == 2) {
final String key = temp[0].trim().toLowerCase();
final String value = temp[1].trim();
if ("job_name".equalsIgnoreCase(key)) {
job.setName(value);
} else if ("job_owner".equalsIgnoreCase(key)) {
job.setOwner(value);
} else if (key.startsWith("resources_used.")) {
job.getResourcesUsed().put(key, value);
} else if ("job_state".equalsIgnoreCase(key)) {
job.setState(value);
} else if ("queue".equalsIgnoreCase(key)) {
job.setQueue(value);
} else if ("server".equalsIgnoreCase(key)) {
job.setServer(value);
} else if ("checkpoint".equalsIgnoreCase(key)) {
job.setCheckpoint(value);
} else if ("ctime".equalsIgnoreCase(key)) {
job.setCtime(value);
} else if ("error_path".equalsIgnoreCase(key)) {
job.setErrorPath(value);
} else if ("exec_host".equalsIgnoreCase(key)) {
job.setExecHost(value);
} else if ("exec_port".equalsIgnoreCase(key)) {
job.setExecPort(value);
} else if ("hold_types".equalsIgnoreCase(key)) {
job.setHoldTypes(value);
} else if ("join_path".equalsIgnoreCase(key)) {
job.setJoinPath(value);
} else if ("keep_files".equalsIgnoreCase(key)) {
job.setKeepFiles(value);
} else if ("mail_points".equalsIgnoreCase(key)) {
job.setMailPoints(value);
} else if ("mail_users".equalsIgnoreCase(key)) {
job.setMailUsers(value);
} else if ("mtime".equalsIgnoreCase(key)) {
job.setMtime(value);
} else if ("output_path".equalsIgnoreCase(key)) {
job.setOutputPath(value);
} else if ("priority".equalsIgnoreCase(key)) {
try {
job.setPriority(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job priority: " + nfe.getMessage(), nfe);
job.setPriority(-1);
}
} else if ("qtime".equalsIgnoreCase(key)) {
job.setQtime(value);
} else if ("rerunable".equalsIgnoreCase(key)) {
job.setRerunable(Boolean.parseBoolean(value));
} else if (key.startsWith("resource_list.")) {
job.getResourceList().put(key, value);
} else if ("session_id".equalsIgnoreCase(key)) {
try {
job.setSessionId(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job session id: " + nfe.getMessage(), nfe);
job.setSessionId(-1);
}
} else if ("substate".equalsIgnoreCase(key)) {
try {
job.setSubstate(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job substate: " + nfe.getMessage(), nfe);
job.setSubstate(-1);
}
} else if (key.startsWith("variable_list")) {
job.getVariableList().put(key, value);
} else if ("etime".equalsIgnoreCase(key)) {
job.setEtime(value);
} else if ("euser".equalsIgnoreCase(key)) {
job.setEuser(value);
} else if ("egroup".equalsIgnoreCase(key)) {
job.setEgroup(value);
} else if ("hashname".equalsIgnoreCase(key)) {
job.setHashName(value);
} else if ("queue_rank".equalsIgnoreCase(key)) {
try {
job.setQueueRank(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job queue rank: " + nfe.getMessage(), nfe);
job.setQueueRank(-1);
}
} else if ("queue_type".equalsIgnoreCase(key)) {
job.setQueueType(value);
} else if ("comment".equalsIgnoreCase(key)) {
job.setComment(value);
} else if ("submit_args".equalsIgnoreCase(key)) {
job.setSubmitArgs(value);
} else if ("submit_host".equalsIgnoreCase(key)) {
job.setSubmitHost(value);
} else if ("start_time".equalsIgnoreCase(key)) {
job.setStartTime(value);
} else if ("start_count".equalsIgnoreCase(key)) {
try {
job.setStartCount(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job start count: " + nfe.getMessage(), nfe);
job.setStartCount(-1);
}
} else if ("fault_tolerant".equalsIgnoreCase(key)) {
job.setFaultTolerant(Boolean.parseBoolean(value));
} else if ("job_array_id".equalsIgnoreCase(key)) {
job.setJobArrayId(Integer.parseInt(value));
} else if ("job_radix".equalsIgnoreCase(key)) {
try {
job.setRadix(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job radix: " + nfe.getMessage(), nfe);
job.setRadix(-1);
}
} else if ("walltime.remaining".equalsIgnoreCase(key)) {
try {
job.setWalltimeRemaining(Long.parseLong(value));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Failed parsing job walltime remaining: " + nfe.getMessage(),
nfe);
job.setWalltimeRemaining(-1L);
}
}
}
}
}
if (job != null) {
jobs.add(job);
}
return jobs;
} else {
return Collections.emptyList();
}
} |
python | def __initialize_ui(self):
"""
Initializes the View ui.
"""
self.viewport().installEventFilter(ReadOnlyFilter(self))
if issubclass(type(self), QListView):
super(type(self), self).setUniformItemSizes(True)
elif issubclass(type(self), QTreeView):
super(type(self), self).setUniformRowHeights(True) |
java | public ResourceName parentName() {
PathTemplate parentTemplate = template.parentTemplate();
return new ResourceName(parentTemplate, values, endpoint);
} |
java | public static <T, K> boolean moveUp(List<T> list, K key,
Function<T, K> keyMapper, int n) {
if (list == null)
return false;
ArrayList<T> newList = new ArrayList<T>();
boolean changed = false;
for (int i = 0; i < list.size(); i++) {
T item = list.get(i);
if (i > 0 && key.equals(keyMapper.apply(item))) {
int posi = i - n;
if (posi < 0)
posi = 0;
newList.add(posi, item);
changed = true;
} else
newList.add(item);
}
if (changed) {
list.clear();
list.addAll(newList);
return true;
}
return false;
} |
java | private static void parseFilters(final FilterType filterType, final WebApp webApp) {
final WebAppFilter filter = new WebAppFilter();
if (filterType.getFilterName() != null) {
filter.setFilterName(filterType.getFilterName().getValue());
}
if (filterType.getFilterClass() != null) {
filter.setFilterClass(filterType.getFilterClass().getValue());
}
if (filterType.getAsyncSupported() != null) {
filter.setAsyncSupported(filterType.getAsyncSupported().isValue());
}
webApp.addFilter(filter);
List<ParamValueType> initParams = filterType.getInitParam();
if (initParams != null && initParams.size() > 0) {
for (ParamValueType initParamElement : initParams) {
final WebAppInitParam initParam = new WebAppInitParam();
initParam.setParamName(initParamElement.getParamName().getValue());
initParam.setParamValue(initParamElement.getParamValue().getValue());
filter.addInitParam(initParam);
}
}
List<DescriptionType> description = filterType.getDescription();
for (DescriptionType descriptionType : description) {
filter.addDispatcherType(DispatcherType.valueOf(descriptionType.getValue()));
}
} |
python | def dry_run_report(self):
"""
Returns text displaying the items that need to be uploaded or a message saying there are no files/folders
to upload.
:return: str: report text
"""
project_uploader = ProjectUploadDryRun()
project_uploader.run(self.local_project)
items = project_uploader.upload_items
if not items:
return "\n\nNo changes found. Nothing needs to be uploaded.\n\n"
else:
result = "\n\nFiles/Folders that need to be uploaded:\n"
for item in items:
result += "{}\n".format(item)
result += "\n"
return result |
python | def update_parameter(self, parameter_id, content=None, name=None, param_type=None):
"""
Updates the parameter attached to an Indicator or IndicatorItem node.
All inputs must be strings or unicode objects.
:param parameter_id: The unique id of the parameter to modify
:param content: The value of the parameter.
:param name: The name of the parameter.
:param param_type: The type of the parameter content.
:return: True, unless none of the optional arguments are supplied
:raises: IOCParseError if the parameter id is not present in the IOC.
"""
if not (content or name or param_type):
log.warning('Must specify at least the value/text(), param/@name or the value/@type values to update.')
return False
parameters_node = self.parameters
elems = parameters_node.xpath('.//param[@id="{}"]'.format(parameter_id))
if len(elems) != 1:
msg = 'Did not find a single parameter with the supplied ID[{}]. Found [{}] parameters'.format(parameter_id,
len(elems))
raise IOCParseError(msg)
param_node = elems[0]
value_node = param_node.find('value')
if name:
param_node.attrib['name'] = name
if value_node is None:
msg = 'No value node is associated with param [{}]. Not updating value node with content or tuple.' \
.format(parameter_id)
log.warning(msg)
else:
if content:
value_node.text = content
if param_type:
value_node.attrib['type'] = param_type
return True |
python | def GetAPFSVolumeByPathSpec(self, path_spec):
"""Retrieves an APFS volume for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyfsapfs.volume: an APFS volume or None if not available.
"""
volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex(path_spec)
if volume_index is None:
return None
return self._fsapfs_container.get_volume(volume_index) |
java | public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
{
int context = getArg0AsNode(xctxt);
XObject val;
if (DTM.NULL != context)
{
DTM dtm = xctxt.getDTM(context);
String qname = dtm.getNodeNameX(context);
val = (null == qname) ? XString.EMPTYSTRING : new XString(qname);
}
else
{
val = XString.EMPTYSTRING;
}
return val;
} |
java | @Override
public Endpoint next(Endpoint[] array) {
return array[(int) (System.nanoTime() % array.length)];
} |
java | public void readExternal(PofReader reader)
throws IOException {
name = reader.readString(0);
last = reader.readLong(1);
} |
python | def get_templates(self, team_context, workitemtypename=None):
"""GetTemplates.
[Preview API] Gets template
:param :class:`<TeamContext> <azure.devops.v5_0.work_item_tracking.models.TeamContext>` team_context: The team context for the operation
:param str workitemtypename: Optional, When specified returns templates for given Work item type.
:rtype: [WorkItemTemplateReference]
"""
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')
query_parameters = {}
if workitemtypename is not None:
query_parameters['workitemtypename'] = self._serialize.query('workitemtypename', workitemtypename, 'str')
response = self._send(http_method='GET',
location_id='6a90345f-a676-4969-afce-8e163e1d5642',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[WorkItemTemplateReference]', self._unwrap_collection(response)) |
python | def list_presets(self, package_keyname, **kwargs):
"""Gets active presets for the given package.
:param str package_keyname: The package for which to get presets
:returns: A list of package presets that can be used for ordering
"""
get_kwargs = {}
get_kwargs['mask'] = kwargs.get('mask', PRESET_MASK)
if 'filter' in kwargs:
get_kwargs['filter'] = kwargs['filter']
package = self.get_package_by_key(package_keyname, mask='id')
acc_presets = self.package_svc.getAccountRestrictedActivePresets(id=package['id'], **get_kwargs)
active_presets = self.package_svc.getActivePresets(id=package['id'], **get_kwargs)
return active_presets + acc_presets |
python | def for_class(digobj, repo):
'''Generate a ContentModel object for the specified
:class:`DigitalObject` class. Content model object is saved
in the specified repository if it doesn't already exist.'''
full_name = '%s.%s' % (digobj.__module__, digobj.__name__)
cmodels = getattr(digobj, 'CONTENT_MODELS', None)
if not cmodels:
logger.debug('%s has no content models', full_name)
return None
if len(cmodels) > 1:
logger.debug('%s has %d content models', full_name, len(cmodels))
raise ValueError(('Cannot construct ContentModel object for ' +
'%s, which has %d CONTENT_MODELS (only 1 is ' +
'supported)') %
(full_name, len(cmodels)))
cmodel_uri = cmodels[0]
logger.debug('cmodel for %s is %s', full_name, cmodel_uri)
cmodel_obj = repo.get_object(cmodel_uri, type=ContentModel,
create=False)
if cmodel_obj.exists:
logger.debug('%s already exists', cmodel_uri)
return cmodel_obj
# otherwise the cmodel doesn't exist. let's create it.
logger.debug('creating %s from %s', cmodel_uri, full_name)
cmodel_obj = repo.get_object(cmodel_uri, type=ContentModel,
create=True)
# XXX: should this use _defined_datastreams instead?
for ds in digobj._local_datastreams.values():
ds_composite_model = cmodel_obj.ds_composite_model.content
type_model = ds_composite_model.get_type_model(ds.id, create=True)
type_model.mimetype = ds.default_mimetype
if ds.default_format_uri:
type_model.format_uri = ds.default_format_uri
cmodel_obj.save()
return cmodel_obj |
java | public Observable<ServiceResponse<ContentKeyPolicyPropertiesInner>> getPolicyPropertiesWithSecretsWithServiceResponseAsync(String resourceGroupName, String accountName, String contentKeyPolicyName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (contentKeyPolicyName == null) {
throw new IllegalArgumentException("Parameter contentKeyPolicyName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getPolicyPropertiesWithSecrets(this.client.subscriptionId(), resourceGroupName, accountName, contentKeyPolicyName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ContentKeyPolicyPropertiesInner>>>() {
@Override
public Observable<ServiceResponse<ContentKeyPolicyPropertiesInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ContentKeyPolicyPropertiesInner> clientResponse = getPolicyPropertiesWithSecretsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} |
java | public List<CmsRelation> getRelationsForResource(
CmsRequestContext context,
CmsResource resource,
CmsRelationFilter filter)
throws CmsException {
List<CmsRelation> result = null;
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
// check the access permissions
if (resource != null) {
checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL);
}
result = m_driverManager.getRelationsForResource(dbc, resource, filter);
} catch (Exception e) {
dbc.report(
null,
Messages.get().container(
Messages.ERR_READ_RELATIONS_1,
(resource != null) ? context.removeSiteRoot(resource.getRootPath()) : "null"),
e);
} finally {
dbc.clear();
}
return result;
} |
python | def add_documents(self, documents):
'''
Adds more than one document using the same API call
Returns two lists: the first one contains the successfully uploaded
documents, and the second one tuples with documents that failed to be
uploaded and the exceptions raised.
'''
result, errors = [], []
for document in documents:
try:
result.append(self.add_document(document))
except RuntimeError as exc:
errors.append((document, exc))
return result, errors |
java | @Benchmark
public int constructAndIter(ConstructAndIterState state)
{
int dataSize = state.dataSize;
int[] data = state.data;
MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap();
for (int i = 0; i < dataSize; i++) {
mutableBitmap.add(data[i]);
}
ImmutableBitmap bitmap = factory.makeImmutableBitmap(mutableBitmap);
return iter(bitmap);
} |
java | public FailoverGroupInner beginForceFailoverAllowDataLoss(String resourceGroupName, String serverName, String failoverGroupName) {
return beginForceFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, serverName, failoverGroupName).toBlocking().single().body();
} |
python | def send(self, message, _sender=None):
"""Sends a message to the actor represented by this `Ref`."""
if not _sender:
context = get_context()
if context:
_sender = context.ref
if self._cell:
if not self._cell.stopped:
self._cell.receive(message, _sender)
return
else:
self._cell = None
if not self.is_local:
if self.uri.node != self.node.nid:
self.node.send_message(message, remote_ref=self, sender=_sender)
else:
self._cell = self.node.guardian.lookup_cell(self.uri)
self.is_local = True
self._cell.receive(message, _sender)
else:
if self.node and self.node.guardian:
cell = self.node.guardian.lookup_cell(self.uri)
if cell:
cell.receive(message, _sender) # do NOT set self._cell--it will never be unset and will cause a memleak
return
if ('_watched', ANY) == message:
message[1].send(('terminated', self), _sender=self)
elif (message == ('terminated', ANY) or message == ('_unwatched', ANY) or message == ('_node_down', ANY) or
message == '_stop' or message == '_kill' or message == '__done'):
pass
else:
Events.log(DeadLetter(self, message, _sender)) |
java | @Override
public SetDefaultPolicyVersionResult setDefaultPolicyVersion(SetDefaultPolicyVersionRequest request) {
request = beforeClientExecution(request);
return executeSetDefaultPolicyVersion(request);
} |
python | def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
"""Build the final response to send back to the browser"""
if 'no_template' in meta and meta['no_template']: # Just send the json back
return HttpResponse(result)
# TODO this breaks pages not using new template
# Add sidebar toggler if plugit did not add by itself
# if not "sidebar-toggler" in result:
# result = "<div class=\"menubar\"><div class=\"sidebar-toggler visible-xs\"><i class=\"ion-navicon\"></i></div></div>" + result
# render the template into the whole page
if not settings.PIAPI_STANDALONE:
return render_to_response('plugIt/' + hproject.get_plugItTemplate_display(),
{"project": hproject,
"plugit_content": result,
"plugit_menu": menu,
'context': context},
context_instance=RequestContext(request))
if proxyMode: # Force inclusion inside template
return render_to_response('plugIt/base.html',
{'plugit_content': result,
"plugit_menu": menu,
'context': context},
context_instance=RequestContext(request))
renderPlugItTemplate = 'plugItBase.html'
if settings.PIAPI_PLUGITTEMPLATE:
renderPlugItTemplate = settings.PIAPI_PLUGITTEMPLATE
return render_to_response('plugIt/' + renderPlugItTemplate,
{"plugit_content": result,
"plugit_menu": menu,
'context': context},
context_instance=RequestContext(request)) |
java | public String getViewPath(String className, String methodName, String viewName) {
if (Strings.isNotEmpty(viewName)) {
if (viewName.charAt(0) == Constants.separator) { return viewName; }
}
Profile profile = profileServie.getProfile(className);
if (null == profile) { throw new RuntimeException("no convention profile for " + className); }
StringBuilder buf = new StringBuilder();
if (profile.getViewPathStyle().equals(Constants.FULL_VIEWPATH)) {
buf.append(Constants.separator);
buf.append(profile.getFullPath(className));
} else if (profile.getViewPathStyle().equals(Constants.SIMPLE_VIEWPATH)) {
buf.append(profile.getViewPath());
// 添加中缀路径
buf.append(profile.getInfix(className));
} else if (profile.getViewPathStyle().equals(Constants.SEO_VIEWPATH)) {
buf.append(profile.getViewPath());
buf.append(Strings.unCamel(profile.getInfix(className)));
} else {
throw new RuntimeException(profile.getViewPathStyle() + " was not supported");
}
// add method mapping path
buf.append(Constants.separator);
if (Strings.isEmpty(viewName) || viewName.equals("success")) {
viewName = methodName;
}
if (null == methodViews.get(viewName)) {
buf.append(viewName);
} else {
buf.append(methodViews.get(viewName));
}
return buf.toString();
} |
java | public void marshall(DescribeEnvironmentMembershipsRequest describeEnvironmentMembershipsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeEnvironmentMembershipsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getUserArn(), USERARN_BINDING);
protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getEnvironmentId(), ENVIRONMENTID_BINDING);
protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getPermissions(), PERMISSIONS_BINDING);
protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getNextToken(), NEXTTOKEN_BINDING);
protocolMarshaller.marshall(describeEnvironmentMembershipsRequest.getMaxResults(), MAXRESULTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public static <T> ConjunctionMatcher<T> compose(Iterable<Matcher<? super T>> matchers)
{
return compose(null, matchers);
} |
python | def handleContractDetails(self, msg, end=False):
""" handles contractDetails and contractDetailsEnd """
if end:
# mark as downloaded
self._contract_details[msg.reqId]['downloaded'] = True
# move details from temp to permanent collector
self.contract_details[msg.reqId] = self._contract_details[msg.reqId]
del self._contract_details[msg.reqId]
# adjust fields if multi contract
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.contract_details[msg.reqId]["m_contractMonth"] = ""
# m_summary should hold closest expiration
expirations = self.getExpirations(self.contracts[msg.reqId], expired=0)
contract = self.contract_details[msg.reqId]["contracts"][-len(expirations)]
self.contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
self.contract_details[msg.reqId]["m_summary"] = vars(
self.contract_details[msg.reqId]["contracts"][0])
# update local db with correct contractString
for tid in self.contract_details:
oldString = self.tickerIds[tid]
newString = self.contractString(self.contract_details[tid]["contracts"][0])
if len(self.contract_details[msg.reqId]["contracts"]) > 1:
self.tickerIds[tid] = newString
if newString != oldString:
if oldString in self._portfolios:
self._portfolios[newString] = self._portfolios[oldString]
if oldString in self._positions:
self._positions[newString] = self._positions[oldString]
# fire callback
self.ibCallback(caller="handleContractDetailsEnd", msg=msg)
# exit
return
# continue...
# collect data on all contract details
# (including those with multiple expiry/strike/sides)
details = vars(msg.contractDetails)
contract = details["m_summary"]
if msg.reqId in self._contract_details:
details['contracts'] = self._contract_details[msg.reqId]["contracts"]
else:
details['contracts'] = []
details['contracts'].append(contract)
details['downloaded'] = False
self._contract_details[msg.reqId] = details
# add details to local symbol list
if contract.m_localSymbol not in self.localSymbolExpiry:
self.localSymbolExpiry[contract.m_localSymbol] = details["m_contractMonth"]
# add contract's multiple expiry/strike/sides to class collectors
contractString = self.contractString(contract)
tickerId = self.tickerId(contractString)
self.contracts[tickerId] = contract
# continue if this is a "multi" contract
if tickerId == msg.reqId:
self._contract_details[msg.reqId]["m_summary"] = vars(contract)
else:
# print("+++", tickerId, contractString)
self.contract_details[tickerId] = details.copy()
self.contract_details[tickerId]["m_summary"] = vars(contract)
self.contract_details[tickerId]["contracts"] = [contract]
# fire callback
self.ibCallback(caller="handleContractDetails", msg=msg) |
python | def find_packages_by_root_package(where):
"""Better than excluding everything that is not needed,
collect only what is needed.
"""
root_package = os.path.basename(where)
packages = [ "%s.%s" % (root_package, sub_package)
for sub_package in find_packages(where)]
packages.insert(0, root_package)
return packages |
python | def rpc_name(rpc_id):
"""Map an RPC id to a string name.
This function looks the RPC up in a map of all globally declared RPCs,
and returns a nice name string. if the RPC is not found in the global
name map, returns a generic name string such as 'rpc 0x%04X'.
Args:
rpc_id (int): The id of the RPC that we wish to look up.
Returns:
str: The nice name of the RPC.
"""
name = _RPC_NAME_MAP.get(rpc_id)
if name is None:
name = 'RPC 0x%04X' % rpc_id
return name |
java | public static Headers of(Map<String, String> headers) {
if (headers == null) throw new NullPointerException("headers == null");
// Make a defensive copy and clean it up.
String[] namesAndValues = new String[headers.size() * 2];
int i = 0;
for (Map.Entry<String, String> header : headers.entrySet()) {
if (header.getKey() == null || header.getValue() == null) {
throw new IllegalArgumentException("Headers cannot be null");
}
String name = header.getKey().trim();
String value = header.getValue().trim();
if (name.length() == 0 || name.indexOf('\0') != -1 || value.indexOf('\0') != -1) {
throw new IllegalArgumentException("Unexpected header: " + name + ": " + value);
}
namesAndValues[i] = name;
namesAndValues[i + 1] = value;
i += 2;
}
return new Headers(namesAndValues);
} |
python | def register_callback_created(self, func, serialised=True):
"""
Register a callback for resource creation. This will be called when any *new* resource
is created within your agent. If `serialised` is not set, the callbacks might arrive
in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following keys
#!python
r : R_ENTITY, R_FEED, etc # the type of resource created
lid : <name> # the local name of the resource
id : <GUID> # the global Id of the resource
epId : <GUID> # the global Id of your agent
`Note` resource types are defined [here](../Core/Const.m.html)
`Example`
#!python
def created_callback(args):
print(args)
...
client.register_callback_created(created_callback)
This would print out something like the following on creation of an R_ENTITY
#!python
OrderedDict([(u'lid', u'new_thing1'), (u'r', 1),
(u'epId', u'ffd47b75ea786f55c76e337cdc47665a'),
(u'id', u'3f11df0a09588a6a1a9732e3837765f8')]))
"""
self.__client.register_callback_created(partial(self.__callback_payload_only, func), serialised=serialised) |
java | private InternalCacheEntry<WrappedBytes, WrappedBytes> performRemove(long bucketHeadAddress, long actualAddress,
WrappedBytes key, WrappedBytes value, boolean requireReturn) {
long prevAddress = 0;
// We only use the head pointer for the first iteration
long address = bucketHeadAddress;
InternalCacheEntry<WrappedBytes, WrappedBytes> ice = null;
while (address != 0) {
long nextAddress = offHeapEntryFactory.getNext(address);
boolean removeThisAddress;
// If the actualAddress was not known, check key equality otherwise just compare with the address
removeThisAddress = actualAddress == 0 ? offHeapEntryFactory.equalsKey(address, key) : actualAddress == address;
if (removeThisAddress) {
if (value != null) {
ice = offHeapEntryFactory.fromMemory(address);
// If value doesn't match and was provided then don't remove it
if (!value.equalsWrappedBytes(ice.getValue())) {
ice = null;
break;
}
}
if (requireReturn && ice == null) {
ice = offHeapEntryFactory.fromMemory(address);
}
entryRemoved(address);
if (prevAddress != 0) {
offHeapEntryFactory.setNext(prevAddress, nextAddress);
} else {
memoryLookup.putMemoryAddress(key, nextAddress);
}
size.decrementAndGet();
break;
}
prevAddress = address;
address = nextAddress;
}
return ice;
} |
java | public static String buildHostsOnlyList(List<HostAndPort> hostAndPorts) {
StringBuilder sb = new StringBuilder();
for (HostAndPort hostAndPort : hostAndPorts) {
sb.append(hostAndPort.getHostText()).append(",");
}
if (sb.length() > 0) {
sb.delete(sb.length() - 1, sb.length());
}
return sb.toString();
} |
python | def bitset(bs, member_label=None, filename=None, directory=None, format=None,
render=False, view=False):
"""Graphviz source for the Hasse diagram of the domains' Boolean algebra."""
if member_label is None:
member_label = MEMBER_LABEL
if filename is None:
kind = 'members' if member_label else 'bits'
filename = FILENAME % (bs.__name__, kind)
dot = graphviz.Digraph(
name=bs.__name__,
comment=repr(bs),
filename=filename,
directory=directory,
format=format,
edge_attr={'dir': 'none'}
)
node_name = NAME_GETTERS[0]
if callable(member_label):
node_label = member_label
else:
node_label = LABEL_GETTERS[member_label]
for i in range(bs.supremum + 1):
b = bs.fromint(i)
name = node_name(b)
dot.node(name, node_label(b))
dot.edges((name, node_name(b & ~a)) for a in b.atoms(reverse=True))
if render or view:
dot.render(view=view) # pragma: no cover
return dot |
java | public void product(IntIntVector other) {
// TODO: Add special case for IntIntDenseVector.
for (int i=0; i<idxAfterLast; i++) {
elements[i] *= other.get(i);
}
} |
python | def export(cwd,
remote,
target=None,
user=None,
username=None,
password=None,
revision='HEAD',
*opts):
'''
Create an unversioned copy of a tree.
cwd
The path to the Subversion repository
remote : None
URL and path to file or directory checkout
target : None
The name to give the file or directory working copy
Default: svn uses the remote basename
user : None
Run svn as a user other than what the minion runs as
username : None
Connect to the Subversion server as another user
password : None
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
CLI Example:
.. code-block:: bash
salt '*' svn.export /path/to/repo svn://remote/repo
'''
opts += (remote,)
if target:
opts += (target,)
revision_args = '-r'
opts += (revision_args, six.text_type(revision),)
return _run_svn('export', cwd, user, username, password, opts) |
java | @Override
public EEnum getIfcFlowInstrumentTypeEnum() {
if (ifcFlowInstrumentTypeEnumEEnum == null) {
ifcFlowInstrumentTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(993);
}
return ifcFlowInstrumentTypeEnumEEnum;
} |
python | def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output |
java | public UpdateBuilder<T, ID> updateColumnValue(String columnName, Object value) throws SQLException {
FieldType fieldType = verifyColumnName(columnName);
if (fieldType.isForeignCollection()) {
throw new SQLException("Can't update foreign colletion field: " + columnName);
}
addUpdateColumnToList(columnName, new SetValue(columnName, fieldType, value));
return this;
} |
python | def enhance(self):
""" Function enhance
Enhance the object with new item or enhanced items
"""
self.update({'os_default_templates':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemOsDefaultTemplate)})
self.update({'operatingsystems':
SubDict(self.api, self.objName,
self.payloadObj, self.key,
SubItemOperatingSystem)}) |
java | public void sendComponent(Component componentRequest) throws TCAPSendException {
if (this.previewMode)
return;
if (this.provider.getStack().getStatisticsEnabled()) {
switch (componentRequest.getType()) {
case Invoke:
this.provider.getStack().getCounterProviderImpl().updateInvokeSentCount(this, (Invoke) componentRequest);
Invoke inv = (Invoke) componentRequest;
OperationCodeImpl oc = (OperationCodeImpl) inv.getOperationCode();
if (oc != null) {
this.provider.getStack().getCounterProviderImpl()
.updateOutgoingInvokesPerOperationCode(oc.getStringValue());
}
break;
case ReturnResult:
this.provider.getStack().getCounterProviderImpl().updateReturnResultSentCount(this);
break;
case ReturnResultLast:
this.provider.getStack().getCounterProviderImpl().updateReturnResultLastSentCount(this);
break;
case ReturnError:
this.provider.getStack().getCounterProviderImpl().updateReturnErrorSentCount(this);
ReturnError re = (ReturnError) componentRequest;
ErrorCodeImpl ec = (ErrorCodeImpl) re.getErrorCode();
if (ec != null) {
this.provider.getStack().getCounterProviderImpl().updateOutgoingErrorsPerErrorCode(ec.getStringValue());
}
break;
case Reject:
this.provider.getStack().getCounterProviderImpl().updateRejectSentCount(this);
Reject rej = (Reject) componentRequest;
ProblemImpl prob = (ProblemImpl) rej.getProblem();
if (prob != null) {
this.provider.getStack().getCounterProviderImpl().updateOutgoingRejectPerProblem(prob.getStringValue());
}
break;
}
}
try {
this.dialogLock.lock();
if (componentRequest.getType() == ComponentType.Invoke) {
InvokeImpl invoke = (InvokeImpl) componentRequest;
// check if its taken!
int invokeIndex = DialogImpl.getIndexFromInvokeId(invoke.getInvokeId());
if (this.operationsSent[invokeIndex] != null) {
throw new TCAPSendException("There is already operation with such invoke id!");
}
invoke.setState(OperationState.Pending);
invoke.setDialog(this);
// if the Invoke timeout value has not be reset by TCAP-User
// for this invocation we are setting it to the the TCAP stack
// default value
if (invoke.getTimeout() == TCAPStackImpl._EMPTY_INVOKE_TIMEOUT)
invoke.setTimeout(this.provider.getStack().getInvokeTimeout());
} else {
if (componentRequest.getType() != ComponentType.ReturnResult) {
// we are sending a response and removing invokeId from
// incomingInvokeList
this.removeIncomingInvokeId(componentRequest.getInvokeId());
}
}
this.scheduledComponentList.add(componentRequest);
} finally {
this.dialogLock.unlock();
}
} |
java | @Deprecated
public BillingInfo createOrUpdateBillingInfo(final BillingInfo billingInfo) {
final String accountCode = billingInfo.getAccount().getAccountCode();
// Unset it to avoid confusing Recurly
billingInfo.setAccount(null);
return doPUT(Account.ACCOUNT_RESOURCE + "/" + accountCode + BillingInfo.BILLING_INFO_RESOURCE,
billingInfo, BillingInfo.class);
} |
java | @Override
public DescribeComplianceByResourceResult describeComplianceByResource(DescribeComplianceByResourceRequest request) {
request = beforeClientExecution(request);
return executeDescribeComplianceByResource(request);
} |
java | @Override
@Pure
protected Class<?> findClass(final String name) throws ClassNotFoundException {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
@Override
public Class<?> run() throws ClassNotFoundException {
final String path = name.replace('.', '/').concat(".class"); //$NON-NLS-1$
final sun.misc.Resource res = DynamicURLClassLoader.this.ucp.getResource(path, false);
if (res != null) {
try {
return defineClass(name, res);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
throw new ClassNotFoundException(name);
}
}, this.acc);
} catch (java.security.PrivilegedActionException pae) {
throw (ClassNotFoundException) pae.getException();
}
} |
python | def get_account(self):
"""Get details of the current account.
:returns: an account object.
:rtype: Account
"""
api = self._get_api(iam.DeveloperApi)
return Account(api.get_my_account_info(include="limits, policies")) |
python | def uniform(self, low: float, high: float) -> float:
"""Return a random floating number in the range: low <= n <= high.
Args:
low (float): The lower bound of the random range.
high (float): The upper bound of the random range.
Returns:
float: A random float.
"""
return float(lib.TCOD_random_get_double(self.random_c, low, high)) |
python | def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False):
r"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > |
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilepath('foo.txt')
'foo.txt'
>>> pysv.validateFilepath('/spam/foo.txt')
'/spam/foo.txt'
>>> pysv.validateFilepath(r'c:\spam\foo.txt')
'c:\\spam\\foo.txt'
>>> pysv.validateFilepath(r'c:\spam\???.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'c:\\spam\\???.txt' is not a valid file path.
"""
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if (value != value.strip()) or (any(c in value for c in '*?"<>|')): # Same as validateFilename, except we allow \ and / and :
if ':' in value:
if value.find(':', 2) != -1 or not value[0].isalpha():
# For Windows: Colon can only be found at the beginning, e.g. 'C:\', or the first letter is not a letter drive.
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
return value
raise NotImplementedError() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.