language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java
|
protected CmsAccessControlEntry internalCreateAce(ResultSet res) throws SQLException {
return internalCreateAce(res, new CmsUUID(res.getString(m_sqlManager.readQuery("C_ACCESS_RESOURCE_ID_0"))));
}
|
java
|
private Variable getVariableAtNode(int index, CallStack callstack) throws UtilEvalError {
Node nameNode = null;
if (jjtGetChild(index).jjtGetNumChildren() > 0
&& (nameNode = jjtGetChild(index).jjtGetChild(0))
instanceof BSHAmbiguousName)
return callstack.top().getVariableImpl(
((BSHAmbiguousName) nameNode).text, true);
return null;
}
|
python
|
def make_response(status, headers, payload, environ):
"""This function generates an appropriate response object for this async
mode.
"""
return Response(body=payload, status=int(status.split()[0]),
headers=headers)
|
java
|
@Override
public int getShardId(final Object[] objs) {
if (objs == null || objs.length == 0) {
return 0;
}
Object input = null;
if (objs[0] == null) {
return 0;
}
if (objs[0] instanceof List) {
List<?> list = (List<?>) objs[0];
if (list.isEmpty()) {
return 0;
}
input = list.get(0);
} else {
input = objs[0];
}
/*
* if (input instanceof Long) {
* hasher.putLong((Long) input);
* } else if (input instanceof Integer) {
* hasher.putInt((Integer) input);
* } else {
* hasher.putString((String) input);
* }*/
return Murmur2Hash.hash(((String) input).getBytes(), 0);
}
|
java
|
private static String getProperty(Properties extensionProperties, String propertyName) {
if (extensionProperties.containsKey(propertyName)) {
Object value = extensionProperties.get(propertyName);
if (value != null) {
return value.toString();
}
}
return null;
}
|
python
|
def _check_not_hanging(self):
"""
Rough check that generate() will not hang or be very slow.
Raises ConfigurationError if generate() spends too much time in retry loop.
Issues a warning.warn() if there is a risk of slowdown.
"""
# (field_name, predicate, warning_msg, exception_msg)
# predicate(g) is a function that returns True if generated combination g must be rejected,
# see checks in generate()
checks = []
# ensure_unique can lead to infinite loops for some tiny erroneous configs
if self._ensure_unique:
checks.append((
_CONF.FIELD.ENSURE_UNIQUE,
self._ensure_unique,
lambda g: len(set(g)) != len(g),
'{generate} may be slow because a significant fraction of combinations contain repeating words and {field_name} is set', # noqa
'Impossible to generate with {field_name}'
))
#
# max_slug_length can easily slow down or block generation if set too small
if self._max_slug_length:
checks.append((
_CONF.FIELD.MAX_SLUG_LENGTH,
self._max_slug_length,
lambda g: sum(len(x) for x in g) + len(g) - 1 > self._max_slug_length,
'{generate} may be slow because a significant fraction of combinations exceed {field_name}={field_value}', # noqa
'Impossible to generate with {field_name}={field_value}'
))
# Perform the relevant checks for all generators, starting from 'all'
n = 100
warning_treshold = 20 # fail probability: 0.04 for 2 attempts, 0.008 for 3 attempts, etc.
for lst_id, lst in sorted(self._lists.items(), key=lambda x: '' if x is None else str(x)):
context = {'generate': 'coolname.generate({})'.format('' if lst_id is None else repr(lst_id))}
# For each generator, perform checks
for field_name, field_value, predicate, warning_msg, exception_msg in checks:
context.update({'field_name': field_name, 'field_value': field_value})
bad_count = 0
for i in range(n):
g = lst[randrange(lst.length)]
if predicate(g):
bad_count += 1
if bad_count >= n:
raise ConfigurationError(exception_msg.format(**context))
elif bad_count >= warning_treshold:
import warnings
warnings.warn(warning_msg.format(**context))
|
python
|
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
|
python
|
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
tables = db_tables(name, **connection_args)
for table in tables:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info('Optimizing table \'%s\' in db \'%s\'..', name, table)
ret = __optimize_table(name, table, **connection_args)
return ret
|
python
|
def command(self, details):
"""
Handles executing a command-based event. This starts the command
as specified in the 'commands' section of the task config.
A separate event is registered to handle the command exit. This
simply logs the exit status.
"""
log = self._params.get('log', self._discard)
if '_config_running' not in dir(self._parent) or 'commands' not in self._parent._config_running:
log.error("Event parent '%s' has no 'commands' config section", self._name)
return
commands = self._parent._config_running['commands']
if self._handler_arg not in commands:
# For now, at least, we implement a predefined command 'stop' if there is no
# explicit stop. This probably needs more work because it needs to handle
# async commands where 'stop' would translate to a SIGTERM of the pid file.
#
if self._handler_arg == 'stop':
self._parent.stop()
else:
log.error("Event parent '%s' has no '%s' command configured", self._name, self._handler_arg)
return
pid = _exec_process(commands[self._handler_arg], self._parent._context, log=log)
log.info("Forked pid %d for %s(%s)", pid, self._name, self._handler_arg)
self._parent._legion.proc_add(event_target(self._parent, 'command_exit', key=pid, arg=self._handler_arg, log=log))
|
java
|
@Override
public boolean isValid(TagData us) {
if (!Util.isSpecified(us, ITEMS)) {
if (!Util.isSpecified(us, BEGIN) || !(Util.isSpecified(us, END))) {
return false;
}
}
return true;
}
|
python
|
def add_token(self, token):
"""Add token to vocabulary.
Args:
token (str): token to add.
"""
token = self.process_token(token)
self._token_count.update([token])
|
java
|
public Class<? extends org.eclipse.xtext.parser.antlr.ITokenDefProvider> bindITokenDefProvider() {
return org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider.class;
}
|
python
|
def get_resource_ids_by_bin(self, bin_id):
"""Gets the list of ``Resource`` ``Ids`` associated with a ``Bin``.
arg: bin_id (osid.id.Id): ``Id`` of a ``Bin``
return: (osid.id.IdList) - list of related resource ``Ids``
raise: NotFound - ``bin_id`` is not found
raise: NullArgument - ``bin_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceBinSession.get_resource_ids_by_bin
id_list = []
for resource in self.get_resources_by_bin(bin_id):
id_list.append(resource.get_id())
return IdList(id_list)
|
python
|
def open(self, event):
"""Opens a file that is specified in event.attr
Parameters
----------
event.attr: Dict
\tkey filepath contains file path of file to be loaded
\tkey filetype contains file type of file to be loaded
\tFiletypes can be pys, pysu, xls
"""
filepath = event.attr["filepath"]
try:
filetype = event.attr["filetype"]
except KeyError:
try:
file_ext = filepath.strip().split(".")[-1]
except:
file_ext = None
if file_ext in ["pys", "pysu", "xls", "xlsx", "ods"]:
filetype = file_ext
else:
filetype = "pys"
type2opener = {
"pys": (Bz2AOpen, [filepath, "r"], {"main_window":
self.main_window}),
"pysu": (AOpen, [filepath, "r"], {"main_window": self.main_window})
}
if xlrd is not None:
type2opener["xls"] = \
(xlrd.open_workbook, [filepath], {"formatting_info": True})
type2opener["xlsx"] = \
(xlrd.open_workbook, [filepath], {"formatting_info": False})
if odf is not None and Ods is not None:
type2opener["ods"] = (open, [filepath, "rb"], {})
# Specify the interface that shall be used
opener, op_args, op_kwargs = type2opener[filetype]
Interface = self.type2interface[filetype]
# Set state for file open
self.opening = True
try:
with opener(*op_args, **op_kwargs) as infile:
# Make loading safe
self.approve(filepath)
if xlrd is None:
interface_errors = (ValueError, )
else:
interface_errors = (ValueError, xlrd.biffh.XLRDError)
try:
wx.BeginBusyCursor()
self.grid.Disable()
self.clear()
interface = Interface(self.grid.code_array, infile)
interface.to_code_array()
self.grid.main_window.macro_panel.codetext_ctrl.SetText(
self.grid.code_array.macros)
except interface_errors, err:
post_command_event(self.main_window, self.StatusBarMsg,
text=str(err))
finally:
self.grid.GetTable().ResetView()
post_command_event(self.main_window, self.ResizeGridMsg,
shape=self.grid.code_array.shape)
self.grid.Enable()
wx.EndBusyCursor()
# Execute macros
self.main_window.actions.execute_macros()
self.grid.GetTable().ResetView()
self.grid.ForceRefresh()
# File sucessfully opened. Approve again to show status.
self.approve(filepath)
# Change current directory to file directory
filedir = os.path.dirname(filepath)
os.chdir(filedir)
except IOError, err:
txt = _("Error opening file {filepath}:").format(filepath=filepath)
txt += " " + str(err)
post_command_event(self.main_window, self.StatusBarMsg, text=txt)
return False
except EOFError:
# Normally on empty grids
pass
finally:
# Unset state for file open
self.opening = False
|
java
|
public boolean isInDiskCacheSync(final Uri uri, final ImageRequest.CacheChoice cacheChoice) {
ImageRequest imageRequest = ImageRequestBuilder
.newBuilderWithSource(uri)
.setCacheChoice(cacheChoice)
.build();
return isInDiskCacheSync(imageRequest);
}
|
java
|
private void computeV( DMatrixRMaj h1 ,DMatrixRMaj h2 , DMatrixRMaj v )
{
double h1x = h1.get(0,0);
double h1y = h1.get(1,0);
double h1z = h1.get(2,0);
double h2x = h2.get(0,0);
double h2y = h2.get(1,0);
double h2z = h2.get(2,0);
v.set(0,0,h1x*h2x);
v.set(0,1,h1x*h2y+h1y*h2x);
v.set(0,2,h1y*h2y);
v.set(0,3,h1z*h2x+h1x*h2z);
v.set(0,4,h1z*h2y+h1y*h2z);
v.set(0,5,h1z*h2z);
}
|
python
|
def delete_collection_namespaced_persistent_volume_claim(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_persistent_volume_claim # noqa: E501
delete collection of PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_persistent_volume_claim(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_persistent_volume_claim_with_http_info(namespace, **kwargs) # noqa: E501
else:
(data) = self.delete_collection_namespaced_persistent_volume_claim_with_http_info(namespace, **kwargs) # noqa: E501
return data
|
python
|
def rc4(data, key):
"""RC4 encryption and decryption method."""
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
out.append(chr(ord(ch) ^ S[(S[i] + S[j]) % 256]))
return "".join(out)
|
java
|
public Producer<CloseableReference<PooledByteBuffer>>
getNetworkFetchEncodedImageProducerSequence() {
synchronized (this) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence");
}
if (mNetworkEncodedImageProducerSequence == null) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection(
"ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence:init");
}
mNetworkEncodedImageProducerSequence =
new RemoveImageTransformMetaDataProducer(
getBackgroundNetworkFetchToEncodedMemorySequence());
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
if (FrescoSystrace.isTracing()) {
FrescoSystrace.endSection();
}
}
return mNetworkEncodedImageProducerSequence;
}
|
python
|
def decode(self, text: str, prefix: str = "@") -> str:
"""Decode <@id> and <!alias> into @username."""
def callback(match: Match) -> str:
m = match.groupdict()
if m["userid"]:
user = self.users.get(m["userid"], None)
if user is None:
username = m["userid"]
else:
username = user.name
elif m["alias"]:
username = m["alias"]
return f"{prefix}{username}"
return self.decode_re.sub(callback, text)
|
java
|
@Override
public void visitCode(Code obj) {
Method m = getMethod();
String sig = m.getSignature();
if (!Values.SIG_VOID.equals(SignatureUtils.getReturnSignature(sig))) {
state = State.SEEN_NOTHING;
branchTargets.clear();
CodeException[] ces = obj.getExceptionTable();
catchTargets.clear();
stack.resetForMethodEntry(this);
for (CodeException ce : ces) {
if (ce.getCatchType() != 0) {
catchTargets.set(ce.getHandlerPC());
}
}
super.visitCode(obj);
}
}
|
python
|
def allowDeletion(store, tableClass, comparisonFactory):
"""
Returns a C{bool} indicating whether deletion of an item or items of a
particular item type should be allowed to proceed.
@param tableClass: An L{Item} subclass.
@param comparison: A one-argument callable taking an attribute and
returning an L{iaxiom.IComparison} describing the items to
collect.
@return: A C{bool} indicating whether deletion should be allowed.
"""
for cascadingAttr in (_disallows.get(tableClass, []) +
_disallows.get(None, [])):
for cascadedItem in store.query(cascadingAttr.type,
comparisonFactory(cascadingAttr),
limit=1):
return False
return True
|
python
|
def nphase_border(im, include_diagonals=False):
r'''
Identifies the voxels in regions that border *N* other regions.
Useful for finding triple-phase boundaries.
Parameters
----------
im : ND-array
An ND image of the porous material containing discrete values in the
pore space identifying different regions. e.g. the result of a
snow-partition
include_diagonals : boolean
When identifying bordering pixels (2D) and voxels (3D) include those
shifted along more than one axis
Returns
-------
image : ND-array
A copy of ``im`` with voxel values equal to the number of uniquely
different bordering values
'''
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
# Get dimension of image
ndim = len(np.shape(im))
if ndim not in [2, 3]:
raise NotImplementedError("Function only works for 2d and 3d images")
# Pad image to handle edges
im = np.pad(im, pad_width=1, mode='edge')
# Stack rolled images for each neighbor to be inspected
stack = _make_stack(im, include_diagonals)
# Sort the stack along the last axis
stack.sort()
out = np.ones_like(im)
# Run through stack recording when neighbor id changes
# Number of changes is number of unique bordering regions
for k in range(np.shape(stack)[ndim])[1:]:
if ndim == 2:
mask = stack[:, :, k] != stack[:, :, k-1]
elif ndim == 3:
mask = stack[:, :, :, k] != stack[:, :, :, k-1]
out += mask
# Un-pad
if ndim == 2:
return out[1:-1, 1:-1].copy()
else:
return out[1:-1, 1:-1, 1:-1].copy()
|
java
|
public static <T, X extends Throwable> T throwThe(X e) throws X {
if (e == null) {
throw new ExceptionNotHandled("Cannot throw null exception.");
}
throw e;
}
|
python
|
def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
|
python
|
def Serialize(self, writer):
"""
Serialize object.
Args:
writer (neo.IO.BinaryWriter):
"""
self.SerializeUnsigned(writer)
writer.WriteSerializableArray(self.scripts)
|
python
|
def modify_subscription_status(netid, subscription_code, status):
"""
Post a subscription 'modify' action for the given netid
and subscription_code
"""
url = _netid_subscription_url(netid, subscription_code)
body = {
'action': 'modify',
'value': str(status)
}
response = post_resource(url, json.dumps(body))
return _json_to_subscriptions(response)
|
python
|
def get(cls, bucket, key, upload_id, with_completed=False):
"""Fetch a specific multipart object."""
q = cls.query.filter_by(
upload_id=upload_id,
bucket_id=as_bucket_id(bucket),
key=key,
)
if not with_completed:
q = q.filter(cls.completed.is_(False))
return q.one_or_none()
|
python
|
def _put_task_in_run_log(self, task_name):
""" Initializes the run log task entry for this task. """
logger.debug('Job {0} initializing run log entry for task {1}'.format(self.name, task_name))
data = {'start_time': datetime.utcnow(),
'command': self.tasks[task_name].command}
self.run_log['tasks'][task_name] = data
|
java
|
public static SSLSocketFactory getPinnedCertSslSocketFactory(Context context,
int keyStoreRawResId,
String keyStorePassword) {
InputStream in = null;
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the keystore from raw resource
in = context.getResources().openRawResource(keyStoreRawResId);
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, keyStorePassword.toCharArray());
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(trusted);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
Logger.e(e.getMessage());
}
}
}
|
java
|
public double getDouble(String attrName) {
BigDecimal bd = getNumber(attrName);
if (bd == null)
throw new NumberFormatException
("value of " + attrName + " is null");
return bd.doubleValue();
}
|
java
|
public List<Class<?>> getClasses(final String pkg, boolean recursive, final Predicate<Class<?>> predicate)
{
final long started = System.currentTimeMillis();
try
{
return filter(finder.findClassesInPackage(pkg, recursive), predicate);
}
finally
{
final long finished = System.currentTimeMillis();
searchTime.addAndGet(finished - started);
if (log.isTraceEnabled())
log.trace("getClasses " +
pkg +
" with predicate=" +
predicate +
" returned in " +
(finished - started) +
" ms");
}
}
|
python
|
def on_clear_button_pressed(self):
"""
PyQt slot called when the user hits the "Clear" button.
Removes any set custom module search path.
"""
self.path = None
self.clear_button.setEnabled(False)
self.folder_label.setText(self.initial_folder_label_text)
logger.debug("User selects to clear the custom module search path.")
|
java
|
public static Date parseToDate(final String date, final String format) throws ParseException
{
final DateFormat df = new SimpleDateFormat(format);
Date parsedDate = null;
parsedDate = df.parse(date);
return parsedDate;
}
|
java
|
public static EdgeRcClientCredentialProvider fromEdgeRc(File file, String section)
throws ConfigurationException, IOException {
Objects.requireNonNull(file, "file cannot be null");
return fromEdgeRc(new FileReader(file), section);
}
|
python
|
def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs):
"""
Initializes a NEBAnalysis object from a directory of a NEB run.
Note that OUTCARs must be present in all image directories. For the
terminal OUTCARs from relaxation calculations, you can specify the
locations using relaxation_dir. If these are not specified, the code
will attempt to look for the OUTCARs in 00 and 0n directories,
followed by subdirs "start", "end" or "initial", "final" in the
root_dir. These are just some typical conventions used
preferentially in Shyue Ping's MAVRL research group. For the
non-terminal points, the CONTCAR is read to obtain structures. For
terminal points, the POSCAR is used. The image directories are
assumed to be the only directories that can be resolved to integers.
E.g., "00", "01", "02", "03", "04", "05", "06". The minimum
sub-directory structure that can be parsed is of the following form (
a 5-image example is shown):
00:
- POSCAR
- OUTCAR
01, 02, 03, 04, 05:
- CONTCAR
- OUTCAR
06:
- POSCAR
- OUTCAR
Args:
root_dir (str): Path to the root directory of the NEB calculation.
relaxation_dirs (tuple): This specifies the starting and ending
relaxation directories from which the OUTCARs are read for the
terminal points for the energies.
Returns:
NEBAnalysis object.
"""
neb_dirs = []
for d in os.listdir(root_dir):
pth = os.path.join(root_dir, d)
if os.path.isdir(pth) and d.isdigit():
i = int(d)
neb_dirs.append((i, pth))
neb_dirs = sorted(neb_dirs, key=lambda d: d[0])
outcars = []
structures = []
# Setup the search sequence for the OUTCARs for the terminal
# directories.
terminal_dirs = []
if relaxation_dirs is not None:
terminal_dirs.append(relaxation_dirs)
terminal_dirs.append((neb_dirs[0][1], neb_dirs[-1][1]))
terminal_dirs.append([os.path.join(root_dir, d)
for d in ["start", "end"]])
terminal_dirs.append([os.path.join(root_dir, d)
for d in ["initial", "final"]])
for i, d in neb_dirs:
outcar = glob.glob(os.path.join(d, "OUTCAR*"))
contcar = glob.glob(os.path.join(d, "CONTCAR*"))
poscar = glob.glob(os.path.join(d, "POSCAR*"))
terminal = i == 0 or i == neb_dirs[-1][0]
if terminal:
for ds in terminal_dirs:
od = ds[0] if i == 0 else ds[1]
outcar = glob.glob(os.path.join(od, "OUTCAR*"))
if outcar:
outcar = sorted(outcar)
outcars.append(Outcar(outcar[-1]))
break
else:
raise ValueError("OUTCAR cannot be found for terminal "
"point %s" % d)
structures.append(Poscar.from_file(poscar[0]).structure)
else:
outcars.append(Outcar(outcar[0]))
structures.append(Poscar.from_file(contcar[0]).structure)
return NEBAnalysis.from_outcars(outcars, structures, **kwargs)
|
java
|
public void restoreExistingRepository(RepositoryBackupChainLog rblog, RepositoryEntry repositoryEntry,
boolean asynchronous) throws BackupOperationException, BackupConfigurationException
{
try
{
// repository should be existed
repoService.getRepository(repositoryEntry.getName());
}
catch (RepositoryException e)
{
throw new RepositoryRestoreExeption("Repository \"" + repositoryEntry.getName() + "\" should be existed", e);
}
catch (RepositoryConfigurationException e)
{
throw new RepositoryRestoreExeption("Repository \"" + repositoryEntry.getName() + "\" should be existed", e);
}
Map<String, File> workspacesMapping = new HashedMap();
Map<String, BackupChainLog> backups = new HashedMap();
for (String path : rblog.getWorkspaceBackupsInfo())
{
BackupChainLog bLog = new BackupChainLog(new File(path));
backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
}
if (!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName()))
{
throw new BackupConfigurationException(
"The backup to system workspace is not system workspace in repository entry: " + rblog.getSystemWorkspace()
+ " is not equal " + repositoryEntry.getSystemWorkspaceName());
}
if (backups.size() != repositoryEntry.getWorkspaceEntries().size())
{
throw new BackupConfigurationException(
"The repository entry is contains more or less workspace entry than backups of workspace in "
+ rblog.getLogFilePath());
}
for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries())
{
if (!backups.containsKey(wsEntry.getName()))
{
throw new BackupConfigurationException("The workspace '" + wsEntry.getName() + "' is not found in backup "
+ rblog.getLogFilePath());
}
else
{
workspacesMapping.put(wsEntry.getName(), new File(backups.get(wsEntry.getName()).getLogFilePath()));
}
}
// check if we have deal with RDBMS backup
boolean isSameConfigRestore = false;
try
{
BackupChainLog bclog = new BackupChainLog(workspacesMapping.get(repositoryEntry.getWorkspaceEntries().get(0).getName()));
if (ClassLoading.forName(bclog.getFullBackupType(), this)
.equals(org.exoplatform.services.jcr.ext.backup.impl.rdbms.FullBackupJob.class))
{
String newConf = new JsonGeneratorImpl().createJsonObject(repositoryEntry).toString();
String currnetConf =
new JsonGeneratorImpl().createJsonObject(
repoService.getRepository(repositoryEntry.getName()).getConfiguration()).toString();
isSameConfigRestore = newConf.equals(currnetConf);
}
}
catch (JsonException e)
{
this.LOG.error("Can't get JSON object from wokrspace configuration", e);
}
catch (RepositoryException e)
{
this.LOG.error(e);
}
catch (RepositoryConfigurationException e)
{
this.LOG.error(e);
}
catch (ClassNotFoundException e)
{
this.LOG.error(e);
}
JobRepositoryRestore jobExistedRepositoryRestore =
isSameConfigRestore ? new JobExistingRepositorySameConfigRestore(repoService, this, repositoryEntry,
workspacesMapping, new File(rblog.getLogFilePath())) : new JobExistingRepositoryRestore(repoService, this,
repositoryEntry, workspacesMapping, new File(rblog.getLogFilePath()));
restoreRepositoryJobs.add(jobExistedRepositoryRestore);
if (asynchronous)
{
jobExistedRepositoryRestore.start();
}
else
{
jobExistedRepositoryRestore.restore();
}
}
|
python
|
def repodata_files(self, channels=None):
"""
Return the repodata paths based on `channels` and the `data_directory`.
There is no check for validity here.
"""
if channels is None:
channels = self.conda_get_condarc_channels()
repodata_urls = self._set_repo_urls_from_channels(channels)
repopaths = []
for repourl in repodata_urls:
fullpath = os.sep.join([self._repo_url_to_path(repourl)])
repopaths.append(fullpath)
return repopaths
|
java
|
public final Queue purgeQueue(String name) {
PurgeQueueRequest request = PurgeQueueRequest.newBuilder().setName(name).build();
return purgeQueue(request);
}
|
java
|
public FavoriteLogCB acceptPK(String id) {
assertObjectNotNull("id", id);
BsFavoriteLogCB cb = this;
cb.query().docMeta().setId_Equal(id);
return (FavoriteLogCB) this;
}
|
java
|
public static List<String> extractParameters(String rawRoute) {
List<String> list = new ArrayList<>();
Matcher m = PATH_PARAMETER_REGEX.matcher(rawRoute);
while (m.find()) {
if (m.group(1).indexOf('<') != -1) {
// Regex case name<reg>
list.add(m.group(1).substring(0, m.group(1).indexOf('<')));
} else if (m.group(1).indexOf('*') != -1) {
// Star case name*
list.add(m.group(1).substring(0, m.group(1).indexOf('*')));
} else if (m.group(1).indexOf('+') != -1) {
// Plus case name+
list.add(m.group(1).substring(0, m.group(1).indexOf('+')));
} else {
// Basic case (name)
list.add(m.group(1));
}
}
return list;
}
|
java
|
private void skipPayload(int numBytes)
throws IOException
{
while (true) {
int bufferRemaining = buffer.size() - position;
if (bufferRemaining >= numBytes) {
position += numBytes;
return;
}
else {
position += bufferRemaining;
numBytes -= bufferRemaining;
}
nextBuffer();
}
}
|
java
|
public Observable<String> supportedVpnDevicesAsync(String resourceGroupName, String virtualNetworkGatewayName) {
return supportedVpnDevicesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
|
python
|
def includeme(configurator):
"""
Add yaml configuration utilities.
:param pyramid.config.Configurator configurator: pyramid's app configurator
"""
settings = configurator.registry.settings
# lets default it to running path
yaml_locations = settings.get('yaml.location',
settings.get('yml.location', os.getcwd()))
configurator.add_directive('config_defaults', config_defaults)
configurator.config_defaults(yaml_locations)
# reading yml configuration
if configurator.registry['config']:
config = configurator.registry['config']
log.debug('Yaml config created')
# extend settings object
if 'configurator' in config and config.configurator:
_extend_settings(settings, config.configurator)
# run include's
if 'include' in config:
_run_includemes(configurator, config.include)
# let's calla a convenience request method
configurator.add_request_method(
lambda request: request.registry['config'],
name='config', property=True
)
|
java
|
public void addRemoteDestination(
String name,
Set<String> queuePointLocalizingSet,
DestinationDefinition destinationDefinition) throws SIResourceException, SIIncorrectCallException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "addRemoteDestination", new Object[] { name, destinationDefinition });
// Try to add the remote destination.
try
{
createRemoteDestination(destinationDefinition, queuePointLocalizingSet);
} catch (SIIncorrectCallException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addRemoteDestination", e);
throw e;
} catch (SIResourceException e)
{
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addRemoteDestination", e);
throw e;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "addRemoteDestination");
}
|
python
|
def display(self, xaxis, alpha, new=True):
"""
E.display(xaxis, alpha = .8)
:Arguments: xaxis, alpha
Plots the CI region on the current figure, with respect to
xaxis, at opacity alpha.
:Note: The fill color of the envelope will be self.mass
on the grayscale.
"""
if new:
figure()
if self.ndim == 1:
if self.mass > 0.:
x = concatenate((xaxis, xaxis[::-1]))
y = concatenate((self.lo, self.hi[::-1]))
fill(
x,
y,
facecolor='%f' % self.mass,
alpha=alpha,
label=(
'centered CI ' + str(
self.mass)))
else:
pyplot(
xaxis,
self.value,
'k-',
alpha=alpha,
label=(
'median'))
else:
if self.mass > 0.:
subplot(1, 2, 1)
contourf(xaxis[0], xaxis[1], self.lo, cmap=cm.bone)
colorbar()
subplot(1, 2, 2)
contourf(xaxis[0], xaxis[1], self.hi, cmap=cm.bone)
colorbar()
else:
contourf(xaxis[0], xaxis[1], self.value, cmap=cm.bone)
colorbar()
|
python
|
def _normalize_roots(file_roots):
'''
Normalize file or pillar roots.
'''
for saltenv, dirs in six.iteritems(file_roots):
normalized_saltenv = six.text_type(saltenv)
if normalized_saltenv != saltenv:
file_roots[normalized_saltenv] = file_roots.pop(saltenv)
if not isinstance(dirs, (list, tuple)):
file_roots[normalized_saltenv] = []
file_roots[normalized_saltenv] = \
_expand_glob_path(file_roots[normalized_saltenv])
return file_roots
|
java
|
public final void elementValueArrayInitializer() throws RecognitionException {
int elementValueArrayInitializer_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 70) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:5: ( '{' ( elementValue ( ',' elementValue )* )? '}' )
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:7: '{' ( elementValue ( ',' elementValue )* )? '}'
{
match(input,121,FOLLOW_121_in_elementValueArrayInitializer2443); if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:11: ( elementValue ( ',' elementValue )* )?
int alt93=2;
int LA93_0 = input.LA(1);
if ( ((LA93_0 >= CharacterLiteral && LA93_0 <= DecimalLiteral)||LA93_0==FloatingPointLiteral||(LA93_0 >= HexLiteral && LA93_0 <= Identifier)||(LA93_0 >= OctalLiteral && LA93_0 <= StringLiteral)||LA93_0==29||LA93_0==36||(LA93_0 >= 40 && LA93_0 <= 41)||(LA93_0 >= 44 && LA93_0 <= 45)||LA93_0==53||LA93_0==58||LA93_0==65||LA93_0==67||(LA93_0 >= 70 && LA93_0 <= 71)||LA93_0==77||(LA93_0 >= 79 && LA93_0 <= 80)||LA93_0==82||LA93_0==85||LA93_0==92||LA93_0==94||(LA93_0 >= 97 && LA93_0 <= 98)||LA93_0==105||LA93_0==108||LA93_0==111||LA93_0==115||LA93_0==118||LA93_0==121||LA93_0==126) ) {
alt93=1;
}
switch (alt93) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:12: elementValue ( ',' elementValue )*
{
pushFollow(FOLLOW_elementValue_in_elementValueArrayInitializer2446);
elementValue();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:25: ( ',' elementValue )*
loop92:
while (true) {
int alt92=2;
int LA92_0 = input.LA(1);
if ( (LA92_0==43) ) {
alt92=1;
}
switch (alt92) {
case 1 :
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:26: ',' elementValue
{
match(input,43,FOLLOW_43_in_elementValueArrayInitializer2449); if (state.failed) return;
pushFollow(FOLLOW_elementValue_in_elementValueArrayInitializer2451);
elementValue();
state._fsp--;
if (state.failed) return;
}
break;
default :
break loop92;
}
}
}
break;
}
match(input,125,FOLLOW_125_in_elementValueArrayInitializer2458); if (state.failed) return;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
if ( state.backtracking>0 ) { memoize(input, 70, elementValueArrayInitializer_StartIndex); }
}
}
|
java
|
public boolean updateImportTask(int importJobId, int importTaskId,
AbstractRESTEntity updateTaskEntity) throws Exception {
LOG.debug("Updating the import task " + importTaskId + " in job " + importJobId +
" with " + updateTaskEntity);
Response httpResponse = HttpUtil.put(
this.addEndPoint(importJobId + "/tasks/" + importTaskId),
this.asJSON(updateTaskEntity),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully updated the task " + importTaskId);
} else {
LOG.error("Unknown error occured while updating the task " + importTaskId);
}
return success;
}
|
python
|
def connect_get_namespaced_pod_portforward(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_portforward # noqa: E501
connect GET requests to portforward of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_portforward(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the PodPortForwardOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param int ports: List of ports to forward Required when using WebSockets
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.connect_get_namespaced_pod_portforward_with_http_info(name, namespace, **kwargs) # noqa: E501
else:
(data) = self.connect_get_namespaced_pod_portforward_with_http_info(name, namespace, **kwargs) # noqa: E501
return data
|
java
|
public static synchronized void register(final String serviceName,
final Callable<Class< ? >> factory) {
if ( serviceName == null ) {
throw new IllegalArgumentException( "serviceName cannot be null" );
}
if ( factory != null ) {
if ( factories == null ) {
factories = new HashMap<String, List<Callable<Class< ? >>>>();
}
List<Callable<Class< ? >>> l = factories.get( serviceName );
if ( l == null ) {
l = new ArrayList<Callable<Class< ? >>>();
factories.put( serviceName,
l );
}
l.add( factory );
}
}
|
java
|
@SuppressWarnings("unchecked")
public static <T> T unwrap(final T entity) {
if (isProxy(entity)) {
return (T) asProxy(entity).__unwrap();
}
return entity;
}
|
python
|
def filter_installed_packages(packages):
"""Return a list of packages that require installation."""
yb = yum.YumBase()
package_list = yb.doPackageLists()
temp_cache = {p.base_package_name: 1 for p in package_list['installed']}
_pkgs = [p for p in packages if not temp_cache.get(p, False)]
return _pkgs
|
java
|
public static CmsUgcSessionQueue createQueue(CmsUgcConfiguration config) {
CmsUgcSessionQueue queue = new CmsUgcSessionQueue(
config.needsQueue(),
config.getQueueInterval().isPresent() ? config.getQueueInterval().get().longValue() : 0,
config.getMaxQueueLength().isPresent() ? config.getMaxQueueLength().get().intValue() : Integer.MAX_VALUE);
return queue;
}
|
java
|
@Nonnull
public static String rescaleImageAndEncodeAsBase64(@Nonnull Image image, final int maxSize) throws IOException {
final int width = image.getWidth(null);
final int height = image.getHeight(null);
final int maxImageSideSize = maxSize > 0 ? maxSize : Math.max(width, height);
final float imageScale = width > maxImageSideSize || height > maxImageSideSize ? (float) maxImageSideSize / (float) Math.max(width, height) : 1.0f;
if (!(image instanceof RenderedImage) || Float.compare(imageScale, 1.0f) != 0) {
final int swidth;
final int sheight;
if (Float.compare(imageScale, 1.0f) == 0) {
swidth = width;
sheight = height;
} else {
swidth = Math.round(imageScale * width);
sheight = Math.round(imageScale * height);
}
final BufferedImage buffer = new BufferedImage(swidth, sheight, BufferedImage.TYPE_INT_ARGB);
final Graphics2D gfx = (Graphics2D) buffer.createGraphics();
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gfx.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
gfx.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
gfx.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
gfx.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
gfx.drawImage(image, AffineTransform.getScaleInstance(imageScale, imageScale), null);
gfx.dispose();
image = buffer;
}
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
if (!ImageIO.write((RenderedImage) image, "png", bos)) {
throw new IOException("Can't encode image as PNG");
}
} finally {
IOUtils.closeQuietly(bos);
}
return Utils.base64encode(bos.toByteArray());
}
|
java
|
public String getIndexTextForClassifications(String guid, List<AtlasClassification> classifications) throws AtlasBaseException {
String ret = null;
AtlasEntityWithExtInfo entityWithExtInfo = getAndCacheEntity(guid);
if (entityWithExtInfo != null) {
StringBuilder sb = new StringBuilder();
if (CollectionUtils.isNotEmpty(classifications)) {
for (AtlasClassification classification : classifications) {
sb.append(classification.getTypeName()).append(FULL_TEXT_DELIMITER);
mapAttributes(classification.getAttributes(), entityWithExtInfo, sb, new HashSet<String>());
}
}
ret = sb.toString();
}
if (LOG.isDebugEnabled()) {
LOG.debug("FullTextMapperV2.map({}): {}", guid, ret);
}
return ret;
}
|
java
|
@Override protected void initGraphics() {
super.initGraphics();
graphicListener = (o, ov, nv) -> { if (nv != null) { graphicContainer.getChildren().setAll(tile.getGraphic()); }};
titleText = new Text();
titleText.setFill(tile.getTitleColor());
Helper.enableNode(titleText, !tile.getTitle().isEmpty());
text = new Text(tile.getText());
text.setFill(tile.getTextColor());
Helper.enableNode(text, tile.isTextVisible());
graphicContainer = new StackPane();
graphicContainer.setMinSize(size * 0.9, tile.isTextVisible() ? size * 0.72 : size * 0.795);
graphicContainer.setMaxSize(size * 0.9, tile.isTextVisible() ? size * 0.72 : size * 0.795);
graphicContainer.setPrefSize(size * 0.9, tile.isTextVisible() ? size * 0.72 : size * 0.795);
if (null != tile.getGraphic()) graphicContainer.getChildren().setAll(tile.getGraphic());
getPane().getChildren().addAll(titleText, graphicContainer, text);
}
|
java
|
public static String getShipType(BigInteger ts) {
if (ts == null)
return null;
else
return getShipType(ts.intValue());
}
|
python
|
def where(self, predicate):
'''Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call where() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("where() parameter predicate={predicate} is not "
"callable".format(predicate=repr(predicate)))
return self._create(ifilter(predicate, self))
|
python
|
def get_highest_build_tool(sdk_version=None):
"""
Gets the highest build tool version based on major version sdk version.
:param sdk_version(int) - sdk version to be used as the marjor build tool version context.
Returns:
A string containg the build tool version (default is 23.0.2 if none is found)
"""
if sdk_version is None:
sdk_version = config.sdk_version
android_home = os.environ.get('AG_MOBILE_SDK', os.environ.get('ANDROID_HOME'))
build_tool_folder = '%s/build-tools' % android_home
folder_list = os.listdir(build_tool_folder)
versions = [folder for folder in folder_list if folder.startswith('%s.' % sdk_version)]
if len(versions) == 0:
return config.build_tool_version
return versions[::-1][0]
|
python
|
def on_add(self, item):
"""Convert to pseuso acces"""
super(Tels, self).on_add(list_views.PseudoAccesCategorie(item))
|
java
|
@Override
public CreateRegexPatternSetResult createRegexPatternSet(CreateRegexPatternSetRequest request) {
request = beforeClientExecution(request);
return executeCreateRegexPatternSet(request);
}
|
java
|
public final String evaluateString( Message message ) throws JMSException
{
Object value = evaluate(message);
if (value == null)
return null;
if (value instanceof String)
return (String)value;
throw new FFMQException("Expected a string but got : "+value.toString(),"INVALID_SELECTOR_EXPRESSION");
}
|
java
|
private List<File> getUninstallDirs() {
List<File> result = new ArrayList<File>();
File x = new File(name);
if (!x.isDirectory()) x = x.getParentFile();
if (x.isDirectory()) result.add(x);
result.add(eclipseIniPath.getParentFile());
return result;
}
|
java
|
public java.util.List<String> getAlarmActions() {
if (alarmActions == null) {
alarmActions = new com.amazonaws.internal.SdkInternalList<String>();
}
return alarmActions;
}
|
python
|
def clip_extents(self):
"""Computes a bounding box in user coordinates
covering the area inside the current clip.
:return:
A ``(x1, y1, x2, y2)`` tuple of floats:
the left, top, right and bottom of the resulting extents,
respectively.
"""
extents = ffi.new('double[4]')
cairo.cairo_clip_extents(
self._pointer, extents + 0, extents + 1, extents + 2, extents + 3)
self._check_status()
return tuple(extents)
|
java
|
public static int lastIndexOfAny(String str, String[] searchStrs) {
if ((str == null) || (searchStrs == null)) {
return -1;
}
int sz = searchStrs.length;
int ret = -1;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.lastIndexOf(search);
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
|
python
|
def url_params(request, except_params=None, as_is=False):
"""
create string with GET-params of request
usage example:
c['sort_url'] = url_params(request, except_params=('sort',))
...
<a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a>
"""
if not request.GET:
return ''
params = []
for key, value in request.GET.items():
if except_params and key not in except_params:
for v in request.GET.getlist(key):
params.append('%s=%s' % (key, urlquote(v)))
if as_is:
str_params = '?' + '&'.join(params)
else:
str_params = '?' + '&'.join(params)
str_params = urlquote(str_params)
return mark_safe(str_params)
|
java
|
@Override
public DescribeImportSnapshotTasksResult describeImportSnapshotTasks(DescribeImportSnapshotTasksRequest request) {
request = beforeClientExecution(request);
return executeDescribeImportSnapshotTasks(request);
}
|
java
|
private int processIntDocument(int termIndex, int[] document,
Matrix contextMatrix,
int rowStart,
BitSet featuresForTerm) {
int contexts = 0;
for (int i = 0; i < document.length; ++i) {
int curToken = document[i];
// Skip processing tokens that are not the current focus
if (curToken != termIndex)
continue;
// Buffer the count of how many times each feature appeared in the
// context.
SparseArray<Integer> contextCounts = new SparseHashArray<Integer>();
// Process all the tokes to the left (prior) to the current token;
for (int left = Math.max(i - contextWindowSize, 0);
left < i; ++left) {
// NOTE: this token value could be -1 if the token's original
// text was filtered out from the corpus, i.e. was EMPTY_TOKEN
int token = document[left];
// Only count co-occurrences that are valid features for the
// current token
if (token >= 0 && featuresForTerm.get(token)) {
Integer count = contextCounts.get(token);
contextCounts.set(token, (count == null) ? 1 : count + 1);
}
}
// Process all the tokes to the right (after) to the current token;
int end = Math.min(i + contextWindowSize, document.length);
for (int right = i + 1; right < end; ++right) {
int token = document[right];
// Only count co-occurrences that are valid features for the
// current token
if (token >= 0 && featuresForTerm.get(token)) {
Integer count = contextCounts.get(token);
contextCounts.set(token, (count == null) ? 1 : count + 1);
}
}
// Each word in the document represents a new context, so the
// specific context instance can be determined from the current word
// and the number of previously process words
int curContext = rowStart + contexts;
for (int feat : contextCounts.getElementIndices()) {
//System.out.println("setting row: " + curContext + ", col: " + feat);
contextMatrix.set(curContext, feat, contextCounts.get(feat));
}
// If the current token wasn't skipped, indicate that another
// context was seen
contexts++;
}
return contexts;
}
|
python
|
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r. Defaults require about 16 MiB.
Time taken is proportional to N*p. Defaults take <100ms of a recent x86.
The last one differs from libscrypt defaults, but matches the 'interactive'
work factor from the original paper. For long term storage where runtime of
key derivation is not a problem, you could use 16 as in libscrypt or better
yet increase N if memory is plentiful.
"""
check_args(password, salt, N, r, p, olen)
out = ctypes.create_string_buffer(olen)
ret = _libscrypt_scrypt(password, len(password), salt, len(salt),
N, r, p, out, len(out))
if ret:
raise ValueError
return out.raw
|
java
|
public RemoteTask createRemoteTask(String strServer, String strRemoteApp, String strUserID, String strPassword)
{
RemoteTask remoteTask = super.createRemoteTask(strServer, strRemoteApp, strUserID, strPassword);
return remoteTask;
}
|
java
|
public void setYoaBase(Integer newYoaBase) {
Integer oldYoaBase = yoaBase;
yoaBase = newYoaBase;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.MEASUREMENT_UNITS__YOA_BASE, oldYoaBase, yoaBase));
}
|
java
|
public static dnskey[] get(nitro_service service, String keyname[]) throws Exception{
if (keyname !=null && keyname.length>0) {
dnskey response[] = new dnskey[keyname.length];
dnskey obj[] = new dnskey[keyname.length];
for (int i=0;i<keyname.length;i++) {
obj[i] = new dnskey();
obj[i].set_keyname(keyname[i]);
response[i] = (dnskey) obj[i].get_resource(service);
}
return response;
}
return null;
}
|
java
|
private static String containsDuplicates(List<BindingTuple> tuples) {
Set<String> sigs = new HashSet<String>();
for (BindingTuple tuple : tuples) {
if (!sigs.add(printSig(tuple.parameterized))) return printSig(tuple.parameterized);
}
return null;
}
|
java
|
@Override
public List<CommerceAddressRestriction> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
|
java
|
public static void add(Element parent, NodeList list) {
int size;
int i;
size = list.getLength();
for (i = 0; i < size; i++) {
addNode(parent, list.item(i));
}
}
|
java
|
static Iterator<MutableLongTuple> wrappingIterator(
LongTuple bounds, Iterator<? extends MutableLongTuple> delegate)
{
return wrappingIteratorInternal(LongTuples.copy(bounds), delegate);
}
|
python
|
def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return None
if description[:7] == 'ImageJ=':
return description
return None
|
java
|
@Override
public final void backupDatabase(final String pDbName) throws Exception {
String dbPath = this.databaseDir + File.separator + pDbName + ".sqlite";
File dbFile = new File(dbPath);
if (dbFile.exists()) {
String encPath = this.backupDir + File.separator + pDbName + ".sqlten";
File dbBkFile = new File(encPath);
if (dbBkFile.exists()) {
Long time = new Date().getTime();
encPath = this.backupDir + File.separator + pDbName + time + ".sqlten";
}
this.cryptoHelper.encryptFile(dbPath, encPath);
}
}
|
java
|
private String getSelectPkSql(String[] where)
{
StringBuilder sql = new StringBuilder("select ")
.append(_entityInfo.id().columnName())
.append(" FROM ").append(_entityInfo.tableName())
.append(" where ");
for (int i = 0; i < where.length; i++) {
sql.append(where[i]).append('=').append('?');
if ((i + 1) < where.length)
sql.append(" AND ");
}
return sql.toString();
}
|
python
|
def get_default_config(self):
"""
Returns the xfs collector settings
"""
config = super(XFSCollector, self).get_default_config()
config.update({
'path': 'xfs'
})
return config
|
python
|
def _check_data_flow_id(self, data_flow):
"""Checks the validity of a data flow id
Checks whether the id of the given data flow is already by anther data flow used within the state.
:param rafcon.core.data_flow.DataFlow data_flow: The data flow to be checked
:return bool validity, str message: validity is True, when the data flow is valid, False else. message gives
more information especially if the data flow is not valid
"""
data_flow_id = data_flow.data_flow_id
if data_flow_id in self.data_flows and data_flow is not self.data_flows[data_flow_id]:
return False, "data_flow_id already existing"
return True, "valid"
|
python
|
def AddOption(self, descriptor, constant=False):
"""Registers an option with the configuration system.
Args:
descriptor: A TypeInfoObject instance describing the option.
constant: If this is set, the option is treated as a constant - it can be
read at any time (before parsing the configuration) and it's an error to
try to override it in a config file.
Raises:
RuntimeError: The descriptor's name must contain a . to denote the section
name, otherwise we raise.
AlreadyInitializedError: If the config has already been read it's too late
to define new options.
"""
if self.initialized:
raise AlreadyInitializedError(
"Config was already initialized when defining %s" % descriptor.name)
descriptor.section = descriptor.name.split(".")[0]
if descriptor.name in self.type_infos:
logging.warning("Config Option %s multiply defined!", descriptor.name)
self.type_infos.Append(descriptor)
if constant:
self.constants.add(descriptor.name)
# Register this option's default value.
self.defaults[descriptor.name] = descriptor.GetDefault()
self.FlushCache()
|
python
|
def AddProcessingOptions(self, argument_group):
"""Adds the processing options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_group.add_argument(
'--single_process', '--single-process', dest='single_process',
action='store_true', default=False, help=(
'Indicate that the tool should run in a single process.'))
argument_helper_names = ['temporary_directory', 'workers', 'zeromq']
if self._CanEnforceProcessMemoryLimit():
argument_helper_names.append('process_resources')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_group, names=argument_helper_names)
|
java
|
public void cancel(final int id) {
final BaseNotificationItem notification = remove(id);
if (notification == null) {
return;
}
notification.cancel();
}
|
python
|
def _find_dependant_trees(self, tree_obj):
""" returns list of trees that are dependent_on given tree_obj """
dependant_trees = []
for tree_name, tree in self.trees.items():
if tree_obj in tree.dependent_on:
dependant_trees.append(tree)
return dependant_trees
|
python
|
def taskfile_updated_data(file_, role):
"""Return the data for updated date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the updated date
:rtype: depending on role
:raises: None
"""
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
dt = file_.date_updated
return dt_to_qdatetime(dt)
|
java
|
public java.util.List<MinimumEngineVersionPerAllowedValue> getMinimumEngineVersionPerAllowedValue() {
if (minimumEngineVersionPerAllowedValue == null) {
minimumEngineVersionPerAllowedValue = new com.amazonaws.internal.SdkInternalList<MinimumEngineVersionPerAllowedValue>();
}
return minimumEngineVersionPerAllowedValue;
}
|
python
|
def selectedParameterTypes(self, row):
"""Gets a list of the intersection of the editable properties in the parameteter *param*'s
component selection. E.g. ['frequency', 'intensity']
:param row: the ith parameter number
:type row: int
:returns: list<str> -- a list of AbstractStimulusComponent attribute names
"""
param = self._parameters[row]
return self._selectionParameters(param)
|
python
|
def subset(self, fromdate, todate):
'''
Return a list of dates from the list between <fromdate> and <todate>
(inclusive)
'''
#CONSIDER: raise an exception if a date is not in self
i_from = self.index(fromdate)
if fromdate != self[i_from]:
# don't go back before fromdate
i_from += 1
i_to = self.index(todate)
return self[i_from:i_to + 1]
|
java
|
public boolean dispatchKeyEvent (KeyEvent e)
{
// bail if we're not enabled, we haven't the focus, or we're not
// showing on-screen
if (!_enabled || !_focus || !_target.isShowing()) {
// log.info("dispatchKeyEvent [enabled=" + _enabled +
// ", focus=" + _focus +
// ", showing=" + ((_target == null) ? "N/A" :
// "" + _target.isShowing()) + "].");
return false;
}
// handle key press and release events
switch (e.getID()) {
case KeyEvent.KEY_PRESSED:
return keyPressed(e);
case KeyEvent.KEY_RELEASED:
return keyReleased(e);
case KeyEvent.KEY_TYPED:
return keyTyped(e);
default:
return false;
}
}
|
python
|
def symmetricsys(dep_tr=None, indep_tr=None, SuperClass=TransformedSys, **kwargs):
""" A factory function for creating symmetrically transformed systems.
Creates a new subclass which applies the same transformation for each dependent variable.
Parameters
----------
dep_tr : pair of callables (default: None)
Forward and backward transformation callbacks to be applied to the
dependent variables.
indep_tr : pair of callables (default: None)
Forward and backward transformation to be applied to the
independent variable.
SuperClass : class
\*\*kwargs :
Default keyword arguments for the TransformedSys subclass.
Returns
-------
Subclass of SuperClass (by default :class:`TransformedSys`).
Examples
--------
>>> import sympy
>>> logexp = (sympy.log, sympy.exp)
>>> def psimp(exprs):
... return [sympy.powsimp(expr.expand(), force=True) for expr in exprs]
...
>>> LogLogSys = symmetricsys(logexp, logexp, exprs_process_cb=psimp)
>>> mysys = LogLogSys.from_callback(lambda x, y, p: [-y[0], y[0] - y[1]], 2, 0)
>>> mysys.exprs
(-exp(x_0), -exp(x_0) + exp(x_0 + y_0 - y_1))
"""
if dep_tr is not None:
if not callable(dep_tr[0]) or not callable(dep_tr[1]):
raise ValueError("Exceptected dep_tr to be a pair of callables")
if indep_tr is not None:
if not callable(indep_tr[0]) or not callable(indep_tr[1]):
raise ValueError("Exceptected indep_tr to be a pair of callables")
class _SymmetricSys(SuperClass):
def __init__(self, dep_exprs, indep=None, **inner_kwargs):
new_kwargs = kwargs.copy()
new_kwargs.update(inner_kwargs)
dep, exprs = zip(*dep_exprs)
super(_SymmetricSys, self).__init__(
zip(dep, exprs), indep,
dep_transf=list(zip(
list(map(dep_tr[0], dep)),
list(map(dep_tr[1], dep))
)) if dep_tr is not None else None,
indep_transf=((indep_tr[0](indep), indep_tr[1](indep))
if indep_tr is not None else None),
**new_kwargs)
@classmethod
def from_callback(cls, cb, ny=None, nparams=None, **inner_kwargs):
new_kwargs = kwargs.copy()
new_kwargs.update(inner_kwargs)
return SuperClass.from_callback(
cb, ny, nparams,
dep_transf_cbs=repeat(dep_tr) if dep_tr is not None else None,
indep_transf_cbs=indep_tr,
**new_kwargs)
return _SymmetricSys
|
python
|
def density_2d(self, r, kwargs_profile):
"""
computes the projected density along the line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: 2d projected density at projected radius r
"""
kwargs = copy.deepcopy(kwargs_profile)
try:
del kwargs['center_x']
del kwargs['center_y']
except:
pass
# integral of self._profile.density(np.sqrt(x^2+r^2))* dx, 0, infty
out = integrate.quad(lambda x: 2*self._profile.density(np.sqrt(x**2+r**2), **kwargs), 0, 100)
return out[0]
|
java
|
public synchronized Registry getRegistry() throws RemoteException {
if (registry == null) {
registry = LocateRegistry.createRegistry(JdcpUtil.DEFAULT_PORT);
}
return registry;
}
|
java
|
public void eventReceived (DEvent event)
{
if (event instanceof InvocationResponseEvent) {
InvocationResponseEvent ire = (InvocationResponseEvent)event;
handleInvocationResponse(ire.getRequestId(), ire.getMethodId(), ire.getArgs());
} else if (event instanceof InvocationNotificationEvent) {
InvocationNotificationEvent ine = (InvocationNotificationEvent)event;
handleInvocationNotification(ine.getReceiverId(), ine.getMethodId(), ine.getArgs());
} else if (event instanceof MessageEvent) {
MessageEvent mevt = (MessageEvent)event;
if (mevt.getName().equals(ClientObject.CLOBJ_CHANGED)) {
handleClientObjectChanged(((Integer)mevt.getArgs()[0]).intValue());
}
}
}
|
python
|
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, AttributeError):
raise ImportError('Class %s cannot be found (%s)' %
(class_str,
traceback.format_exception(*sys.exc_info())))
|
python
|
def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclusive, # type: bool
response_name, # type: str
field1, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
field2, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Determines if there is a conflict between two particular fields."""
parent_type1, ast1, def1 = field1
parent_type2, ast2, def2 = field2
# If it is known that two fields could not possibly apply at the same
# time, due to the parent types, then it is safe to permit them to diverge
# in aliased field or arguments used as they will not present any ambiguity
# by differing.
# It is known that two parent types could never overlap if they are
# different Object types. Interface or Union types might overlap - if not
# in the current state of the schema, then perhaps in some future version,
# thus may not safely diverge.
are_mutually_exclusive = parent_fields_are_mutually_exclusive or (
parent_type1 != parent_type2
and isinstance(parent_type1, GraphQLObjectType)
and isinstance(parent_type2, GraphQLObjectType)
)
# The return type for each field.
type1 = def1 and def1.type
type2 = def2 and def2.type
if not are_mutually_exclusive:
# Two aliases must refer to the same field.
name1 = ast1.name.value
name2 = ast2.name.value
if name1 != name2:
return (
(response_name, "{} and {} are different fields".format(name1, name2)),
[ast1],
[ast2],
)
# Two field calls must have the same arguments.
if not _same_arguments(ast1.arguments, ast2.arguments):
return ((response_name, "they have differing arguments"), [ast1], [ast2])
if type1 and type2 and do_types_conflict(type1, type2):
return (
(
response_name,
"they return conflicting types {} and {}".format(type1, type2),
),
[ast1],
[ast2],
)
# Collect and compare sub-fields. Use the same "visited fragment names" list
# for both collections so fields in a fragment reference are never
# compared to themselves.
selection_set1 = ast1.selection_set
selection_set2 = ast2.selection_set
if selection_set1 and selection_set2:
conflicts = _find_conflicts_between_sub_selection_sets( # type: ignore
context,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
get_named_type(type1), # type: ignore
selection_set1,
get_named_type(type2), # type: ignore
selection_set2,
)
return _subfield_conflicts(conflicts, response_name, ast1, ast2)
return None
|
java
|
public String [] getNames() {
String [] result = new String[headers.size()];
headers.keySet().toArray(result);
return result;
}
|
java
|
public void removeResourceFromUsersPubList(CmsObject cms, Collection<CmsUUID> structureIds) throws CmsException {
m_securityManager.removeResourceFromUsersPubList(cms.getRequestContext(), structureIds);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.