language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python
|
def serialise(structure):
"""
structure (ctypes.Structure)
The structure to serialise.
Returns a ctypes.c_char array.
Does not copy memory.
"""
return ctypes.cast(
ctypes.pointer(structure),
ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)),
).contents
|
java
|
public void cacheDescriptorValue(IBond bond, IAtomContainer container, IDescriptorResult doubleResult) {
if (cachedDescriptorValues == null) {
cachedDescriptorValues = new HashMap();
cachedDescriptorValues.put(PREVIOUS_ATOMCONTAINER, container);
} else if (cachedDescriptorValues.get(PREVIOUS_ATOMCONTAINER) != container) {
cachedDescriptorValues.clear();
cachedDescriptorValues.put(PREVIOUS_ATOMCONTAINER, container);
}
cachedDescriptorValues.put(bond, doubleResult);
}
|
java
|
public final boolean isId(final String pNm) {
for (String idNm : this.idColNms) {
if (idNm.equals(pNm)) {
return true;
}
}
return false;
}
|
python
|
async def release(self, conn):
"""Release free connection back to the connection pool.
"""
assert conn in self._used, (conn, self._used)
self._used.remove(conn)
if not conn.closed:
if self._closing:
await conn.close()
else:
self._free.append(conn)
await self._wakeup()
|
python
|
def load_tables(self, query, meta):
"""
Load necessary resources tables into db to execute given query.
"""
try:
for table in meta.tables:
self.load_table(table)
except NoCredentialsError:
help_link = 'http://boto3.readthedocs.io/en/latest/guide/configuration.html'
raise QueryError('Unable to locate AWS credential. '
'Please see {0} on how to configure AWS credential.'.format(help_link))
|
java
|
public static long getDateParameter(final ServletRequest pReq, final String pName, final long pDefault) {
String str = pReq.getParameter(pName);
try {
return str != null ? StringUtil.toDate(str).getTime() : pDefault;
}
catch (IllegalArgumentException iae) {
return pDefault;
}
}
|
python
|
def is_netcdf(url):
'''
Returns True if the URL points to a valid local netCDF file
:param str url: Location of file on the file system
'''
# Try an obvious exclusion of remote resources
if url.startswith('http'):
return False
# If it's a known extension, give it a shot
if url.endswith('nc'):
return True
# Brute force
with open(url, 'rb') as f:
magic_number = f.read(4)
if len(magic_number) < 4:
return False
if is_classic_netcdf(magic_number):
return True
elif is_hdf5(magic_number):
return True
return False
|
python
|
def clean_highlight(self):
"""
Remove the empty highlight
"""
if not self.valid:
return
for hit in self._results['hits']['hits']:
if 'highlight' in hit:
hl = hit['highlight']
for key, item in list(hl.items()):
if not item:
del hl[key]
|
python
|
def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None:
"""
Adds serialization support for a new type.
:param type: The type to add support for.
:param serialize: A callable that takes an object of type ``type`` and returns a string.
:param unserialize: A callable that takes a string and returns an object of type ``type``.
"""
self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize))
|
java
|
private void addNewJobs(Set<BambooJob> jobs, List<BambooJob> existingJobs, BambooCollector collector) {
long start = System.currentTimeMillis();
int count = 0;
List<BambooJob> newJobs = new ArrayList<>();
for (BambooJob job : jobs) {
BambooJob existing = null;
if (!CollectionUtils.isEmpty(existingJobs) && (existingJobs.contains(job))) {
existing = existingJobs.get(existingJobs.indexOf(job));
}
String niceName = getNiceName(job, collector);
if (existing == null) {
job.setCollectorId(collector.getId());
job.setEnabled(false); // Do not enable for collection. Will be enabled when added to dashboard
job.setDescription(job.getJobName());
job.setLastUpdated(System.currentTimeMillis());
if (StringUtils.isNotEmpty(niceName)) {
job.setNiceName(niceName);
}
newJobs.add(job);
count++;
} else if (StringUtils.isEmpty(existing.getNiceName()) && StringUtils.isNotEmpty(niceName)) {
existing.setNiceName(niceName);
bambooJobRepository.save(existing);
}
}
//save all in one shot
if (!CollectionUtils.isEmpty(newJobs)) {
bambooJobRepository.save(newJobs);
}
log("New jobs", start, count);
}
|
python
|
def add_file_handler(logger=None, file_path="out.log", level=logging.INFO,
log_format=log_formats.easy_read):
"""
Addes a newly created file handler to the specified logger
:param logger: logging name or object to modify, defaults to root logger
:param file_path: path to file to log to
:param level: logging level to set handler at
:param log_format: formatter to use
"""
if not isinstance(logger, logging.Logger):
logger = logging.getLogger(logger)
logger.addHandler(get_file_handler(file_path, level, log_format))
|
python
|
def calculate_lyapunov(self):
"""
Return the current Lyapunov Characteristic Number (LCN).
Note that you need to call init_megno() before the start of the simulation.
To get a timescale (the Lyapunov timescale), take the inverse of this quantity.
"""
if self._calculate_megno==0:
raise RuntimeError("Lyapunov Characteristic Number cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation.")
clibrebound.reb_tools_calculate_lyapunov.restype = c_double
return clibrebound.reb_tools_calculate_lyapunov(byref(self))
|
python
|
def precision(links_true, links_pred=None):
"""precision(links_true, links_pred)
Compute the precision.
The precision is given by TP/(TP+FP).
Parameters
----------
links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The true (or actual) collection of links.
links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The predicted collection of links.
Returns
-------
float
The precision
"""
if _isconfusionmatrix(links_true):
confusion_matrix = links_true
v = confusion_matrix[0, 0] \
/ (confusion_matrix[0, 0] + confusion_matrix[1, 0])
else:
tp = true_positives(links_true, links_pred)
fp = false_positives(links_true, links_pred)
v = tp / (tp + fp)
return float(v)
|
java
|
public Invoke createTCInvokeRequest() {
InvokeImpl t = (InvokeImpl) TcapFactory.createComponentInvoke();
t.setProvider(provider);
return t;
}
|
python
|
def recursively_save_dict_contents_to_group(h5file, path, dic):
"""
....
"""
reconstruction_flags = {}
# reconstruction_key_flags = {}
for key, item in dic.items():
if type(key) is not str:
# import pickle
# key = pickle.dumps(key).decode("ascii")
import json
key = json.dumps(key)
reconstruction_flags[path + key + "_key_/"] = "json_key"
if item is None:
import json
jitem = json.dumps(item)
h5file[path + key] = jitem
reconstruction_flags[path + key + "_typ_/"] = "json_value"
elif isinstance(item, (np.ndarray, np.int64, np.float64, str, bytes)):
h5file[path + key] = item
elif isinstance(item, (float)):
h5file[path + key] = item
reconstruction_flags[path + key + "_typ_/"] = "float"
elif isinstance(item, (int)):
h5file[path + key] = item
reconstruction_flags[path + key + "_typ_/"] = "int"
elif isinstance(item, dict):
rf = recursively_save_dict_contents_to_group(h5file, path + key + '/', item)
reconstruction_flags.update(rf)
# reconstruction_key_flags.update(rkf)
elif isinstance(item, list):
# i = iter(item)
item_dict = dict(zip(range(len(item)), item))
wholekey = path + key + "_typ_/"
reconstruction_flags[wholekey] = "list"
rf = recursively_save_dict_contents_to_group(h5file, path + key + '/', item_dict)
reconstruction_flags.update(rf)
# reconstruction_key_flags.update(rkf)
elif isinstance(item, tuple):
# i = iter(item)
item_dict = dict(zip(range(len(item)), item))
wholekey = path + key + "_typ_/"
reconstruction_flags[wholekey] = "tuple"
rf = recursively_save_dict_contents_to_group(h5file, path + key + '/', item_dict)
reconstruction_flags.update(rf)
else:
logger.info("Saving type {} with json".format(type(item)))
import json
jitem = json.dumps(item)
h5file[path + key] = jitem
reconstruction_flags[path + key + "_typ_/"] = "json_value"
# raise ValueError('Cannot save %s type'%type(item))
return reconstruction_flags
|
python
|
def sigma2Derivative(self,R,log=False):
"""
NAME:
sigmaDerivative
PURPOSE:
return the derivative wrt R of the sigma_R^2 profile at this R
INPUT:
R - Galactocentric radius (/ro)
log - if True, return the derivative of the log (default: False)
OUTPUT:
Sigma_R^2'(R) or (log Sigma_R^2(r) )'
HISTORY:
2011-03-24 - Written - Bovy (NYU)
"""
if log:
return -2./self._params[1]
else:
return self._params[2]**2.*sc.exp(-2.*(R-1.)/self._params[1])\
*(-2./self._params[1])
|
java
|
@Override
public void run() {
try {
while (!delegate.isShutdown()) {
this.rateLimiter.acquire();
Runnable r = queue.take();
if (!delegate.isShutdown()) {
delegate.execute(r);
}
}
} catch (InterruptedException ie) {
LOG.info("Interrupted", ie);
}
}
|
java
|
protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
// if there remain any unimported toplevels (these must have
// no classes at all), process their import statements as well.
for (JCCompilationUnit tree : trees) {
if (!tree.starImportScope.isFilled()) {
Env<AttrContext> topEnv = enter.topLevelEnv(tree);
finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
}
}
}
|
java
|
public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
InputStream inStream = resultset.getBinaryStream(iColumn);
if (resultset.wasNull())
this.setData(null, false, DBConstants.READ_MOVE); // Null value
else
{
try {
// This is kind of weird, but for some reason, the inStream will only accept read(byte[]), so I have to do this:
byte rgBytes[] = new byte[2048];
ByteArrayOutputStream baOut = new ByteArrayOutputStream();
while (true)
{
int iRead = 0;
try {
iRead = inStream.read(rgBytes);
} catch (EOFException ex) {
iRead = 0;
}
if (iRead > 0)
baOut.write(rgBytes, 0, iRead);
if (iRead < rgBytes.length)
break; // End of stream
}
rgBytes = baOut.toByteArray();
Object objData = null;
if (rgBytes.length > 0)
{
String string = new String(rgBytes, BundleConstants.OBJECT_ENCODING);
objData = ClassServiceUtility.getClassService().convertStringToObject(string, null);
//x ByteArrayInputStream ibyStream = new ByteArrayInputStream(rgBytes);
//x ObjectInputStream iStream = new ObjectInputStream(ibyStream);
//x objData = iStream.readObject();
}
this.setData(objData, false, DBConstants.READ_MOVE);
} catch (IOException ex) {
ex.printStackTrace(); // Never
} catch (ClassNotFoundException ex) {
ex.printStackTrace(); // Never
}
}
}
|
python
|
def _get_next_obj(self, length):
"""Assumes we've already read the object length"""
data = b''
while len(data) < length:
data += self.sock.recv(length - len(data))
return pickle.loads(data)
|
python
|
def add_reference_resources(data, remote_retriever=None):
"""Add genome reference information to the item to process.
"""
aligner = data["config"]["algorithm"].get("aligner", None)
if remote_retriever:
data["reference"] = remote_retriever.get_refs(data["genome_build"],
alignment.get_aligner_with_aliases(aligner, data),
data["config"])
else:
data["reference"] = genome.get_refs(data["genome_build"], alignment.get_aligner_with_aliases(aligner, data),
data["dirs"]["galaxy"], data)
_check_ref_files(data["reference"], data)
# back compatible `sam_ref` target
data["sam_ref"] = utils.get_in(data, ("reference", "fasta", "base"))
ref_loc = utils.get_in(data, ("config", "resources", "species", "dir"),
utils.get_in(data, ("reference", "fasta", "base")))
if remote_retriever:
data = remote_retriever.get_resources(data["genome_build"], ref_loc, data)
else:
data["genome_resources"] = genome.get_resources(data["genome_build"], ref_loc, data)
data["genome_resources"] = genome.add_required_resources(data["genome_resources"])
if effects.get_type(data) == "snpeff" and "snpeff" not in data["reference"]:
data["reference"]["snpeff"] = effects.get_snpeff_files(data)
if "genome_context" not in data["reference"]:
data["reference"]["genome_context"] = annotation.get_context_files(data)
if "viral" not in data["reference"]:
data["reference"]["viral"] = viral.get_files(data)
if not data["reference"]["viral"]:
data["reference"]["viral"] = None
if "versions" not in data["reference"]:
data["reference"]["versions"] = _get_data_versions(data)
data = _fill_validation_targets(data)
data = _fill_prioritization_targets(data)
data = _fill_capture_regions(data)
# Re-enable when we have ability to re-define gemini configuration directory
if False:
data["reference"]["gemini"] = population.get_gemini_files(data)
return data
|
python
|
def deprecated(msg, dep_version):
"""Decorate a function, method or class to mark as deprecated.
Raise DeprecationWarning and add a deprecation notice to the docstring.
"""
def wrapper(func):
docstring = func.__doc__ or ''
docstring_msg = '.. deprecated:: {version} {msg}'.format(
version=dep_version,
msg=msg,
)
if docstring:
# We don't know how far to indent this message
# so instead we just dedent everything.
string_list = docstring.splitlines()
first_line = string_list[0]
remaining = textwrap.dedent(''.join(string_list[1:]))
docstring = '\n'.join([
first_line,
remaining,
'',
docstring_msg,
])
else:
docstring = docstring_msg
func.__doc__ = docstring
@wraps(func)
def inner(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
return inner
return wrapper
|
java
|
public void initLeading ()
{
m_nLeading = 0;
while (m_nLeading < m_sValue.length () && m_sValue.charAt (m_nLeading) == ' ')
m_nLeading++;
if (m_nLeading == m_sValue.length ())
setEmpty ();
}
|
java
|
public void addFields(List<ModelFieldBean> modelFields) {
Assert.notNull(modelFields, "modelFields must not be null");
for (ModelFieldBean bean : modelFields) {
this.fields.put(bean.getName(), bean);
}
}
|
python
|
def translate_path(self, orig_path):
"""Translates a path for a static file request. The server base path
could be different from our cwd.
Parameters
----------
path : string
The path.
Returns
-------
The absolute file path denoted by the original path.
"""
init_path = orig_path
orig_path = urlparse.urlparse(orig_path)[2]
needs_redirect = False
is_folder = len(orig_path) <= 1 or orig_path[-1] == '/'
orig_path = posixpath.normpath(urlparse_unquote(orig_path))
if is_folder:
orig_path += '/'
path = None
for (name, fm) in self.server._folder_masks:
if not orig_path.startswith(name):
continue
cur_base = os.path.abspath(os.path.join(self.server.base_path, fm))
path = cur_base
words = orig_path[len(name):].split('/')
words = filter(None, words)
for word in words:
_drive, word = os.path.splitdrive(word)
_head, word = os.path.split(word)
if word in (os.curdir, os.pardir):
continue
if word.startswith('.'): # don't ever allow any hidden files
raise PreventDefaultResponse(404, "File not found")
path = os.path.join(path, word)
# make path absolute and check if it exists
path = os.path.abspath(path)
if os.path.exists(path):
break
# if pass is still None here the file cannot be found
if path is None:
# try proxies
for (name, pxy) in self.server._folder_proxys:
if not orig_path.startswith(name):
continue
remain = orig_path[len(name) - 1:]
proxy = urlparse.urlparse(pxy)
reala = urlparse.urlparse(init_path)
pxya = urlparse.urlunparse((
proxy[0], # scheme
proxy[1], # netloc
"{0}{1}".format(proxy[2], remain), # path
reala[3], # params
reala[4], # query
reala[5], # fragment
))
self.send_to_proxy(pxya) # raises PreventDefaultResponse
msg("no matching folder alias: {0}".format(orig_path))
raise PreventDefaultResponse(404, "File not found")
if os.path.isdir(path):
if not is_folder:
needs_redirect = True
else:
for orig_index in ["index.html", "index.htm"]:
index = os.path.join(path, orig_index)
if os.path.isfile(index):
path = index
break
if os.path.isdir(path):
# no black-/white-list for directories
is_white = True
else:
# match agains black- and white-list
is_white = len(self.server._pattern_white) == 0
for pattern in self.server._pattern_white:
if fnmatch.fnmatch(path, pattern):
is_white = True
break
for pattern in self.server._pattern_black:
if fnmatch.fnmatch(path, pattern):
is_white = False
break
if not is_white:
raise PreventDefaultResponse(404, "File not found")
# make sure to not accept any trickery to get away from the base path
if not path.startswith(cur_base):
raise ValueError("WARNING: attempt to access {0}".format(path))
# favicon handling
if self.server.favicon_everywhere and \
os.path.basename(path) == 'favicon.ico' and \
not os.path.exists(path):
for (name, fm) in self.server._folder_masks:
fav_base = os.path.abspath(
os.path.join(self.server.base_path, fm))
favicon = os.path.join(fav_base, 'favicon.ico')
if os.path.exists(favicon):
path = favicon
break
if self.server.favicon_fallback is not None and \
os.path.exists(self.server.favicon_fallback):
path = os.path.join(
self.server.base_path, self.server.favicon_fallback)
break
# redirect improper index requests
if needs_redirect:
self.send_response(301, "Use index page with slash")
location = urlparse.urlunparse(tuple([
seg if ix != 2 else seg + '/'
for (ix, seg) in enumerate(urlparse.urlparse(init_path))
]))
self.send_header("Location", location)
self.end_headers()
raise PreventDefaultResponse()
# handle ETag caching
if self.request_version >= "HTTP/1.1" and os.path.isfile(path):
e_tag = None
with open(path, 'rb') as input_f:
e_tag = "{0:x}".format(zlib.crc32(input_f.read()) & 0xFFFFFFFF)
thread_local.size = input_f.tell()
if e_tag is not None:
match = _getheader(self.headers, 'if-none-match')
if match is not None:
if self.check_cache(e_tag, match):
raise PreventDefaultResponse()
self.send_header("ETag", e_tag, end_header=True)
self.send_header("Cache-Control",
"max-age={0}".format(self.server.max_age),
end_header=True)
return path
|
java
|
public boolean enableWriteAheadLogging() {
synchronized (mLock) {
throwIfNotOpenLocked();
if ((mConfigurationLocked.openFlags & ENABLE_WRITE_AHEAD_LOGGING) != 0) {
return true;
}
if (isReadOnlyLocked()) {
// WAL doesn't make sense for readonly-databases.
// TODO: True, but connection pooling does still make sense...
return false;
}
if (mConfigurationLocked.isInMemoryDb()) {
Log.i(TAG, "can't enable WAL for memory databases.");
return false;
}
// make sure this database has NO attached databases because sqlite's write-ahead-logging
// doesn't work for databases with attached databases
if (mHasAttachedDbsLocked) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "this database: " + mConfigurationLocked.label
+ " has attached databases. can't enable WAL.");
}
return false;
}
mConfigurationLocked.openFlags |= ENABLE_WRITE_AHEAD_LOGGING;
try {
mConnectionPoolLocked.reconfigure(mConfigurationLocked);
} catch (RuntimeException ex) {
mConfigurationLocked.openFlags &= ~ENABLE_WRITE_AHEAD_LOGGING;
throw ex;
}
}
return true;
}
|
java
|
public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);
}
|
python
|
def _DISPATCH(self, body, ticket=None):
"""Dispatch message to the appropriate method
in :attr:`state`, handle possible exceptions,
and return a response suitable to be used in a reply.
To protect from calling special methods it does not dispatch
method names starting with underscore (``_``).
This returns the return value or exception error
with defaults fields in a suitable format to be used
as a reply.
The exceptions :exc:`SystemExit` and :exc:`KeyboardInterrupt`
will not be handled, and will propagate.
In the case of a successful call the return value will
be::
{'ok': return_value, **default_fields}
If the method raised an exception the return value
will be::
{'nok': [repr exc, str traceback], **default_fields}
:raises KeyError: if the method specified is unknown
or is a special method (name starting with underscore).
"""
if ticket:
sticket = '%s' % (shortuuid(ticket), )
else:
ticket = sticket = str(next(self.ticket_counter))
try:
method, args = itemgetter('method', 'args')(body)
self.log.info('#%s --> %s',
sticket, self._reprcall(method, args))
act = self.lookup_action(method)
r = {'ok': act(args or {})}
self.log.info('#%s <-- %s', sticket, reprkwargs(r))
except self.Next:
raise
except Exception as exc:
einfo = sys.exc_info()
r = {'nok': [safe_repr(exc), self._get_traceback(einfo)]}
self.log.error('#%s <-- nok=%r', sticket, exc)
return dict(self._default_fields, **r)
|
java
|
protected IScope getFeatureScope(Anchor anchor) {
IScope cached = cachedFeatureScope.get(anchor);
if (cached != null)
return cached;
if (anchor != Anchor.RECEIVER) {
cached = createSimpleFeatureCallScope();
cachedFeatureScope.put(anchor, cached);
return cached;
} else if (context instanceof XExpression) {
cached = createFeatureCallScopeForReceiver(null); // receiver is missing intentionally
cachedFeatureScope.put(anchor, cached);
return cached;
}
cachedFeatureScope.put(anchor, IScope.NULLSCOPE);
return IScope.NULLSCOPE;
}
|
java
|
static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessful=f.renameTo(newLocation);
if (relocationSuccessful) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
|
java
|
private void syncSysMetaFromRemote() {
for (String topology : JStormMetrics.SYS_TOPOLOGIES) {
if (context.getTopologyMetricContexts().containsKey(topology)) {
syncMetaFromRemote(topology,
context.getTopologyMetricContexts().get(topology),
Lists.newArrayList(MetaType.TOPOLOGY, MetaType.WORKER, MetaType.NIMBUS));
}
}
}
|
python
|
def launch_local(in_name, out_name, script_path, poll=None, max_input=None,
files=(), cmdenvs=(), pipe=True, python_cmd='python', remove_tempdir=True,
identity_mapper=False, num_reducers=None,
**kw):
"""A simple local emulation of hadoop
This doesn't run hadoop and it doesn't support many advanced features, it
is intended for simple debugging. The input/output uses HDFS if an
HDFS path is given. This allows for small tasks to be run locally
(primarily while debugging). A temporary working directory is used and
removed.
Support
* Environmental variables
* Map-only tasks
* Combiner
* Files
* Pipe (see below)
* Display of stdout/stderr
* Iterator of KV pairs as input or output (bypassing HDFS)
:param in_name: Input path (string or list of strings) or Iterator of (key, value). If it is an iterator then no input is taken from HDFS.
:param out_name: Output path or None. If None then output is not placed on HDFS, it is available through the 'output' key of the return value.
:param script_path: Path to the script (e.g., script.py)
:param poll: If not None, then only attempt to get a kv pair from kvs if when called, poll returns True.
:param max_input: Maximum number of Mapper inputs, None (default) then unlimited.
:param files: Extra files (other than the script) (iterator). NOTE: Hadoop copies the files into working directory
:param cmdenvs: Extra cmdenv parameters (iterator)
:param pipe: If true (default) then call user code through a pipe to isolate it and stop bugs when printing to stdout. See project docs.
:param python_cmd: The python command to use. The default is "python". Can be used to override the system default python, e.g. python_cmd = "python2.6"
:param remove_tempdir: If True (default), then rmtree the temporary dir, else print its location. Useful if you need to see temporary files or how input files are copied.
:param identity_mapper: If True, use an identity mapper, regardless of what is in the script.
:param num_reducers: If 0, don't run the reducer even if one exists, else obey what is in the script.
:rtype: Dictionary with some of the following entries (depending on options)
:returns: freeze_cmds: Freeze command(s) ran
:returns: frozen_tar_path: HDFS path to frozen file
:returns: hadoop_cmds: Hadoopy command(s) ran
:returns: process: subprocess.Popen object
:returns: output: Iterator of (key, value) pairs
:raises: subprocess.CalledProcessError: Hadoop error.
:raises: OSError: Hadoop streaming not found.
:raises: TypeError: Input types are not correct.
:raises: ValueError: Script not found
"""
if isinstance(files, (str, unicode)) or isinstance(cmdenvs, (str, unicode)) or ('cmdenvs' in kw and isinstance(kw['cmdenvs'], (str, unicode))):
raise TypeError('files and cmdenvs must be iterators of strings and not strings!')
logging.info('Local[%s]' % script_path)
script_info = hadoopy._runner._parse_info(script_path, python_cmd)
if isinstance(in_name, (str, unicode)) or (in_name and isinstance(in_name, (list, tuple)) and isinstance(in_name[0], (str, unicode))):
in_kvs = hadoopy.readtb(in_name)
else:
in_kvs = in_name
if 'reduce' in script_info['tasks'] and num_reducers != 0:
if identity_mapper:
kvs = in_kvs
else:
kvs = list(LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll))
if 'combine' in script_info['tasks']:
kvs = hadoopy.Test.sort_kv(kvs)
kvs = list(LocalTask(script_path, 'combine', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs))
kvs = hadoopy.Test.sort_kv(kvs)
kvs = LocalTask(script_path, 'reduce', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs)
else:
if identity_mapper:
kvs = in_kvs
else:
kvs = LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll)
out = {}
if out_name is not None:
hadoopy.writetb(out_name, kvs)
out['output'] = hadoopy.readtb(out_name)
else:
out['output'] = kvs
return out
|
java
|
private final void performRecovery(LogInput logInput)
throws ObjectManagerException {
final String methodName = "performRecovery";
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
methodName,
new Object[] { logInput });
// Set no checkpoint end yest seen.
checkpointEndSeen = false;
// We start reading the log at the start of the last complete checkpoint.
// The checkpointed and in flight transactions are recovered until we find checkpoint end.
try {
for (;;) { // Loop over input log records.
LogRecord logRecordRead = logInput.readNext();
logRecordRead.performRecovery(this);
} // for log records to read.
} catch (LogFileExhaustedException exception) {
// No FFDC Code Needed, condition expected when end of log seen.
if (Tracing.isAnyTracingEnabled() && trace.isEventEnabled())
trace.event(this,
cclass,
methodName,
exception);
} catch (ObjectManagerException exception) {
// No FFDC Code Needed.
ObjectManager.ffdc.processException(this,
cclass,
methodName,
exception,
"1:751:1.62");
shutdown();
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
methodName,
"ObjectManagerException:758");
throw exception;
} // try.
// Have wee seen a completed checkpoint?
if (checkpointEndSeen == false) {
// TODO At cold start, we need to mark the log header so that it indicates that we have not yet
// completed the first ever checkpoint. If we fail before we do this we then know
// that we crashed before it is rewritten, we can safely have another go at writing it
// another first checkpoint. We could just assume that because we have not seen
// a checkpoint end then we did not successfully cold start and have another go.
shutdown();
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
methodName,
new Object[] { "CheckpointEndNotFoundException:774", logFileName });
throw new CheckpointEndNotFoundException(this,
logFileName);
}
synchronized (this) {
// Make the state change.
setState(nextStateForLogReplayed);
} // synchronized (this).
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this,
cclass,
methodName);
}
|
java
|
private static UIComponent createFacetUIPanel(FaceletContext ctx, UIComponent parent, String facetName)
{
FacesContext facesContext = ctx.getFacesContext();
UIComponent panel = facesContext.getApplication().createComponent(facesContext, UIPanel.COMPONENT_TYPE, null);
// The panel created by this method is special. To be restored properly and do not
// create duplicate ids or any other unwanted conflicts, it requires an unique id.
// This code is usually called when more than one component is added to a facet and
// it is necessary to create a shared container.
// Use FaceletCompositionContext.generateUniqueComponentId() is not possible, because
// <c:if> blocks inside a facet will make component ids unstable. Use UniqueIdVendor
// is feasible but also will be affected by <c:if> blocks inside a facet.
// The only solution that will generate real unique ids is use the parent id and the
// facet name and derive an unique id that cannot be generated by SectionUniqueIdCounter,
// doing the same trick as with metadata: use a double __ and add a prefix (f).
// Note this id will never be printed into the response, because this is just a container.
FaceletCompositionContext mctx = FaceletCompositionContext.getCurrentInstance(ctx);
UniqueIdVendor uniqueIdVendor = mctx.getUniqueIdVendorFromStack();
if (uniqueIdVendor == null)
{
uniqueIdVendor = ComponentSupport.getViewRoot(ctx, parent);
}
if (uniqueIdVendor != null)
{
// UIViewRoot implements UniqueIdVendor, so there is no need to cast to UIViewRoot
// and call createUniqueId(). See ComponentTagHandlerDelegate
int index = facetName.indexOf('.');
String cleanFacetName = facetName;
if (index >= 0)
{
cleanFacetName = facetName.replace('.', '_');
}
panel.setId(uniqueIdVendor.createUniqueId(facesContext,
mctx.getSharedStringBuilder()
.append(parent.getId())
.append("__f_")
.append(cleanFacetName).toString()));
}
panel.getAttributes().put(FACET_CREATED_UIPANEL_MARKER, Boolean.TRUE);
panel.getAttributes().put(ComponentSupport.COMPONENT_ADDED_BY_HANDLER_MARKER, Boolean.TRUE);
return panel;
}
|
java
|
protected DataSource createDataSource(DBType aDbType,
String aDbUrl,
String aUsername,
String aPassword,
Hashtable<String, DataSource> aDsTable)
throws SQLException {
DataSource retDatasource;
String totalMaxPoolSizeName;
switch (aDbType) {
case ORACLE:
totalMaxPoolSizeName = ORACLE_MAX_POOL_SIZE_NAME;
break;
case MSSQL:
totalMaxPoolSizeName = MSSQL_MAX_POOL_SIZE_NAME;
break;
case MYSQL:
totalMaxPoolSizeName = MYSQL_MAX_POOL_SIZE_NAME;
break;
case SYBASE:
totalMaxPoolSizeName = SYBASE_MAX_POOL_SIZE_NAME;
break;
case DB2:
totalMaxPoolSizeName = DB2_MAX_POOL_SIZE_NAME;
break;
case NETCOOL:
totalMaxPoolSizeName = NETCOOL_MAX_POOL_SIZE_NAME;
break;
default:
totalMaxPoolSizeName = CUSTOM_MAX_POOL_SIZE_NAME;
break;
}
int totalMaxPoolSize = this.getPropIntValue(totalMaxPoolSizeName,
MAX_TOTAL_POOL_SIZE_DEFAULT_VALUE);
int perUserMaxPoolSize =
this.getPropIntValue(PooledDataSourceProvider.MAX_POOL_SIZE_NAME,
PooledDataSourceProvider.MAX_POOL_SIZE_DEFAULT_VALUE);
int numDs = aDsTable.size();
int actualTotal = perUserMaxPoolSize * numDs;
if (actualTotal >= totalMaxPoolSize) {
throw new TotalMaxPoolSizeExceedException
("Can not create another datasource, the total max pool size exceeded. " +
" Expected total max pool size = " + totalMaxPoolSize +
" Actual total max pool size = " + actualTotal);
}
retDatasource = this.createDataSource(aDbType, aDbUrl, aUsername, aPassword);
return retDatasource;
}
|
python
|
def get_system_uptime_output_show_system_uptime_days(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
show_system_uptime = ET.SubElement(output, "show-system-uptime")
rbridge_id_key = ET.SubElement(show_system_uptime, "rbridge-id")
rbridge_id_key.text = kwargs.pop('rbridge_id')
days = ET.SubElement(show_system_uptime, "days")
days.text = kwargs.pop('days')
callback = kwargs.pop('callback', self._callback)
return callback(config)
|
java
|
public int getInteger(String key, int defaultValue) {
int result = defaultValue;
try {
if (key != null)
result = getInteger(key);
} catch (MissingResourceException e) {
}
return result;
}
|
python
|
def list_perceel_adapter(obj, request):
"""
Adapter for rendering a list of
:class: `crabpy.gateway.capakey.Perceel` to json.
"""
return {
'id': obj.id,
'sectie': obj.sectie,
'capakey': obj.capakey,
'percid': obj.percid
}
|
java
|
public void updateStyleElement() {
// TODO: this should be sufficient - why does Batik occasionally not pick up
// the changes unless we actually replace the style element itself?
// cssman.updateStyleElement(document, style);
Element newstyle = cssman.makeStyleElement(document);
style.getParentNode().replaceChild(newstyle, style);
style = newstyle;
}
|
python
|
def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param state:
:param custom_filters: list of custom filters
:param run_task: run callback in task (no wait results)
:param kwargs:
:return: decorated function
"""
def decorator(callback):
self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp,
content_types=content_types, state=state, run_task=run_task, **kwargs)
return callback
return decorator
|
java
|
public static ByteBuffer toByteBuffer(String s) {
ByteBuffer buffer = ByteBuffer.allocateDirect(s.length());
buffer.put(s.getBytes(UTF_8));
buffer.flip();
return buffer;
}
|
java
|
private String getCData(final Node n) {
StringBuffer buf = new StringBuffer();
NodeList nl = n.getChildNodes();
for (int x = 0; x < nl.getLength(); x++) {
Node innerNode = nl.item(x);
if (
(innerNode.getNodeType() == Node.TEXT_NODE)
|| (innerNode.getNodeType() == Node.CDATA_SECTION_NODE)) {
buf.append(innerNode.getNodeValue());
}
}
return buf.toString();
}
|
python
|
def _coerceValue(self,value,strict=0):
"""Coerce parameter to appropriate type
Should accept None or null string. Must be an array.
"""
try:
if isinstance(value,str):
# allow single blank-separated string as input
value = value.split()
if len(value) != len(self.value):
raise IndexError
v = len(self.value)*[0]
for i in range(len(v)):
v[i] = self._coerceOneValue(value[i],strict)
return v
except (IndexError, TypeError):
raise ValueError("Value must be a " + repr(len(self.value)) +
"-element array for " + self.name)
|
python
|
def place(self, **kw):
"""
Place a widget in the parent widget.
:param in\_: master relative to which the widget is placed
:type in\_: widget
:param x: locate anchor of this widget at position x of master
:type x: int
:param y: locate anchor of this widget at positiony of master
:type y: int
:param relx: locate anchor of this widget between 0 and 1
relative to width of master (1 is right edge)
:type relx: float
:param rely: locate anchor of this widget between 0 and 1
relative to height of master (1 is bottom edge)
:type rely: float
:param anchor: position anchor according to given direction
("n", "s", "e", "w" or combinations)
:type anchor: str
:param width: width of this widget in pixel
:type width: int
:param height: height of this widget in pixel
:type height: int
:param relwidth: width of this widget between 0.0 and 1.0
relative to width of master (1.0 is the same width
as the master)
:type relwidth: float
:param relheight: height of this widget between 0.0 and 1.0
relative to height of master (1.0 is the same
height as the master)
:type relheight: float
:param bordermode: "inside" or "outside": whether to take border width of master widget into account
:type bordermode: str
"""
ttk.Scrollbar.place(self, **kw)
try:
self._place_kw = self.place_info()
except TypeError:
# bug in some tkinter versions
self._place_kw = self._get_info("place")
self._layout = 'place'
|
java
|
public static FileBytes allocate(File file, String mode, int size) {
return new FileBytes(file, mode, (int) Math.min(Memory.Util.toPow2(size), Integer.MAX_VALUE));
}
|
java
|
public static <T extends Enum<T>> EnumPath<T> enumPath(Class<? extends T> type, Path<?> parent, String property) {
return new EnumPath<T>(type, PathMetadataFactory.forProperty(parent, property));
}
|
python
|
def register_connection(self, alias, api_key, base_url, timeout=5):
"""
Create and register a new connection.
:param alias: The alias of the connection. If not changed with `switch_connection`,
the connection with default 'alias' is used by the resources.
:param api_key: The private api key.
:param base_url: The api url including protocol, host, port (optional) and location.
:param timeout: The time in seconds to wait for 'connect' and 'read' respectively.
Use a tuple to set these values separately or None to wait forever.
:return:
"""
if not base_url.endswith('/'):
base_url += '/'
self._connections[alias] = Connection(api_key, base_url, timeout)
|
java
|
public FieldInfo getDeclaredFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
if (fieldInfo == null) {
return null;
}
for (final FieldInfo fi : fieldInfo) {
if (fi.getName().equals(fieldName)) {
return fi;
}
}
return null;
}
|
python
|
def word_game_round(self, message):
"play a word game: Play a game where you think of words that start with a letter and fit a topic."
letter = random.choice(string.ascii_uppercase)
topics = []
while len(topics) < 10:
new_topic = random.choice(WORD_GAME_TOPICS)
if new_topic not in topics:
topics.append({
"index": len(topics) + 1,
"topic": new_topic
})
context = {
"letter": letter,
"topics": topics
}
self.say(rendered_template("word_game.html", context), message=message)
|
java
|
public void update(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
Map<String, Object> esFieldDataTmp = new LinkedHashMap<>(esFieldData.size());
esFieldData.forEach((k, v) -> esFieldDataTmp.put(Util.cleanColumn(k), v));
append4Update(mapping, pkVal, esFieldDataTmp);
commitBulk();
}
|
python
|
def ephemeral(*,
port: int = 6060,
timeout_connection: int = 30,
verbose: bool = False
) -> Iterator[Client]:
"""
Launches an ephemeral server instance that will be immediately
close when no longer in context.
Parameters:
port: the port that the server should run on.
verbose: if set to True, the server will print its output to the
stdout, otherwise it will remain silent.
Returns:
a client for communicating with the server.
"""
url = "http://127.0.0.1:{}".format(port)
cmd = ["bugzood", "--debug", "-p", str(port)]
try:
stdout = None if verbose else subprocess.DEVNULL
stderr = None if verbose else subprocess.DEVNULL
proc = subprocess.Popen(cmd,
preexec_fn=os.setsid,
stdout=stdout,
stderr=stderr)
yield Client(url, timeout_connection=timeout_connection)
finally:
os.killpg(proc.pid, signal.SIGTERM)
|
java
|
public static int compareMavenVersions(String v1, String v2) {
return parseMavenVersion(v1).compareTo(parseMavenVersion(v2));
}
|
python
|
def notebook_substitute_ref_with_url(ntbk, cr):
"""
In markdown cells of notebook object `ntbk`, replace sphinx
cross-references with links to online docs. Parameter `cr` is a
CrossReferenceLookup object.
"""
# Iterate over cells in notebook
for n in range(len(ntbk['cells'])):
# Only process cells of type 'markdown'
if ntbk['cells'][n]['cell_type'] == 'markdown':
# Get text of markdown cell
txt = ntbk['cells'][n]['source']
# Replace links to online docs with sphinx cross-references
txt = cr.substitute_ref_with_url(txt)
# Replace current cell text with processed text
ntbk['cells'][n]['source'] = txt
|
python
|
def add_node(self, node, adapter_number, port_number, label=None, dump=True):
"""
Add a node to the link
:param dump: Dump project on disk
"""
port = node.get_port(adapter_number, port_number)
if port is None:
raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(adapter_number, port_number, node.name))
if port.link is not None:
raise aiohttp.web.HTTPConflict(text="Port is already used")
self._link_type = port.link_type
for other_node in self._nodes:
if other_node["node"] == node:
raise aiohttp.web.HTTPConflict(text="Cannot connect to itself")
if node.node_type in ["nat", "cloud"]:
if other_node["node"].node_type in ["nat", "cloud"]:
raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_node["node"].node_type, node.node_type))
# Check if user is not connecting serial => ethernet
other_port = other_node["node"].get_port(other_node["adapter_number"], other_node["port_number"])
if other_port is None:
raise aiohttp.web.HTTPNotFound(text="Port {}/{} for {} not found".format(other_node["adapter_number"], other_node["port_number"], other_node["node"].name))
if port.link_type != other_port.link_type:
raise aiohttp.web.HTTPConflict(text="It's not allowed to connect a {} to a {}".format(other_port.link_type, port.link_type))
if label is None:
label = {
"x": -10,
"y": -10,
"rotation": 0,
"text": html.escape("{}/{}".format(adapter_number, port_number)),
"style": "font-size: 10; font-style: Verdana"
}
self._nodes.append({
"node": node,
"adapter_number": adapter_number,
"port_number": port_number,
"port": port,
"label": label
})
if len(self._nodes) == 2:
yield from self.create()
for n in self._nodes:
n["node"].add_link(self)
n["port"].link = self
self._created = True
self._project.controller.notification.emit("link.created", self.__json__())
if dump:
self._project.dump()
|
python
|
def reciprocal(x, a, b, n):
"""
reciprocal function to the power n to fit convergence data
"""
if n < 1:
n = 1
elif n > 5:
n = 5
if isinstance(x, list):
y_l = []
for x_v in x:
y_l.append(a + b / x_v ** n)
y = np.array(y_l)
else:
y = a + b / x ** n
return y
|
python
|
def _process_items(cls, vals):
"Processes list of items assigning unique paths to each."
if type(vals) is cls:
return vals.data
elif not isinstance(vals, (list, tuple)):
vals = [vals]
items = []
counts = defaultdict(lambda: 1)
cls._unpack_paths(vals, items, counts)
items = cls._deduplicate_items(items)
return items
|
java
|
private boolean exceedsThresholds() {
boolean isFirstAppend = this.operations.size() > 0 && isAppendOperation(this.operations.getFirst());
long length = isFirstAppend ? this.operations.getFirst().getLength() : 0;
if (isFirstAppend && length == 0 && !((AggregatedAppendOperation) this.operations.getFirst()).attributes.isEmpty()) {
// No data, but we have at least one attribute waiting. Pretend as if we had data to flush.
length = 1;
}
return length >= this.config.getFlushThresholdBytes()
|| (length > 0 && getElapsedSinceLastFlush().compareTo(this.config.getFlushThresholdTime()) >= 0);
}
|
java
|
private Context translateContinue(WyilFile.Stmt.Continue stmt, Context context) {
LoopScope enclosingLoop = context.getEnclosingLoopScope();
enclosingLoop.addContinueContext(context);
return null;
}
|
java
|
public static IAtomContainer getAtomContainer(String formulaString, IChemObjectBuilder builder) {
return MolecularFormulaManipulator.getAtomContainer(MolecularFormulaManipulator.getMolecularFormula(
formulaString, builder));
}
|
java
|
private static FDBigInteger big5powRec(int p) {
if (p < MAX_FIVE_POW) {
return POW_5_CACHE[p];
}
// construct the value.
// recursively.
int q, r;
// in order to compute 5^p,
// compute its square root, 5^(p/2) and square.
// or, let q = p / 2, r = p -q, then
// 5^p = 5^(q+r) = 5^q * 5^r
q = p >> 1;
r = p - q;
FDBigInteger bigq = big5powRec(q);
if (r < SMALL_5_POW.length) {
return bigq.mult(SMALL_5_POW[r]);
} else {
return bigq.mult(big5powRec(r));
}
}
|
java
|
@Override
public MessageContext getMessageContext()
throws IllegalStateException
{
boolean isEndpointMethod = false; // LI2281.07
// Get the method context for the current thread, and check to see if
// the current method is from WebService Endpoint interface. d174057
Object context = EJSContainer.getMethodContext(); // d646139.1
if (context instanceof EJSDeployedSupport)
{
EJSDeployedSupport s = (EJSDeployedSupport) context;
if (s.methodInfo.ivInterface == MethodInterface.SERVICE_ENDPOINT)
{
isEndpointMethod = true;
}
}
// getMessageContext is allowed only from within Web Service Endpoint
// interface methods. StatefulSessionBeanO overrides this method and
// throws an exception for that spec restriction.
if (!isEndpointMethod)
{
IllegalStateException ise;
// Not an allowed method for Stateful beans per EJB Specification.
ise = new IllegalStateException("SessionBean: getMessageContext not " +
"allowed from Non-WebService " +
"Endpoint method");
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "getMessageContext: " + ise);
throw ise;
}
if (messageContextMethod == null) {
try {
messageContextMethod =
Class.forName("com.ibm.ws.webservices.engine.MessageContext")
.getMethod("getCurrentThreadsContext", (Class[]) null);
} catch (SecurityException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"348",
this);
} catch (NoSuchMethodException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"354",
this);
} catch (ClassNotFoundException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"360",
this);
}
}
MessageContext theMessageContext = null;
try {
theMessageContext = (MessageContext) messageContextMethod.invoke(null, (Object[]) null);
} catch (IllegalArgumentException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"372",
this);
} catch (IllegalAccessException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"378",
this);
} catch (InvocationTargetException e) {
FFDCFilter.processException(
e,
CLASS_NAME + ".getMessageContext",
"384",
this);
}
return theMessageContext;
}
|
java
|
private void initDurationButtonGroup() {
m_groupDuration = new CmsRadioButtonGroup();
m_endsAfterRadioButton = new CmsRadioButton(
EndType.TIMES.toString(),
Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0));
m_endsAfterRadioButton.setGroup(m_groupDuration);
m_endsAtRadioButton = new CmsRadioButton(
EndType.DATE.toString(),
Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_DATE_0));
m_endsAtRadioButton.setGroup(m_groupDuration);
m_groupDuration.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
if (handleChange()) {
String value = event.getValue();
if (null != value) {
m_controller.setEndType(value);
}
}
}
});
}
|
java
|
@Override
protected void visitItemAccessNode(ItemAccessNode node) {
// simplify children first
visitChildren(node);
ExprNode baseExpr = node.getChild(0);
ExprNode keyExpr = node.getChild(1);
if (baseExpr instanceof ListLiteralNode && keyExpr instanceof IntegerNode) {
ListLiteralNode listLiteral = (ListLiteralNode) baseExpr;
long index = ((IntegerNode) keyExpr).getValue();
if (index > 0 && index < listLiteral.numChildren()) {
node.getParent().replaceChild(node, listLiteral.getChild((int) index));
} else {
// out of range
node.getParent().replaceChild(node, new NullNode(node.getSourceLocation()));
}
} else if (baseExpr instanceof MapLiteralNode) {
MapLiteralNode mapLiteral = (MapLiteralNode) baseExpr;
for (int i = 0; i < mapLiteral.numChildren(); i += 2) {
if (ExprEquivalence.get().equivalent(keyExpr, mapLiteral.getChild(i))) {
node.getParent().replaceChild(node, mapLiteral.getChild(i + 1));
return;
}
}
// no matching key
node.getParent().replaceChild(node, new NullNode(node.getSourceLocation()));
}
}
|
java
|
public static final boolean deleteTableIfExists(final AmazonDynamoDB dynamo, final DeleteTableRequest deleteTableRequest) {
try {
dynamo.deleteTable(deleteTableRequest);
return true;
} catch (final ResourceNotFoundException e) {
if (LOG.isTraceEnabled()) {
LOG.trace("Table " + deleteTableRequest.getTableName() + " does not exist", e);
}
}
return false;
}
|
python
|
def urlencode_utf8(params):
"""
UTF-8 safe variant of urllib.urlencode.
http://stackoverflow.com/a/8152242
"""
if hasattr(params, 'items'):
params = params.items()
params = (
'='.join((
quote_plus(k.encode('utf8'), safe='/'),
quote_plus(v.encode('utf8'), safe='/')
)) for k, v in params
)
return '&'.join(params)
|
java
|
private void updateDatabase() {
if (getMainConfig().getInt("Database.dbVersion") == 0) {
alertOldDbVersion(0, 1);
//We first check if we have the DB version in the database. If we do, we have a old layout in our hands
String value = getStorageHandler().getStorageEngine().getConfigEntry("dbVersion");
if (value != null) {
//We have a old database, do the whole conversion
try {
new OldFormatConverter().run();
getMainConfig().setValue("Database.dbVersion", 1);
sendConsoleMessage(Level.INFO, "Updated to Revision 1!");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
getMainConfig().setValue("Database.dbVersion", 1);
sendConsoleMessage(Level.INFO, "Updated to Revision 1!");
}
} else if (getMainConfig().getInt("Database.dbVersion") == -1) {
alertOldDbVersion(-1,1);
try {
new OldFormatConverter().step2();
getMainConfig().setValue("Database.dbVersion", 1);
sendConsoleMessage(Level.INFO, "Updated to Revision 1!");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
|
java
|
@NonNull
public static On leftOuterJoin(@NonNull DataSource datasource) {
if (datasource == null) {
throw new IllegalArgumentException("datasource cannot be null.");
}
return new On(Type.LEFT_OUTER, datasource);
}
|
python
|
def timestamp(self, timestamp):
"""
Allows for custom timestamps to be saved with the record.
"""
clone = copy.deepcopy(self)
clone._timestamp = timestamp
return clone
|
python
|
def main():
"""Run the workflow task."""
log = logging.getLogger('sip.mock_workflow_stage')
if len(sys.argv) != 2:
log.critical('Expecting JSON string as first argument!')
return
config = json.loads(sys.argv[1])
log.info('Running mock_workflow_stage (version: %s).', __version__)
log.info('Received configuration: %s', json.dumps(config))
log.info('Starting task')
i = 0
start_time = time.time()
duration = config.get('duration', 20)
while time.time() - start_time <= duration:
time.sleep(duration / 20)
elapsed = time.time() - start_time
log.info(" %s %2i / 20 (elapsed %.2f s)",
config.get('message', 'Progress '),
i + 1, elapsed)
i += 1
log.info('Task complete!')
|
python
|
def set_target(self, new_target):
"""
Sets the new target in mm, the movement starts immediately. If the value is outside
the interval [0, 250] or the motor is already moving, an error is returned, otherwise
the new target is returned."""
try:
self.device.target = new_target
return 'T={}'.format(new_target)
except RuntimeError:
return 'err: not idle'
except ValueError:
return 'err: not 0<=T<=250'
|
python
|
def tb2radiance(self, tb_, **kwargs):
"""Get the radiance from the Tb using the simple non-linear regression
method. SI units of course!
"""
# L = C1 * νc**3 / (exp (C2 νc / [αTb + β]) − 1)
#
# C1 = 2 * h * c**2 and C2 = hc/k
#
lut = kwargs.get('lut', None)
normalized = kwargs.get('normalized', True)
if lut is not None:
raise NotImplementedError('Using a tb-radiance LUT is not yet supported')
if not normalized:
raise NotImplementedError('Deriving the band integrated radiance is not supported')
c_1 = 2 * H_PLANCK * C_SPEED ** 2
c_2 = H_PLANCK * C_SPEED / K_BOLTZMANN
vc_ = SEVIRI[self.bandname][self.platform_name][0]
# Multiply by 100 to get SI units!
vc_ *= 100.0
alpha = SEVIRI[self.bandname][self.platform_name][1]
beta = SEVIRI[self.bandname][self.platform_name][2]
radiance = c_1 * vc_ ** 3 / \
(np.exp(c_2 * vc_ / (alpha * tb_ + beta)) - 1)
unit = 'W/m^2 sr^-1 (m^-1)^-1'
scale = 1.0
return {'radiance': radiance,
'unit': unit,
'scale': scale}
|
java
|
@SuppressWarnings("unchecked")
private void doPopulateDatabasePass(final BuildData buildData) throws BuildProcessingException {
log.info("Doing " + buildData.getBuildLocale() + " Populate Database Pass");
final ContentSpec contentSpec = buildData.getContentSpec();
final Map<String, BaseTopicWrapper<?>> topics = new HashMap<String, BaseTopicWrapper<?>>();
if (buildData.isTranslationBuild()) {
//Translations should reference an existing historical topic with the fixed urls set, so we assume this to be the case
populateTranslatedTopicDatabase(buildData, topics);
} else {
populateDatabaseTopics(buildData, topics);
}
// Check if the app should be shutdown
if (isShuttingDown.get()) {
return;
}
// Add all the levels to the database
DocBookBuildUtilities.addLevelsToDatabase(buildData.getBuildDatabase(), contentSpec.getBaseLevel());
// Check if the app should be shutdown
if (isShuttingDown.get()) {
return;
}
// Process the topics to make sure they are valid
doTopicPass(buildData, topics);
}
|
java
|
public String decryptStr(String data, Charset charset) {
return StrUtil.str(decrypt(data), charset);
}
|
python
|
def get_all_attribute_value(
self, tag_name, attribute, format_value=True, **attribute_filter
):
"""
Yields all the attribute values in xml files which match with the tag name and the specific attribute
:param str tag_name: specify the tag name
:param str attribute: specify the attribute
:param bool format_value: specify if the value needs to be formatted with packagename
"""
tags = self.find_tags(tag_name, **attribute_filter)
for tag in tags:
value = tag.get(attribute) or tag.get(self._ns(attribute))
if value is not None:
if format_value:
yield self._format_value(value)
else:
yield value
|
python
|
def _events_available_during_other_events(
events, slots, X, summation_type=None, **kwargs
):
"""
Constraint that ensures that an event is not scheduled at the same time as
another event for which it is unavailable. Unavailability of events is
either because it is explicitly defined or because they share a tag.
"""
summation = lpu.summation_functions[summation_type]
event_availability_array = lpu.event_availability_array(events)
label = 'Event clashes with another event'
for slot1, slot2 in lpu.concurrent_slots(slots):
for row, event in enumerate(event_availability_array):
if events[row].unavailability:
for col, availability in enumerate(event):
if availability == 0:
yield Constraint(
f'{label} - event: {row} and event: {col}',
summation(
(X[row, slot1], X[col, slot2])
) <= 1 + availability
)
|
python
|
def tran(inimage,outimage,direction='forward',x=None,y=None,
coords=None, coordfile=None,colnames=None,separator=None,
precision=6, output=None,verbose=True):
""" Primary interface to perform coordinate transformations in pixel
coordinates between 2 images using STWCS and full distortion models
read from each image's header.
"""
single_coord = False
# Only use value provided in `coords` if nothing has been specified for coordfile
if coords is not None and coordfile is None:
coordfile = coords
warnings.simplefilter('always',DeprecationWarning)
warnings.warn("Please update calling code to pass in `coordfile` instead of `coords`.",
category=DeprecationWarning)
warnings.simplefilter('default',DeprecationWarning)
if coordfile is not None:
if colnames in util.blank_list:
colnames = ['c1','c2']
# Determine columns which contain pixel positions
cols = util.parse_colnames(colnames,coordfile)
# read in columns from input coordinates file
xyvals = np.loadtxt(coordfile,usecols=cols,delimiter=separator)
if xyvals.ndim == 1: # only 1 entry in coordfile
xlist = [xyvals[0].copy()]
ylist = [xyvals[1].copy()]
else:
xlist = xyvals[:,0].copy()
ylist = xyvals[:,1].copy()
del xyvals
else:
if isinstance(x,np.ndarray):
xlist = x.tolist()
ylist = y.tolist()
elif not isinstance(x,list):
xlist = [x]
ylist = [y]
single_coord = True
else:
xlist = x
ylist = y
# start by reading in WCS+distortion info for each image
im1wcs = wcsutil.HSTWCS(inimage)
if im1wcs.wcs.is_unity():
print("####\nNo valid input WCS found in {}.\n Results may be invalid.\n####\n".format(inimage))
if util.is_blank(outimage):
fname,fextn = fileutil.parseFilename(inimage)
numsci = fileutil.countExtn(fname)
chips = []
for e in range(1,numsci+1):
chips.append(wcsutil.HSTWCS(fname,ext=('sci',e)))
if len(chips) == 0:
chips = [im1wcs]
im2wcs = distortion.utils.output_wcs(chips)
else:
im2wcs = wcsutil.HSTWCS(outimage)
if im2wcs.wcs.is_unity():
print("####\nNo valid output WCS found in {}.\n Results may be invalid.\n####\n".format(outimage))
# Setup the transformation
p2p = wcs_functions.WCSMap(im1wcs,im2wcs)
if direction[0].lower() == 'f':
outx,outy = p2p.forward(xlist,ylist)
else:
outx,outy = p2p.backward(xlist,ylist)
if isinstance(outx,np.ndarray):
outx = outx.tolist()
outy = outy.tolist()
# add formatting based on precision here...
xstr = []
ystr = []
fmt = "%."+repr(precision)+"f"
for ox,oy in zip(outx,outy):
xstr.append(fmt%ox)
ystr.append(fmt%oy)
if verbose or (not verbose and util.is_blank(output)):
print('# Coordinate transformations for ',inimage)
print('# X(in) Y(in) X(out) Y(out)\n')
for xs,ys,a,b in zip(xlist,ylist,xstr,ystr):
print("%.4f %.4f %s %s"%(xs,ys,a,b))
# Create output file, if specified
if output:
f = open(output,mode='w')
f.write("# Coordinates converted from %s\n"%inimage)
for xs,ys in zip(xstr,ystr):
f.write('%s %s\n'%(xs,ys))
f.close()
print('Wrote out results to: ',output)
if single_coord:
outx = outx[0]
outy = outy[0]
return outx,outy
|
python
|
def call(self, name, operation, timeout=10, args=None, **kwargs):
"""Send a message and wait for reply
@param name: name of destination service queue
@param operation: name of service operation to invoke
@param timeout: RPC timeout to await a reply
@param args: dictionary of keyword args to pass to operation.
Use this OR kwargs.
@param kwargs: additional args to pass to operation
"""
if args:
if kwargs:
raise TypeError("specify args dict or keyword arguments, not both")
else:
args = kwargs
# create a direct queue for the reply. This may end up being a
# bottleneck for performance: each rpc call gets a brand new
# exclusive queue. However this approach is used nova.rpc and
# seems to have carried them pretty far. If/when this
# becomes a bottleneck we can set up a long-lived backend queue and
# use correlation_id to deal with concurrent RPC calls. See:
# http://www.rabbitmq.com/tutorials/tutorial-six-python.html
msg_id = uuid.uuid4().hex
# expire the reply queue shortly after the timeout. it will be
# (lazily) deleted by the broker if we don't clean it up first
queue_arguments = {'x-expires': int((timeout + 1) * 1000)}
queue = Queue(name=msg_id, exchange=self._exchange, routing_key=msg_id,
durable=False, queue_arguments=queue_arguments)
messages = []
event = threading.Event()
def _callback(body, message):
messages.append(body)
message.ack()
event.set()
d = dict(op=operation, args=args)
headers = {'reply-to': msg_id, 'sender': self.add_sysname(self.name)}
dest = self.add_sysname(name)
def _declare_and_send(channel):
consumer = Consumer(channel, (queue,), callbacks=(_callback,))
with Producer(channel) as producer:
producer.publish(d, routing_key=dest, headers=headers,
exchange=self._exchange, serializer=self._serializer)
return consumer
log.debug("sending call to %s:%s", dest, operation)
with connections[self._pool_conn].acquire(block=True) as conn:
consumer, channel = self.ensure(conn, _declare_and_send)
try:
self._consume(conn, consumer, timeout=timeout, until_event=event)
# try to delete queue, but don't worry if it fails (will expire)
try:
queue = queue.bind(channel)
queue.delete(nowait=True)
except Exception:
log.exception("error deleting queue")
finally:
conn.maybe_close_channel(channel)
msg_body = messages[0]
if msg_body.get('error'):
raise_error(msg_body['error'])
else:
return msg_body.get('result')
|
python
|
def v_args(inline=False, meta=False, tree=False):
"A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
if [tree, meta, inline].count(True) > 1:
raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.")
def _visitor_args_dec(obj):
return _apply_decorator(obj, _visitor_args_func_dec, inline=inline, meta=meta, whole_tree=tree)
return _visitor_args_dec
|
java
|
public List<T> getDomainObjectsAsList(Set<? extends KEY> keys) {
// it is not "possible" to use huge number of parameters in a
// Restrictions.in criterion and therefore we chunk the query
// into pieces
List<T> all = new ArrayList<T>();
Iterator<? extends KEY> iter = keys.iterator();
List<KEY> chunkKeys = new ArrayList<KEY>();
for (int i = 1; iter.hasNext(); i++) {
KEY element = iter.next();
chunkKeys.add(element);
if ((i % CHUNK_SIZE) == 0) {
all.addAll(getChunk(chunkKeys));
chunkKeys = new ArrayList<KEY>();
}
}
// and then the last part
if (!chunkKeys.isEmpty()) {
all.addAll(getChunk(chunkKeys));
}
return all;
}
|
python
|
def append(self, value):
"""Validate item appending to list."""
self.__field.validate_element(value)
return list.append(self, value)
|
java
|
private ParserContext singleBackingTypeParserContext() throws ExpressionCompileException {
ParserContext context = new ParserContext();
context.setStrongTyping(true);
context.addInput("this", backingType);
PropertyDescriptor[] propertyDescriptors;
try {
propertyDescriptors = Introspector.getBeanInfo(backingType).getPropertyDescriptors();
} catch (IntrospectionException e) {
throw new ExpressionCompileException("Could not read class " + backingType);
}
// read @Visible annotated fields.
for (Field field : backingType.getDeclaredFields()) {
if (field.isAnnotationPresent(Visible.class)) {
context.addInput(field.getName(), field.getType());
if (!field.getAnnotation(Visible.class).readOnly()) {
writeableProperties.add(field.getName());
}
}
}
// read javabean properties -- these override @Visible fields.
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
// skip getClass()
if (CLASS.equals(propertyDescriptor.getName()))
continue;
if (null != propertyDescriptor.getWriteMethod()) {
writeableProperties.add(propertyDescriptor.getName());
}
// if this is a collection, determine its type parameter
if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
Type propertyType;
if (propertyDescriptor.getReadMethod() != null) {
propertyType = propertyDescriptor.getReadMethod().getGenericReturnType();
}
else {
propertyType = propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0];
}
ParameterizedType collectionType = (ParameterizedType) Generics
.getExactSuperType(propertyType, Collection.class);
Class<?>[] parameterClasses = new Class[1];
Type parameterType = collectionType.getActualTypeArguments()[0];
parameterClasses[0] = Generics.erase(parameterType);
context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType(), parameterClasses);
} else {
context.addInput(propertyDescriptor.getName(), propertyDescriptor.getPropertyType());
}
}
return context;
}
|
java
|
public static Years from(TemporalAmount amount) {
if (amount instanceof Years) {
return (Years) amount;
}
Objects.requireNonNull(amount, "amount");
int years = 0;
for (TemporalUnit unit : amount.getUnits()) {
long value = amount.get(unit);
if (value != 0) {
long[] converted = Temporals.convertAmount(value, unit, YEARS);
if (converted[1] != 0) {
throw new DateTimeException(
"Amount could not be converted to a whole number of years: " + value + " " + unit);
}
years = Math.addExact(years, Math.toIntExact(converted[0]));
}
}
return of(years);
}
|
java
|
boolean isBuiltin(Class clazz) {
return clazz == null ? false
: builtin.contains(clazz.getName());
}
|
python
|
def to_string(cls, error_code):
"""Returns the string message for the given error code.
Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.ERROR_UNKNOWN:
return 'Unknown error.'
elif error_code == cls.ERROR_NO_MORE_EVENTS:
return 'There are no more available watchpoint units.'
elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return 'No more address comparisons can be set.'
elif error_code == cls.ERROR_NO_MORE_DATA_COMP:
return 'No more data comparisons can be set.'
elif error_code == cls.ERROR_INVALID_ADDR_MASK:
return 'Invalid flags passed for the address mask.'
elif error_code == cls.ERROR_INVALID_DATA_MASK:
return 'Invalid flags passed for the data mask.'
elif error_code == cls.ERROR_INVALID_ACCESS_MASK:
return 'Invalid flags passed for the access mask.'
return super(JLinkDataErrors, cls).to_string(error_code)
|
java
|
public PeriodConverter[] getPeriodConverters() {
ConverterSet set = iPeriodConverters;
PeriodConverter[] converters = new PeriodConverter[set.size()];
set.copyInto(converters);
return converters;
}
|
python
|
def get_params(self):
"""Get signature and params
"""
params = {
'key': self.get_app_key(),
'uid': self.user_id,
'widget': self.widget_code
}
products_number = len(self.products)
if self.get_api_type() == self.API_GOODS:
if isinstance(self.products, list):
if products_number == 1:
product = self.products[0]
if isinstance(product, Product):
post_trial_product = None
if isinstance(product.get_trial_product(), Product):
post_trial_product = product
product = product.get_trial_product()
params['amount'] = product.get_amount()
params['currencyCode'] = product.get_currency_code()
params['ag_name'] = product.get_name()
params['ag_external_id'] = product.get_id()
params['ag_type'] = product.get_type()
if product.get_type() == Product.TYPE_SUBSCRIPTION:
params['ag_period_length'] = product.get_period_length()
params['ag_period_type'] = product.get_period_type()
if product.is_recurring():
params['ag_recurring'] = 1 if product.is_recurring() else 0
if post_trial_product:
params['ag_trial'] = 1
params['ag_post_trial_external_id'] = post_trial_product.get_id()
params['ag_post_trial_period_length'] = post_trial_product.get_period_length()
params['ag_post_trial_period_type'] = post_trial_product.get_period_type()
params['ag_post_trial_name'] = post_trial_product.get_name()
params['post_trial_amount'] = post_trial_product.get_amount()
params['post_trial_currencyCode'] = post_trial_product.get_currency_code()
else:
self.append_to_errors('Not a Product instance')
else:
self.append_to_errors('Only 1 product is allowed')
elif self.get_api_type() == self.API_CART:
index = 0
for product in self.products:
params['external_ids[' + str(index) + ']'] = product.get_id()
if product.get_amount() > 0:
params['prices[' + str(index) + ']'] = product.get_amount()
if product.get_currency_code() != '' and product.get_currency_code() is not None:
params['currencies[' + str(index) + ']'] = product.get_currency_code()
index += 1
params['sign_version'] = signature_version = str(self.get_default_widget_signature())
if not self.is_empty(self.extra_params, 'sign_version'):
signature_version = params['sign_version'] = str(self.extra_params['sign_version'])
params = self.array_merge(params, self.extra_params)
params['sign'] = self.calculate_signature(params, self.get_secret_key(), int(signature_version))
return params
|
java
|
public ClassLoader getUserCodeClassLoader() {
if (this.userCodeClassLoader == null) {
this.userCodeClassLoader = buildUserCodeClassLoader(jarFiles, classpaths, getClass().getClassLoader());
}
return this.userCodeClassLoader;
}
|
java
|
public boolean isShardingColumn(final String columnName, final String tableName) {
for (TableRule each : tableRules) {
if (each.getLogicTable().equalsIgnoreCase(tableName) && isShardingColumn(each, columnName)) {
return true;
}
}
return false;
}
|
java
|
public org.tensorflow.framework.RPCOptions getRpcOptions() {
return rpcOptions_ == null ? org.tensorflow.framework.RPCOptions.getDefaultInstance() : rpcOptions_;
}
|
java
|
private static String getNotificationID() {
NotificationManager.ID_COUNTER = NotificationManager.ID_COUNTER+1;
logger.fine("Notifications identifier counter: "+ID_COUNTER);
return "Notification#" + (NotificationManager.ID_COUNTER);
}
|
java
|
public void appendKeyValueNode(final KeyValueNode<?> node) throws NumberFormatException {
final String key = node.getKey();
final Object value = node.getValue();
if (isNullOrEmpty(key)) {
// Add the node to the list of nodes
appendChild(node, false);
} else {
KeyValueNode<?> fixedNode = node;
if (key.equalsIgnoreCase(CommonConstants.CS_TITLE_TITLE) && value instanceof String) {
title = (KeyValueNode<String>) node;
setKeyValueNodeKey(title, CommonConstants.CS_TITLE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_ID_TITLE) && (value instanceof String || value instanceof Integer)) {
final KeyValueNode<Integer> idNode;
if (value instanceof String) {
idNode = new KeyValueNode<Integer>(CommonConstants.CS_ID_TITLE, Integer.parseInt((String) value));
cloneKeyValueNode(node, idNode);
fixedNode = idNode;
} else {
idNode = (KeyValueNode<Integer>) node;
}
id = idNode;
setKeyValueNodeKey(id, CommonConstants.CS_ID_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_CHECKSUM_TITLE) && value instanceof String) {
checksum = (KeyValueNode<String>) node;
setKeyValueNodeKey(checksum, CommonConstants.CS_CHECKSUM_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_PRODUCT_TITLE) && value instanceof String) {
product = (KeyValueNode<String>) node;
setKeyValueNodeKey(product, CommonConstants.CS_PRODUCT_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_VERSION_TITLE) && value instanceof String) {
version = (KeyValueNode<String>) node;
setKeyValueNodeKey(version, CommonConstants.CS_VERSION_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BOOK_TYPE_TITLE) && (value instanceof String || value instanceof BookType)) {
final KeyValueNode<BookType> bookTypeNode;
if (value instanceof String) {
bookTypeNode = new KeyValueNode<BookType>(key, BookType.getBookType((String) value));
cloneKeyValueNode(node, bookTypeNode);
fixedNode = bookTypeNode;
} else {
bookTypeNode = (KeyValueNode<BookType>) node;
}
bookType = bookTypeNode;
setKeyValueNodeKey(bookType, CommonConstants.CS_BOOK_TYPE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_EDITION_TITLE) && value instanceof String) {
edition = (KeyValueNode<String>) node;
setKeyValueNodeKey(edition, CommonConstants.CS_EDITION_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BOOK_VERSION_TITLE) && value instanceof String) {
bookVersion = (KeyValueNode<String>) node;
setKeyValueNodeKey(bookVersion, CommonConstants.CS_BOOK_VERSION_TITLE);
} else if (key.equalsIgnoreCase(
CommonConstants.CS_BUG_LINKS_TITLE) && (value instanceof String || value instanceof BugLinkType)) {
final KeyValueNode<BugLinkType> bugLinkNode;
if (value instanceof String) {
bugLinkNode = new KeyValueNode<BugLinkType>(CommonConstants.CS_BUG_LINKS_TITLE, BugLinkType.getType((String) value));
cloneKeyValueNode(node, bugLinkNode);
fixedNode = bugLinkNode;
} else {
bugLinkNode = (KeyValueNode<BugLinkType>) value;
}
bugLinks = bugLinkNode;
setKeyValueNodeKey(bugLinks, CommonConstants.CS_BUG_LINKS_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_COMPONENT_TITLE) && value instanceof String) {
bugzillaComponent = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaComponent, CommonConstants.CS_BUGZILLA_COMPONENT_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_PRODUCT_TITLE) && value instanceof String) {
bugzillaProduct = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaProduct, CommonConstants.CS_BUGZILLA_PRODUCT_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_VERSION_TITLE) && value instanceof String) {
bugzillaVersion = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaVersion, CommonConstants.CS_BUGZILLA_VERSION_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_KEYWORDS_TITLE) && value instanceof String) {
bugzillaKeywords = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaKeywords, CommonConstants.CS_BUGZILLA_KEYWORDS_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_SERVER_TITLE) && value instanceof String) {
bugzillaServer = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaServer, CommonConstants.CS_BUGZILLA_SERVER_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_URL_TITLE) && value instanceof String) {
bugzillaURL = (KeyValueNode<String>) node;
setKeyValueNodeKey(bugzillaURL, CommonConstants.CS_BUGZILLA_URL_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BUGZILLA_ASSIGNEE_TITLE) && (value instanceof String || value instanceof Boolean)) {
final KeyValueNode<Boolean> injectBugzillaAssigneeNode;
if (value instanceof String) {
final Boolean fixedValue;
if (((String) value).equalsIgnoreCase("ON")) {
fixedValue = true;
} else {
fixedValue = Boolean.parseBoolean((String) value);
}
injectBugzillaAssigneeNode = new KeyValueNode<Boolean>(CommonConstants.CS_BUGZILLA_ASSIGNEE_TITLE, fixedValue);
cloneKeyValueNode(node, injectBugzillaAssigneeNode);
fixedNode = injectBugzillaAssigneeNode;
} else {
injectBugzillaAssigneeNode = (KeyValueNode<Boolean>) node;
}
injectBugzillaAssignee = injectBugzillaAssigneeNode;
setKeyValueNodeKey(injectBugzillaAssignee, CommonConstants.CS_BUGZILLA_ASSIGNEE_TITLE);
} else if (key.equalsIgnoreCase(
CommonConstants.CS_INLINE_INJECTION_TITLE) && (value instanceof String || value instanceof InjectionOptions)) {
final KeyValueNode<InjectionOptions> injectionOptionsNode;
if (value instanceof String) {
injectionOptionsNode = new KeyValueNode<InjectionOptions>(CommonConstants.CS_INLINE_INJECTION_TITLE,
new InjectionOptions((String) value));
cloneKeyValueNode(node, injectionOptionsNode);
fixedNode = injectionOptionsNode;
} else {
injectionOptionsNode = (KeyValueNode<InjectionOptions>) node;
}
injectionOptions = injectionOptionsNode;
setKeyValueNodeKey(injectionOptions, CommonConstants.CS_INLINE_INJECTION_TITLE);
} else if ((key.equalsIgnoreCase(CommonConstants.CS_FORMAT_TITLE) || key.equalsIgnoreCase("DTD")) && value instanceof String) {
format = (KeyValueNode<String>) node;
setKeyValueNodeKey(format, CommonConstants.CS_FORMAT_TITLE);
if (value != null) {
if (((String) value).equalsIgnoreCase(CommonConstants.DOCBOOK_50_TITLE)) {
format.setValue(CommonConstants.DOCBOOK_50_TITLE);
} else if (((String) value).equalsIgnoreCase(CommonConstants.DOCBOOK_45_TITLE)) {
format.setValue(CommonConstants.DOCBOOK_45_TITLE);
}
}
} else if (key.equalsIgnoreCase(CSConstants.OUTPUT_STYLE_TITLE) && value instanceof String) {
outputStyle = (KeyValueNode<String>) node;
setKeyValueNodeKey(outputStyle, CSConstants.OUTPUT_STYLE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_PUBSNUMBER_TITLE) && (value instanceof String || value instanceof Integer)) {
final KeyValueNode<Integer> pubsNumberNode;
if (value instanceof String) {
pubsNumberNode = new KeyValueNode<Integer>(key, Integer.parseInt((String) value));
cloneKeyValueNode(node, pubsNumberNode);
fixedNode = pubsNumberNode;
} else {
pubsNumberNode = (KeyValueNode<Integer>) node;
}
pubsNumber = pubsNumberNode;
setKeyValueNodeKey(pubsNumber, CommonConstants.CS_PUBSNUMBER_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_PUBLICAN_CFG_TITLE) && value instanceof String) {
publicanCfgs.put(DEFAULT_PUBLICAN_CFG_KEY, (KeyValueNode<String>) node);
setKeyValueNodeKey(node, CommonConstants.CS_PUBLICAN_CFG_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BRAND_TITLE) && value instanceof String) {
brand = (KeyValueNode<String>) node;
setKeyValueNodeKey(brand, CommonConstants.CS_BRAND_TITLE);
} else if ((key.equalsIgnoreCase(CommonConstants.CS_ABSTRACT_TITLE) || key.equalsIgnoreCase(
CommonConstants.CS_ABSTRACT_ALTERNATE_TITLE)) && (value instanceof String || value instanceof SpecTopic)) {
if (value instanceof SpecTopic) {
abstractTopic = (KeyValueNode<SpecTopic>) node;
if (value != null) {
abstractTopic.getValue().setTopicType(TopicType.ABSTRACT);
}
setKeyValueNodeKey(abstractTopic, CommonConstants.CS_ABSTRACT_TITLE);
} else {
description = (KeyValueNode<String>) node;
setKeyValueNodeKey(description, CommonConstants.CS_ABSTRACT_TITLE);
}
} else if (key.equalsIgnoreCase(CommonConstants.CS_COPYRIGHT_HOLDER_TITLE) && value instanceof String) {
copyrightHolder = (KeyValueNode<String>) node;
setKeyValueNodeKey(copyrightHolder, CommonConstants.CS_COPYRIGHT_HOLDER_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_COPYRIGHT_YEAR_TITLE) && value instanceof String) {
copyrightYear = (KeyValueNode<String>) node;
setKeyValueNodeKey(copyrightYear, CommonConstants.CS_COPYRIGHT_YEAR_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_SUBTITLE_TITLE) && value instanceof String) {
subtitle = (KeyValueNode<String>) node;
setKeyValueNodeKey(subtitle, CommonConstants.CS_SUBTITLE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_REV_HISTORY_TITLE) && value instanceof SpecTopic) {
revisionHistory = (KeyValueNode<SpecTopic>) node;
if (value != null) {
revisionHistory.getValue().setTopicType(TopicType.REVISION_HISTORY);
}
setKeyValueNodeKey(revisionHistory, CommonConstants.CS_REV_HISTORY_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_FEEDBACK_TITLE) && value instanceof SpecTopic) {
feedback = (KeyValueNode<SpecTopic>) node;
if (value != null) {
feedback.getValue().setTopicType(TopicType.FEEDBACK);
}
setKeyValueNodeKey(feedback, CommonConstants.CS_FEEDBACK_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_LEGAL_NOTICE_TITLE) && value instanceof SpecTopic) {
legalNotice = (KeyValueNode<SpecTopic>) node;
if (value != null) {
legalNotice.getValue().setTopicType(TopicType.LEGAL_NOTICE);
}
setKeyValueNodeKey(legalNotice, CommonConstants.CS_LEGAL_NOTICE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_AUTHOR_GROUP_TITLE) && value instanceof SpecTopic) {
authorGroup = (KeyValueNode<SpecTopic>) node;
if (value != null) {
authorGroup.getValue().setTopicType(TopicType.AUTHOR_GROUP);
}
setKeyValueNodeKey(authorGroup, CommonConstants.CS_AUTHOR_GROUP_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_MAVEN_ARTIFACT_ID_TITLE) && value instanceof String) {
artifactId = (KeyValueNode<String>) node;
setKeyValueNodeKey(artifactId, CommonConstants.CS_MAVEN_ARTIFACT_ID_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_MAVEN_GROUP_ID_TITLE) && value instanceof String) {
groupId = (KeyValueNode<String>) node;
setKeyValueNodeKey(groupId, CommonConstants.CS_MAVEN_GROUP_ID_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_MAVEN_POM_VERSION_TITLE) && value instanceof String) {
pomVersion = (KeyValueNode<String>) node;
setKeyValueNodeKey(pomVersion, CommonConstants.CS_MAVEN_POM_VERSION_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_BRAND_LOGO_TITLE) && value instanceof String) {
brandLogo = (KeyValueNode<String>) node;
setKeyValueNodeKey(brandLogo, CommonConstants.CS_BRAND_LOGO_TITLE);
} else if ((key.equalsIgnoreCase(CommonConstants.CS_FILE_TITLE) || key.equalsIgnoreCase(
CommonConstants.CS_FILE_SHORT_TITLE)) && node instanceof FileList) {
files = (FileList) node;
setKeyValueNodeKey(files, CommonConstants.CS_FILE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_JIRA_COMPONENT_TITLE) && value instanceof String) {
jiraComponent = (KeyValueNode<String>) node;
setKeyValueNodeKey(jiraComponent, CommonConstants.CS_JIRA_COMPONENT_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_JIRA_PROJECT_TITLE) && value instanceof String) {
jiraProject = (KeyValueNode<String>) node;
setKeyValueNodeKey(jiraProject, CommonConstants.CS_JIRA_PROJECT_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_JIRA_VERSION_TITLE) && value instanceof String) {
jiraVersion = (KeyValueNode<String>) node;
setKeyValueNodeKey(jiraVersion, CommonConstants.CS_JIRA_VERSION_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_JIRA_LABELS_TITLE) && value instanceof String) {
jiraLabels = (KeyValueNode<String>) node;
setKeyValueNodeKey(jiraLabels, CommonConstants.CS_JIRA_LABELS_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_JIRA_SERVER_TITLE) && value instanceof String) {
jiraServer = (KeyValueNode<String>) node;
setKeyValueNodeKey(jiraServer, CommonConstants.CS_JIRA_SERVER_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_ENTITIES_TITLE) && value instanceof String) {
entities = (KeyValueNode<String>) node;
setKeyValueNodeKey(entities, CommonConstants.CS_ENTITIES_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_DEFAULT_PUBLICAN_CFG_TITLE) && value instanceof String) {
defaultPublicanCfg = (KeyValueNode<String>) node;
setKeyValueNodeKey(defaultPublicanCfg, CommonConstants.CS_DEFAULT_PUBLICAN_CFG_TITLE);
} else if (CSConstants.CUSTOM_PUBLICAN_CFG_PATTERN.matcher(key).matches() && value instanceof String) {
final Matcher matcher = CSConstants.CUSTOM_PUBLICAN_CFG_PATTERN.matcher(key);
matcher.find();
final String name = matcher.group(1);
setKeyValueNodeKey(node, name + "-" + CommonConstants.CS_PUBLICAN_CFG_TITLE);
publicanCfgs.put(name, (KeyValueNode<String>) node);
} else if (key.equalsIgnoreCase(CommonConstants.CS_INDEX_TITLE) && (value instanceof String || value instanceof Boolean)) {
final KeyValueNode<Boolean> useIndexNode;
if (value instanceof String) {
final Boolean fixedValue;
if (((String) value).equalsIgnoreCase("ON")) {
fixedValue = true;
} else {
fixedValue = Boolean.parseBoolean((String) value);
}
useIndexNode = new KeyValueNode<Boolean>(CommonConstants.CS_INDEX_TITLE, fixedValue);
cloneKeyValueNode(node, useIndexNode);
fixedNode = useIndexNode;
} else {
useIndexNode = (KeyValueNode<Boolean>) node;
}
includeIndex = useIndexNode;
setKeyValueNodeKey(includeIndex, CommonConstants.CS_INDEX_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_LOCALE_TITLE) && value instanceof String) {
locale = (KeyValueNode<String>) node;
setKeyValueNodeKey(locale, CommonConstants.CS_LOCALE_TITLE);
} else if (key.equalsIgnoreCase(CommonConstants.CS_DEFAULT_PREFACE) && value instanceof String) {
final KeyValueNode<Boolean> useDefaultPrefaceNode;
if (value instanceof String) {
final Boolean fixedValue;
if (((String) value).equalsIgnoreCase("ON")) {
fixedValue = true;
} else {
fixedValue = Boolean.parseBoolean((String) value);
}
useDefaultPrefaceNode = new KeyValueNode<Boolean>(CommonConstants.CS_DEFAULT_PREFACE, fixedValue);
cloneKeyValueNode(node, useDefaultPrefaceNode);
fixedNode = useDefaultPrefaceNode;
} else {
useDefaultPrefaceNode = (KeyValueNode<Boolean>) node;
}
useDefaultPreface = useDefaultPrefaceNode;
setKeyValueNodeKey(useDefaultPreface, CommonConstants.CS_DEFAULT_PREFACE);
}
// Add the node to the list of nodes
appendChild(fixedNode, false);
}
}
|
python
|
def fcast(value: float) -> TensorLike:
"""Cast to float tensor"""
newvalue = tf.cast(value, FTYPE)
if DEVICE == 'gpu':
newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover
return newvalue
|
python
|
def mx_page_trees(self, mx_page):
""" return trees assigned to given MX Page """
resp = dict()
for tree_name, tree in self.scheduler.timetable.trees.items():
if tree.mx_page == mx_page:
rest_tree = self._get_tree_details(tree_name)
resp[tree.tree_name] = rest_tree.document
return resp
|
java
|
public final EObject ruleXClosure() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
Token otherlv_3=null;
Token lv_explicitSyntax_5_0=null;
Token otherlv_7=null;
EObject lv_declaredFormalParameters_2_0 = null;
EObject lv_declaredFormalParameters_4_0 = null;
EObject lv_expression_6_0 = null;
enterRule();
try {
// InternalXbase.g:2491:2: ( ( ( ( ( () '[' ) )=> ( () otherlv_1= '[' ) ) ( ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) ) )? ( (lv_expression_6_0= ruleXExpressionInClosure ) ) otherlv_7= ']' ) )
// InternalXbase.g:2492:2: ( ( ( ( () '[' ) )=> ( () otherlv_1= '[' ) ) ( ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) ) )? ( (lv_expression_6_0= ruleXExpressionInClosure ) ) otherlv_7= ']' )
{
// InternalXbase.g:2492:2: ( ( ( ( () '[' ) )=> ( () otherlv_1= '[' ) ) ( ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) ) )? ( (lv_expression_6_0= ruleXExpressionInClosure ) ) otherlv_7= ']' )
// InternalXbase.g:2493:3: ( ( ( () '[' ) )=> ( () otherlv_1= '[' ) ) ( ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) ) )? ( (lv_expression_6_0= ruleXExpressionInClosure ) ) otherlv_7= ']'
{
// InternalXbase.g:2493:3: ( ( ( () '[' ) )=> ( () otherlv_1= '[' ) )
// InternalXbase.g:2494:4: ( ( () '[' ) )=> ( () otherlv_1= '[' )
{
// InternalXbase.g:2500:4: ( () otherlv_1= '[' )
// InternalXbase.g:2501:5: () otherlv_1= '['
{
// InternalXbase.g:2501:5: ()
// InternalXbase.g:2502:6:
{
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getXClosureAccess().getXClosureAction_0_0_0(),
current);
}
}
otherlv_1=(Token)match(input,54,FOLLOW_38); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getXClosureAccess().getLeftSquareBracketKeyword_0_0_1());
}
}
}
// InternalXbase.g:2514:3: ( ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) ) )?
int alt42=2;
alt42 = dfa42.predict(input);
switch (alt42) {
case 1 :
// InternalXbase.g:2515:4: ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) )
{
// InternalXbase.g:2538:4: ( ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) ) )
// InternalXbase.g:2539:5: ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )? ( (lv_explicitSyntax_5_0= '|' ) )
{
// InternalXbase.g:2539:5: ( ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )* )?
int alt41=2;
int LA41_0 = input.LA(1);
if ( (LA41_0==RULE_ID||LA41_0==32||LA41_0==49) ) {
alt41=1;
}
switch (alt41) {
case 1 :
// InternalXbase.g:2540:6: ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) ) (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )*
{
// InternalXbase.g:2540:6: ( (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter ) )
// InternalXbase.g:2541:7: (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter )
{
// InternalXbase.g:2541:7: (lv_declaredFormalParameters_2_0= ruleJvmFormalParameter )
// InternalXbase.g:2542:8: lv_declaredFormalParameters_2_0= ruleJvmFormalParameter
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXClosureAccess().getDeclaredFormalParametersJvmFormalParameterParserRuleCall_1_0_0_0_0());
}
pushFollow(FOLLOW_39);
lv_declaredFormalParameters_2_0=ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXClosureRule());
}
add(
current,
"declaredFormalParameters",
lv_declaredFormalParameters_2_0,
"org.eclipse.xtext.xbase.Xbase.JvmFormalParameter");
afterParserOrEnumRuleCall();
}
}
}
// InternalXbase.g:2559:6: (otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) ) )*
loop40:
do {
int alt40=2;
int LA40_0 = input.LA(1);
if ( (LA40_0==48) ) {
alt40=1;
}
switch (alt40) {
case 1 :
// InternalXbase.g:2560:7: otherlv_3= ',' ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) )
{
otherlv_3=(Token)match(input,48,FOLLOW_13); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_3, grammarAccess.getXClosureAccess().getCommaKeyword_1_0_0_1_0());
}
// InternalXbase.g:2564:7: ( (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter ) )
// InternalXbase.g:2565:8: (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter )
{
// InternalXbase.g:2565:8: (lv_declaredFormalParameters_4_0= ruleJvmFormalParameter )
// InternalXbase.g:2566:9: lv_declaredFormalParameters_4_0= ruleJvmFormalParameter
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXClosureAccess().getDeclaredFormalParametersJvmFormalParameterParserRuleCall_1_0_0_1_1_0());
}
pushFollow(FOLLOW_39);
lv_declaredFormalParameters_4_0=ruleJvmFormalParameter();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXClosureRule());
}
add(
current,
"declaredFormalParameters",
lv_declaredFormalParameters_4_0,
"org.eclipse.xtext.xbase.Xbase.JvmFormalParameter");
afterParserOrEnumRuleCall();
}
}
}
}
break;
default :
break loop40;
}
} while (true);
}
break;
}
// InternalXbase.g:2585:5: ( (lv_explicitSyntax_5_0= '|' ) )
// InternalXbase.g:2586:6: (lv_explicitSyntax_5_0= '|' )
{
// InternalXbase.g:2586:6: (lv_explicitSyntax_5_0= '|' )
// InternalXbase.g:2587:7: lv_explicitSyntax_5_0= '|'
{
lv_explicitSyntax_5_0=(Token)match(input,56,FOLLOW_40); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_explicitSyntax_5_0, grammarAccess.getXClosureAccess().getExplicitSyntaxVerticalLineKeyword_1_0_1_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXClosureRule());
}
setWithLastConsumed(current, "explicitSyntax", true, "|");
}
}
}
}
}
break;
}
// InternalXbase.g:2601:3: ( (lv_expression_6_0= ruleXExpressionInClosure ) )
// InternalXbase.g:2602:4: (lv_expression_6_0= ruleXExpressionInClosure )
{
// InternalXbase.g:2602:4: (lv_expression_6_0= ruleXExpressionInClosure )
// InternalXbase.g:2603:5: lv_expression_6_0= ruleXExpressionInClosure
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXClosureAccess().getExpressionXExpressionInClosureParserRuleCall_2_0());
}
pushFollow(FOLLOW_41);
lv_expression_6_0=ruleXExpressionInClosure();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXClosureRule());
}
set(
current,
"expression",
lv_expression_6_0,
"org.eclipse.xtext.xbase.Xbase.XExpressionInClosure");
afterParserOrEnumRuleCall();
}
}
}
otherlv_7=(Token)match(input,55,FOLLOW_2); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_7, grammarAccess.getXClosureAccess().getRightSquareBracketKeyword_3());
}
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
}
|
python
|
def revert_snapshot(name, snap_name, runas=None):
'''
Revert a VM to a snapshot
:param str name:
Name/ID of VM to revert to a snapshot
:param str snap_name:
Name/ID of snapshot to revert to
:param str runas:
The user that the prlctl command will be run as
Example:
.. code-block:: bash
salt '*' parallels.revert_snapshot macvm base-with-updates runas=macdev
'''
# Validate VM and snapshot names
name = salt.utils.data.decode(name)
snap_name = _validate_snap_name(name, snap_name, runas=runas)
# Construct argument list
args = [name, '--id', snap_name]
# Execute command and return output
return prlctl('snapshot-switch', args, runas=runas)
|
java
|
public Actions keyDown(CharSequence key) {
if (isBuildingActions()) {
action.addAction(new KeyDownAction(jsonKeyboard, jsonMouse, asKeys(key)));
}
return addKeyAction(key, codePoint -> tick(defaultKeyboard.createKeyDown(codePoint)));
}
|
java
|
public static base_responses add(nitro_service client, server resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
server addresources[] = new server[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new server();
addresources[i].name = resources[i].name;
addresources[i].ipaddress = resources[i].ipaddress;
addresources[i].domain = resources[i].domain;
addresources[i].translationip = resources[i].translationip;
addresources[i].translationmask = resources[i].translationmask;
addresources[i].domainresolveretry = resources[i].domainresolveretry;
addresources[i].state = resources[i].state;
addresources[i].ipv6address = resources[i].ipv6address;
addresources[i].comment = resources[i].comment;
addresources[i].td = resources[i].td;
}
result = add_bulk_request(client, addresources);
}
return result;
}
|
python
|
def take_bug_reports(ads, test_name, begin_time, destination=None):
"""Takes bug reports on a list of android devices.
If you want to take a bug report, call this function with a list of
android_device objects in on_fail. But reports will be taken on all the
devices in the list concurrently. Bug report takes a relative long
time to take, so use this cautiously.
Args:
ads: A list of AndroidDevice instances.
test_name: Name of the test method that triggered this bug report.
begin_time: timestamp taken when the test started, can be either
string or int.
destination: string, path to the directory where the bugreport
should be saved.
"""
begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time))
def take_br(test_name, begin_time, ad, destination):
ad.take_bug_report(test_name, begin_time, destination=destination)
args = [(test_name, begin_time, ad, destination) for ad in ads]
utils.concurrent_exec(take_br, args)
|
python
|
def yara_match(file_path, rules):
"""Callback for a newly extracted file"""
print('New Extracted File: {:s}'.format(file_path))
print('Mathes:')
pprint(rules.match(file_path))
|
java
|
private void dispatch(final ExecutionReference reference, final ExecutableFlow exflow,
final Executor choosenExecutor) throws ExecutorManagerException {
exflow.setUpdateTime(System.currentTimeMillis());
this.executorLoader.assignExecutor(choosenExecutor.getId(),
exflow.getExecutionId());
try {
this.apiGateway.callWithExecutable(exflow, choosenExecutor,
ConnectorParams.EXECUTE_ACTION);
} catch (final ExecutorManagerException ex) {
logger.error("Rolling back executor assignment for execution id:"
+ exflow.getExecutionId(), ex);
this.executorLoader.unassignExecutor(exflow.getExecutionId());
throw new ExecutorManagerException(ex);
}
reference.setExecutor(choosenExecutor);
// move from flow to running flows
this.runningExecutions.get().put(exflow.getExecutionId(), new Pair<>(reference, exflow));
synchronized (this.runningExecutions.get()) {
// Wake up RunningExecutionsUpdaterThread from wait() so that it will immediately check status
// from executor(s). Normally flows will run at least some time and can't be cleaned up
// immediately, so there will be another wait round (or many, actually), but for unit tests
// this is significant to let them run quickly.
this.runningExecutions.get().notifyAll();
}
synchronized (this) {
// wake up all internal waiting threads, too
this.notifyAll();
}
logger.info(String.format(
"Successfully dispatched exec %d with error count %d",
exflow.getExecutionId(), reference.getNumErrors()));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.