language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def path(self):
"""URL path for change set APIs.
:rtype: str
:returns: the path based on project, zone, and change set names.
"""
return "/projects/%s/managedZones/%s/changes/%s" % (
self.zone.project,
self.zone.name,
self.name,
) |
python | def _collect_fields(self):
'''
Collects all the attributes that are instance of
:class:`incoming.datatypes.Types`. These attributes are used for
defining rules of validation for every field/key in the incoming JSON
payload.
:returns: a tuple of attribute names from an instance of a sub-class
of :class:`PayloadValidator`.
'''
fields = []
for prop in dir(self):
if isinstance(getattr(self, prop), Types):
fields.append(prop)
if not len(fields):
raise Exception('No keys/fields defined in the validator class.')
return tuple(fields) |
python | def process_extensions(
headers: Headers,
available_extensions: Optional[Sequence[ClientExtensionFactory]],
) -> List[Extension]:
"""
Handle the Sec-WebSocket-Extensions HTTP response header.
Check that each extension is supported, as well as its parameters.
Return the list of accepted extensions.
Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the
connection.
:rfc:`6455` leaves the rules up to the specification of each
:extension.
To provide this level of flexibility, for each extension accepted by
the server, we check for a match with each extension available in the
client configuration. If no match is found, an exception is raised.
If several variants of the same extension are accepted by the server,
it may be configured severel times, which won't make sense in general.
Extensions must implement their own requirements. For this purpose,
the list of previously accepted extensions is provided.
Other requirements, for example related to mandatory extensions or the
order of extensions, may be implemented by overriding this method.
"""
accepted_extensions: List[Extension] = []
header_values = headers.get_all("Sec-WebSocket-Extensions")
if header_values:
if available_extensions is None:
raise InvalidHandshake("No extensions supported")
parsed_header_values: List[ExtensionHeader] = sum(
[parse_extension(header_value) for header_value in header_values], []
)
for name, response_params in parsed_header_values:
for extension_factory in available_extensions:
# Skip non-matching extensions based on their name.
if extension_factory.name != name:
continue
# Skip non-matching extensions based on their params.
try:
extension = extension_factory.process_response_params(
response_params, accepted_extensions
)
except NegotiationError:
continue
# Add matching extension to the final list.
accepted_extensions.append(extension)
# Break out of the loop once we have a match.
break
# If we didn't break from the loop, no extension in our list
# matched what the server sent. Fail the connection.
else:
raise NegotiationError(
f"Unsupported extension: "
f"name = {name}, params = {response_params}"
)
return accepted_extensions |
python | def iteritems(self):
"""
Iterate through the property names and values of this CIM instance.
Each iteration item is a tuple of the property name (in the original
lexical case) and the property value.
The order of properties is preserved.
"""
for key, val in self.properties.iteritems():
yield (key, val.value) |
java | @Override
public RTMPConnection getConnection(int clientId) {
log.trace("Getting connection by client id: {}", clientId);
for (RTMPConnection conn : connMap.values()) {
if (conn.getId() == clientId) {
return connMap.get(conn.getSessionId());
}
}
return null;
} |
python | def verify(self, **kwargs):
"""Authorization Request parameters that are OPTIONAL in the OAuth 2.0
specification MAY be included in the OpenID Request Object without also
passing them as OAuth 2.0 Authorization Request parameters, with one
exception: The scope parameter MUST always be present in OAuth 2.0
Authorization Request parameters.
All parameter values that are present both in the OAuth 2.0
Authorization Request and in the OpenID Request Object MUST exactly
match."""
super(AuthorizationRequest, self).verify(**kwargs)
clear_verified_claims(self)
args = {}
for arg in ["keyjar", "opponent_id", "sender", "alg", "encalg",
"encenc"]:
try:
args[arg] = kwargs[arg]
except KeyError:
pass
if "opponent_id" not in kwargs:
args["opponent_id"] = self["client_id"]
if "request" in self:
if isinstance(self["request"], str):
# Try to decode the JWT, checks the signature
oidr = OpenIDRequest().from_jwt(str(self["request"]), **args)
# check if something is change in the original message
for key, val in oidr.items():
if key in self:
if self[key] != val:
# log but otherwise ignore
logger.warning('{} != {}'.format(self[key], val))
# remove all claims
_keys = list(self.keys())
for key in _keys:
if key not in oidr:
del self[key]
self.update(oidr)
# replace the JWT with the parsed and verified instance
self[verified_claim_name("request")] = oidr
if "id_token_hint" in self:
if isinstance(self["id_token_hint"], str):
idt = IdToken().from_jwt(str(self["id_token_hint"]), **args)
self["verified_id_token_hint"] = idt
if "response_type" not in self:
raise MissingRequiredAttribute("response_type missing", self)
_rt = self["response_type"]
if "id_token" in _rt:
if "nonce" not in self:
raise MissingRequiredAttribute("Nonce missing", self)
else:
try:
if self['nonce'] != kwargs['nonce']:
raise ValueError(
'Nonce in id_token not matching nonce in authz '
'request')
except KeyError:
pass
if "openid" not in self.get("scope", []):
raise MissingRequiredValue("openid not in scope", self)
if "offline_access" in self.get("scope", []):
if "prompt" not in self or "consent" not in self["prompt"]:
raise MissingRequiredValue("consent in prompt", self)
if "prompt" in self:
if "none" in self["prompt"] and len(self["prompt"]) > 1:
raise InvalidRequest("prompt none combined with other value",
self)
return True |
java | public static String mergeToSingleUnderscore(String s) {
StringBuffer buffer = new StringBuffer();
boolean inMerge = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ' || c == '_') {
if (!inMerge) {
buffer.append('_');
}
inMerge = true;
} else {
inMerge = false;
buffer.append(c);
}
}
return buffer.toString();
} |
java | public List<NodeTypeData> getAllNodeTypes()
{
try
{
return this.nodeTypeRepository.getAllNodeTypes();
}
catch (RepositoryException e)
{
LOG.error(e.getLocalizedMessage());
}
return new ArrayList<NodeTypeData>();
} |
java | @Override public void init(ProcessingEnvironment procEnv) {
super.init(procEnv);
if (System.getProperty("lombok.disable") != null) {
lombokDisabled = true;
return;
}
this.processingEnv = procEnv;
this.javacProcessingEnv = getJavacProcessingEnvironment(procEnv);
this.javacFiler = getJavacFiler(procEnv.getFiler());
placePostCompileAndDontMakeForceRoundDummiesHook();
trees = Trees.instance(javacProcessingEnv);
transformer = new JavacTransformer(procEnv.getMessager(), trees);
SortedSet<Long> p = transformer.getPriorities();
if (p.isEmpty()) {
this.priorityLevels = new long[] {0L};
this.priorityLevelsRequiringResolutionReset = new HashSet<Long>();
} else {
this.priorityLevels = new long[p.size()];
int i = 0;
for (Long prio : p) this.priorityLevels[i++] = prio;
this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset();
}
} |
java | public void setFQNType(Integer newFQNType) {
Integer oldFQNType = fqnType;
fqnType = newFQNType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FULLY_QUALIFIED_NAME__FQN_TYPE, oldFQNType, fqnType));
} |
python | def datetime_from_timestamp(n, epoch=datetime.datetime.fromordinal(693594)):
"""Return datetime object from timestamp in Excel serial format.
Examples
--------
>>> datetime_from_timestamp(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
"""
return epoch + datetime.timedelta(n) |
python | def check_valid(line0, line1):
"""
Check :func:`word_embedding_loader.loader.glove.check_valid` for the API.
"""
data0 = line0.split(b' ')
if len(data0) != 2:
return False
# check if data0 is int values
try:
map(int, data0)
_parse_line(line1, float)
except:
return False
return True |
python | def delete_version(self, version_id=None):
"""
Deletes this draft version (revert to published)
:raises NotAllowed: if this version is already published.
:raises Conflict: if this version is already deleted.
"""
if not version_id:
version_id = self.version.id
target_url = self._client.get_url('VERSION', 'DELETE', 'single', {'layer_id': self.id, 'version_id': version_id})
r = self._client.request('DELETE', target_url)
logger.info("delete_version(): %s", r.status_code) |
python | def write_input(self, atoms=None, properties=['energy'], system_changes=all_changes):
'''Write input file(s).'''
with work_dir(self.directory):
self.calc.write_input(self, atoms, properties, system_changes)
self.write_pbs_in(properties)
subprocess.call(self.copy_out_cmd % {
'ldir': self.directory,
'rdir': self.parameters['rdir'],
'user': self.parameters['user'],
'host': self.parameters['host']
}, shell=True) |
python | def get_bytes(self, *args, **kwargs):
""" no string decoding performed """
return super(XClient, self).get(*args, **kwargs) |
python | def run(self, args):
"""
Lists project names.
:param args Namespace arguments parsed from the command line
"""
long_format = args.long_format
# project_name and auth_role args are mutually exclusive
if args.project_name or args.project_id:
project = self.fetch_project(args, must_exist=True, include_children=True)
self.print_project_details(project, long_format)
else:
self.print_project_list_details(args.auth_role, long_format) |
python | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date and end_date in ISO 8601 format
:rtype: list of str
"""
start_dt = iso_to_datetime(start_date)
end_dt = iso_to_datetime(end_date)
num_days = int((end_dt - start_dt).days)
return [datetime_to_iso(start_dt + datetime.timedelta(i)) for i in range(num_days + 1)] |
java | private float[] generateParticleTimeStamps(float totalTime)
{
float timeStamps[] = new float[mEmitRate * 2];
if ( burstMode ) {
for (int i = 0; i < mEmitRate * 2; i += 2) {
timeStamps[i] = totalTime;
timeStamps[i + 1] = 0;
}
}
else {
for (int i = 0; i < mEmitRate * 2; i += 2) {
timeStamps[i] = totalTime + mRandom.nextFloat();
timeStamps[i + 1] = 0;
}
}
return timeStamps;
} |
java | public synchronized void add(Resource subject, URI predicate, Value object, Resource... contexts) throws MarkLogicSesameException {
cache.add(subject,predicate,object,contexts);
if( cache.size() > cacheSize - 1){
forceRun();
}
} |
java | public List<DynamoDBMapper.FailedBatch> batchDelete(Iterable<T> objectsToDelete) {
return mapper.batchWrite((Iterable<T>)Collections.<T>emptyList(), objectsToDelete);
} |
python | def _process_block_arch_specific(self, addr, irsb, func_addr): # pylint: disable=unused-argument
"""
According to arch types ['ARMEL', 'ARMHF', 'MIPS32'] does different
fixes
For ARM deals with link register on the stack
(see _arm_track_lr_on_stack)
For MIPS32 simulates a new state where the global pointer is 0xffffffff
from current address after three steps if the first successor does not
adjust this value updates this function address (in function manager)
to use a conrete global pointer
:param int addr: irsb address
:param pyvex.IRSB irsb: irsb
:param func_addr: function address
:return: None
"""
if is_arm_arch(self.project.arch):
if self._arch_options.ret_jumpkind_heuristics:
if addr == func_addr:
self._arm_track_lr_on_stack(addr, irsb, self.functions[func_addr])
elif 'lr_saved_on_stack' in self.functions[func_addr].info and \
self.functions[func_addr].info['lr_saved_on_stack'] and \
irsb.jumpkind == 'Ijk_Boring' and \
irsb.next is not None and \
isinstance(irsb.next, pyvex.IRExpr.RdTmp):
# do a bunch of checks to avoid unnecessary simulation from happening
self._arm_track_read_lr_from_stack(irsb, self.functions[func_addr])
elif self.project.arch.name == "MIPS32":
function = self.kb.functions.function(func_addr)
if addr >= func_addr and addr - func_addr < 15 * 4 and 'gp' not in function.info:
# check if gp is being written to
last_gp_setting_insn_id = None
insn_ctr = 0
if not irsb.statements:
# Get an IRSB with statements
irsb = self.project.factory.block(irsb.addr, size=irsb.size).vex
for stmt in irsb.statements:
if isinstance(stmt, pyvex.IRStmt.IMark):
insn_ctr += 1
if insn_ctr >= 10:
break
elif isinstance(stmt, pyvex.IRStmt.Put) and stmt.offset == self.project.arch.registers['gp'][0]:
last_gp_setting_insn_id = insn_ctr
break
if last_gp_setting_insn_id is None:
return
# Prudently search for $gp values
state = self.project.factory.blank_state(addr=addr, mode="fastpath",
remove_options={o.OPTIMIZE_IR}
)
state.regs.t9 = func_addr
state.regs.gp = 0xffffffff
succ = self.project.factory.successors(state, num_inst=last_gp_setting_insn_id + 1)
if not succ.flat_successors:
return
state = succ.flat_successors[0]
if not state.regs.gp.symbolic and state.solver.is_false(state.regs.gp == 0xffffffff):
function.info['gp'] = state.regs.gp._model_concrete.value |
java | private <T> void publishToCacheWriter(Consumer<T> action, Supplier<T> data) {
if (!configuration.isWriteThrough()) {
return;
}
try {
action.accept(data.get());
} catch (CacheWriterException e) {
throw e;
} catch (RuntimeException e) {
throw new CacheWriterException("Exception in CacheWriter", e);
}
} |
python | def go():
"""Make the magic happen."""
parser = argparse.ArgumentParser(prog='PROG', epilog=help_epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-V', '--version', action='store_true',
help="show version and info about the system, and exit")
parser.add_argument('-v', '--verbose', action='store_true',
help="send all internal debugging lines to stderr, which may be very "
"useful to debug any problem that may arise.")
parser.add_argument('-q', '--quiet', action='store_true',
help="don't show anything (unless it has a real problem), so the "
"original script stderr is not polluted at all.")
parser.add_argument('-d', '--dependency', action='append',
help="specify dependencies through command line (this option can be "
"used multiple times)")
parser.add_argument('-r', '--requirement', action='append',
help="indicate files to read dependencies from (this option can be "
"used multiple times)")
parser.add_argument('-p', '--python', action='store',
help=("Specify the Python interpreter to use.\n"
" Default is: %s") % (sys.executable,))
parser.add_argument('-x', '--exec', dest='executable', action='store_true',
help=("Indicate that the child_program should be looked up in the "
"virtualenv."))
parser.add_argument('-i', '--ipython', action='store_true', help="use IPython shell.")
parser.add_argument('--system-site-packages', action='store_true', default=False,
help=("Give the virtual environment access to the "
"system site-packages dir."))
parser.add_argument('--virtualenv-options', action='append', default=[],
help=("Extra options to be supplied to virtualenv. (this option can be "
"used multiple times)"))
parser.add_argument('--check-updates', action='store_true',
help=("check for packages updates"))
parser.add_argument('--no-precheck-availability', action='store_true',
help=("Don't check if the packages exists in PyPI before actually try "
"to install them."))
parser.add_argument('--pip-options', action='append', default=[],
help=("Extra options to be supplied to pip. (this option can be "
"used multiple times)"))
parser.add_argument('--python-options', action='append', default=[],
help=("Extra options to be supplied to python. (this option can be "
"used multiple times)"))
parser.add_argument('--rm', dest='remove', metavar='UUID',
help=("Remove a virtualenv by UUID. See --get-venv-dir option to "
"easily find out the UUID."))
parser.add_argument('--clean-unused-venvs', action='store',
help=("This option remove venvs that haven't been used for more than "
"CLEAN_UNUSED_VENVS days. Appart from that, will compact usage "
"stats file.\n"
"When this option is present, the cleaning takes place at the "
"beginning of the execution."))
parser.add_argument('--get-venv-dir', action='store_true',
help=("Show the virtualenv base directory (which includes the "
"virtualenv UUID) and quit."))
parser.add_argument('child_program', nargs='?', default=None)
parser.add_argument('child_options', nargs=argparse.REMAINDER)
cli_args = _get_normalized_args(parser)
# update args from config file (if needed).
args = file_options.options_from_file(cli_args)
# validate input, parameters, and support some special options
if args.version:
print("Running 'fades' version", fades.__version__)
print(" Python:", sys.version_info)
print(" System:", platform.platform())
return 0
# set up logger and dump basic version info
logger = fades_logger.set_up(args.verbose, args.quiet)
logger.debug("Running Python %s on %r", sys.version_info, platform.platform())
logger.debug("Starting fades v. %s", fades.__version__)
logger.debug("Arguments: %s", args)
# verify that the module is NOT being used from a virtualenv
if detect_inside_virtualenv(sys.prefix, getattr(sys, 'real_prefix', None),
getattr(sys, 'base_prefix', None)):
logger.error(
"fades is running from inside a virtualenv (%r), which is not supported", sys.prefix)
raise FadesError("Cannot run from a virtualenv")
if args.verbose and args.quiet:
logger.warning("Overriding 'quiet' option ('verbose' also requested)")
# start the virtualenvs manager
venvscache = cache.VEnvsCache(os.path.join(helpers.get_basedir(), 'venvs.idx'))
# start usage manager
usage_manager = envbuilder.UsageManager(os.path.join(helpers.get_basedir(), 'usage_stats'),
venvscache)
if args.clean_unused_venvs:
try:
max_days_to_keep = int(args.clean_unused_venvs)
except ValueError:
logger.error("clean_unused_venvs must be an integer.")
raise FadesError('clean_unused_venvs not an integer')
usage_manager.clean_unused_venvs(max_days_to_keep)
return 0
uuid = args.remove
if uuid:
venv_data = venvscache.get_venv(uuid=uuid)
if venv_data:
# remove this venv from the cache
env_path = venv_data.get('env_path')
if env_path:
envbuilder.destroy_venv(env_path, venvscache)
else:
logger.warning("Invalid 'env_path' found in virtualenv metadata: %r. "
"Not removing virtualenv.", env_path)
else:
logger.warning('No virtualenv found with uuid: %s.', uuid)
return 0
# decided which the child program really is
analyzable_child_program, child_program = decide_child_program(
args.executable, args.child_program)
# Group and merge dependencies
indicated_deps = consolidate_dependencies(args.ipython,
analyzable_child_program,
args.requirement,
args.dependency)
# Check for packages updates
if args.check_updates:
helpers.check_pypi_updates(indicated_deps)
# get the interpreter version requested for the child_program
interpreter, is_current = helpers.get_interpreter_version(args.python)
# options
pip_options = args.pip_options # pip_options mustn't store.
python_options = args.python_options
options = {}
options['pyvenv_options'] = []
options['virtualenv_options'] = args.virtualenv_options
if args.system_site_packages:
options['virtualenv_options'].append("--system-site-packages")
options['pyvenv_options'] = ["--system-site-packages"]
create_venv = False
venv_data = venvscache.get_venv(indicated_deps, interpreter, uuid, options)
if venv_data:
env_path = venv_data['env_path']
# A venv was found in the cache check if its valid or re-generate it.
if not os.path.exists(env_path):
logger.warning("Missing directory (the virtualenv will be re-created): %r", env_path)
venvscache.remove(env_path)
create_venv = True
else:
create_venv = True
if create_venv:
# Check if the requested packages exists in pypi.
if not args.no_precheck_availability and indicated_deps.get('pypi'):
logger.info("Checking the availabilty of dependencies in PyPI. "
"You can use '--no-precheck-availability' to avoid it.")
if not helpers.check_pypi_exists(indicated_deps):
logger.error("An indicated dependency doesn't exist. Exiting")
raise FadesError("Required dependency does not exist")
# Create a new venv
venv_data, installed = envbuilder.create_venv(indicated_deps, args.python, is_current,
options, pip_options)
# store this new venv in the cache
venvscache.store(installed, venv_data, interpreter, options)
if args.get_venv_dir:
# all it was requested is the virtualenv's path, show it and quit (don't run anything)
print(venv_data['env_path'])
return 0
# run forest run!!
python_exe = 'ipython' if args.ipython else 'python'
python_exe = os.path.join(venv_data['env_bin_path'], python_exe)
# add the virtualenv /bin path to the child PATH.
environ_path = venv_data['env_bin_path']
if 'PATH' in os.environ:
environ_path += os.pathsep + os.environ['PATH']
os.environ['PATH'] = environ_path
# store usage information
usage_manager.store_usage_stat(venv_data, venvscache)
if child_program is None:
interactive = True
logger.debug(
"Calling the interactive Python interpreter with arguments %r", python_options)
cmd = [python_exe] + python_options
p = subprocess.Popen(cmd)
else:
interactive = False
if args.executable:
cmd = [os.path.join(venv_data['env_bin_path'], child_program)]
logger.debug("Calling child program %r with options %s",
child_program, args.child_options)
else:
cmd = [python_exe] + python_options + [child_program]
logger.debug(
"Calling Python interpreter with arguments %s to execute the child program"
" %r with options %s", python_options, child_program, args.child_options)
try:
p = subprocess.Popen(cmd + args.child_options)
except FileNotFoundError:
logger.error("Command not found: %s", child_program)
raise FadesError("Command not found")
def _signal_handler(signum, _):
"""Handle signals received by parent process, send them to child.
The only exception is CTRL-C, that is generated *from* the interactive
interpreter (it's a keyboard combination!), so we swallow it for the
interpreter to not see it twice.
"""
if interactive and signum == signal.SIGINT:
logger.debug("Swallowing signal %s", signum)
else:
logger.debug("Redirecting signal %s to child", signum)
os.kill(p.pid, signum)
# redirect the useful signals
for s in REDIRECTED_SIGNALS:
signal.signal(s, _signal_handler)
# wait child to finish, end
rc = p.wait()
if rc:
logger.debug("Child process not finished correctly: returncode=%d", rc)
return rc |
java | public static Protos.Resource scalar(String name, String role, double value) {
checkNotNull(name);
checkNotNull(role);
checkNotNull(value);
return Protos.Resource.newBuilder()
.setName(name)
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(value))
.setRole(role)
.build();
} |
java | public ApiResponse<Info> versionInfoWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = versionInfoValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<Info>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} |
python | def decompress(chunks, compression):
"""Decompress
:param __generator[bytes] chunks: compressed body chunks.
:param str compression: compression constant.
:rtype: __generator[bytes]
:return: decompressed chunks.
:raise: TypeError, DecompressError
"""
if compression not in SUPPORTED_COMPRESSIONS:
raise TypeError('Unsupported compression type: %s' % (compression,))
de_compressor = DECOMPRESSOR_FACTORIES[compression]()
try:
for chunk in chunks:
try:
yield de_compressor.decompress(chunk)
except OSError as err:
# BZ2Decompressor: invalid data stream
raise DecompressError(err) from None
# BZ2Decompressor does not support flush() method.
if hasattr(de_compressor, 'flush'):
yield de_compressor.flush()
except zlib.error as err:
raise DecompressError(err) from None |
java | public List iterateObjectsToList() {
List result = new ArrayList();
Iterator iterator = iterateObjects();
for (; iterator.hasNext(); ) {
result.add(iterator.next());
}
return result;
} |
java | private static File getFax4jInternalTemporaryDirectoryImpl()
{
File temporaryFile=null;
try
{
//create temporary file
temporaryFile=File.createTempFile("temp_",".temp");
}
catch(IOException exception)
{
throw new FaxException("Unable to create temporary file.",exception);
}
//get parent directory
File temporaryDirectory=temporaryFile.getParentFile();
//delete file
boolean deleted=temporaryFile.delete();
if(!deleted)
{
temporaryFile.deleteOnExit();
}
//read properties
Properties properties=LibraryConfigurationLoader.readInternalConfiguration();
//get values
String name=properties.getProperty("org.fax4j.product.name");
String version=properties.getProperty("org.fax4j.product.version");
//create sub directory
File fax4jTemporaryDirectory=new File(temporaryDirectory,name+"_"+version);
if(!fax4jTemporaryDirectory.exists())
{
boolean created=fax4jTemporaryDirectory.mkdirs();
if(!created)
{
throw new FaxException("Unable to create fax4j internal temporary directory: "+fax4jTemporaryDirectory);
}
}
return fax4jTemporaryDirectory;
} |
java | private void tryStartingKbMode(int keyCode) {
if (mTimePicker.trySettingInputEnabled(false) &&
(keyCode == -1 || addKeyIfLegal(keyCode))) {
mInKbMode = true;
mDoneButton.setEnabled(false);
updateDisplay(false);
}
} |
java | public void marshall(Layer layer, ProtocolMarshaller protocolMarshaller) {
if (layer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(layer.getLayerDigest(), LAYERDIGEST_BINDING);
protocolMarshaller.marshall(layer.getLayerAvailability(), LAYERAVAILABILITY_BINDING);
protocolMarshaller.marshall(layer.getLayerSize(), LAYERSIZE_BINDING);
protocolMarshaller.marshall(layer.getMediaType(), MEDIATYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def moveToNextRow(vs, func, reverse=False):
'Move cursor to next (prev if reverse) row for which func returns True. Returns False if no row meets the criteria.'
rng = range(vs.cursorRowIndex-1, -1, -1) if reverse else range(vs.cursorRowIndex+1, vs.nRows)
for i in rng:
try:
if func(vs.rows[i]):
vs.cursorRowIndex = i
return True
except Exception:
pass
return False |
python | def GetPlaylists(self, start, max_count, order, reversed):
"""Gets a set of playlists.
:param int start: The index of the first playlist to be fetched
(according to the ordering).
:param int max_count: The maximum number of playlists to fetch.
:param str order: The ordering that should be used.
:param bool reversed: Whether the order should be reversed.
"""
cv = convert2dbus
return self.iface.GetPlaylists(cv(start, 'u'),
cv(max_count, 'u'),
cv(order, 's'),
cv(reversed, 'b')) |
python | def getUserSid(username):
'''
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy
'''
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find('\\') != -1:
domain = username.split('\\')[0]
username = username.split('\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringSid(
win32security.LookupAccountName(None, domain + '\\' + username)[0]) |
java | protected void configureSession(Session session) {
if(! session.getProperties().contains(MAIL_SMTP_ALLOW8BITMIME)) {
session.getProperties().put(MAIL_SMTP_ALLOW8BITMIME, "true");
}
} |
java | private static ImmutableList<Node> paramNamesOf(Node paramList) {
checkArgument(paramList.isParamList(), paramList);
ImmutableList.Builder<Node> builder = ImmutableList.builder();
paramNamesOf(paramList, builder);
return builder.build();
} |
python | def labels(self, nodeids=None):
"""
Return the list of labels for *nodeids*, or all labels.
Args:
nodeids: an iterable of nodeids for predications to get
labels from; if `None`, return labels for all
predications
Note:
This returns the label of each predication, even if it's
shared by another predication. Thus,
`zip(nodeids, xmrs.labels(nodeids))` will pair nodeids with
their labels.
Returns:
A list of labels
"""
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nid][2] for nid in nodeids] |
python | def user_exists(name, runas=None):
'''
Return whether the user exists based on rabbitmqctl list_users.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.user_exists rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
return name in list_users(runas=runas) |
java | public final AntlrDatatypeRuleToken ruleValidID() throws RecognitionException {
AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken();
Token this_ID_0=null;
Token kw=null;
enterRule();
try {
// InternalXtext.g:2138:2: ( (this_ID_0= RULE_ID | kw= 'true' | kw= 'false' ) )
// InternalXtext.g:2139:2: (this_ID_0= RULE_ID | kw= 'true' | kw= 'false' )
{
// InternalXtext.g:2139:2: (this_ID_0= RULE_ID | kw= 'true' | kw= 'false' )
int alt49=3;
switch ( input.LA(1) ) {
case RULE_ID:
{
alt49=1;
}
break;
case 39:
{
alt49=2;
}
break;
case 40:
{
alt49=3;
}
break;
default:
NoViableAltException nvae =
new NoViableAltException("", 49, 0, input);
throw nvae;
}
switch (alt49) {
case 1 :
// InternalXtext.g:2140:3: this_ID_0= RULE_ID
{
this_ID_0=(Token)match(input,RULE_ID,FollowSets000.FOLLOW_2);
current.merge(this_ID_0);
newLeafNode(this_ID_0, grammarAccess.getValidIDAccess().getIDTerminalRuleCall_0());
}
break;
case 2 :
// InternalXtext.g:2148:3: kw= 'true'
{
kw=(Token)match(input,39,FollowSets000.FOLLOW_2);
current.merge(kw);
newLeafNode(kw, grammarAccess.getValidIDAccess().getTrueKeyword_1());
}
break;
case 3 :
// InternalXtext.g:2154:3: kw= 'false'
{
kw=(Token)match(input,40,FollowSets000.FOLLOW_2);
current.merge(kw);
newLeafNode(kw, grammarAccess.getValidIDAccess().getFalseKeyword_2());
}
break;
}
}
leaveRule();
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} |
java | @Override
public List<WSStepThreadExecutionAggregate> getStepExecutionAggregatesFromJobExecutionId(
long jobExecutionId) throws NoSuchJobExecutionException {
// Optimize for programming ease rather than a single trip to the database.
// We might have to revisit.
List<WSStepThreadExecutionAggregate> retVal = new ArrayList<WSStepThreadExecutionAggregate>();
//sorted by start time
List<StepExecution> topLevelStepExecutions = getStepExecutionsTopLevelFromJobExecutionId(jobExecutionId);
for (StepExecution stepExec : topLevelStepExecutions) {
retVal.add(getStepExecutionAggregate(stepExec.getStepExecutionId()));
}
return retVal;
} |
java | private static void appendKeyValue(StringBuffer str, String key, String value) {
str.append(key);
if (value == IS_USED) {
str.append(";");
} else {
str.append("=(");
str.append(value);
str.append(");");
}
} |
java | private static void attemptRetryOnException(String logPrefix, Request<?> request,
JusError exception) throws JusError {
RetryPolicy retryPolicy = request.getRetryPolicy();
if (retryPolicy == null) {
throw exception;
}
try {
retryPolicy.retry(exception);
} catch (JusError e) {
request.addMarker(Request.EVENT_NETWORK_RETRY_FAILED,
String.format("%s-timeout-giveup [conn-timeout=%s] [read-timeout=%s]",
logPrefix, retryPolicy.getCurrentConnectTimeout(),
retryPolicy.getCurrentReadTimeout()));
throw e;
}
request.addMarker(Request.EVENT_NETWORK_RETRY,
String.format("%s-retry [conn-timeout=%s] [read-timeout=%s]",
logPrefix, retryPolicy.getCurrentConnectTimeout(),
retryPolicy.getCurrentReadTimeout()));
} |
python | def delete_policy_version(policy_name, version_id,
region=None, key=None, keyid=None, profile=None):
'''
Delete a policy version.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_policy_version mypolicy v1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy_arn = _get_policy_arn(policy_name, region, key, keyid, profile)
if not policy_version_exists(policy_arn, version_id, region, key, keyid, profile):
return True
try:
conn.delete_policy_version(policy_arn, version_id)
log.info('Deleted IAM policy %s version %s.', policy_name, version_id)
except boto.exception.BotoServerError as e:
aws = __utils__['boto.get_error'](e)
log.debug(aws)
log.error('Failed to delete IAM policy %s version %s: %s',
policy_name, version_id, aws.get('message'))
return False
return True |
python | def load(self, carddict):
"""
Takes a carddict as produced by ``Card.save`` and sets this card
instances information to the previously saved cards information.
"""
self.code = carddict["code"]
if isinstance(self.code, text_type):
self.code = eval(self.code)
self.name = carddict["name"]
self.abilities = carddict["abilities"]
if isinstance(self.abilities, text_type):
self.abilities = eval(self.abilities)
self.attributes = carddict["attributes"]
if isinstance(self.attributes, text_type):
self.attributes = eval(self.attributes)
self.info = carddict["info"]
if isinstance(self.info, text_type):
self.info = eval(self.info)
return self |
java | public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) {
Parameter[] parameterTypes = thisAsFirstArgument ? getRemainingParameterTypes(declaredMethod.getParameters()) : declaredMethod.getParameters();
String methodName = declaredMethod.getName();
if (classNode.hasDeclaredMethod(methodName, copyParameters(parameterTypes, genericsPlaceholders))) {
return null;
}
ClassNode returnType = declaredMethod.getReturnType();
String propertyName = !returnType.isPrimaryClassNode() ? GrailsNameUtils.getPropertyForGetter(methodName, returnType.getTypeClass()) : GrailsNameUtils.getPropertyForGetter(methodName);
if (propertyName != null && parameterTypes.length == 0 && classNode.hasProperty(propertyName)) {
return null;
}
propertyName = GrailsNameUtils.getPropertyForSetter(methodName);
if (propertyName != null && parameterTypes.length == 1 && classNode.hasProperty(propertyName)) {
return null;
}
BlockStatement methodBody = new BlockStatement();
ArgumentListExpression arguments = createArgumentListFromParameters(parameterTypes, thisAsFirstArgument, genericsPlaceholders);
returnType = replaceGenericsPlaceholders(returnType, genericsPlaceholders);
MethodCallExpression methodCallExpression = new MethodCallExpression(delegate, methodName, arguments);
methodCallExpression.setMethodTarget(declaredMethod);
if(!noNullCheck) {
ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, declaredMethod);
VariableExpression apiVar = addApiVariableDeclaration(delegate, declaredMethod, methodBody);
IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar, missingMethodException);
methodBody.addStatement(ifStatement);
} else {
methodBody.addStatement(new ExpressionStatement(methodCallExpression));
}
MethodNode methodNode = new MethodNode(methodName,
Modifier.PUBLIC, returnType, copyParameters(parameterTypes, genericsPlaceholders),
GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY, methodBody);
copyAnnotations(declaredMethod, methodNode);
if(shouldAddMarkerAnnotation(markerAnnotation, methodNode)) {
methodNode.addAnnotation(markerAnnotation);
}
classNode.addMethod(methodNode);
return methodNode;
} |
python | def add_patch(ax, color, pts_per_edge, *edges):
"""Add a polygonal surface patch to a plot.
Args:
ax (matplotlib.artist.Artist): A matplotlib axis.
color (Tuple[float, float, float]): Color as RGB profile.
pts_per_edge (int): Number of points to use in polygonal
approximation of edge.
edges (Tuple[~bezier.curve.Curve, ...]): Curved edges defining
a boundary.
"""
from matplotlib import patches
from matplotlib import path as _path_mod
s_vals = np.linspace(0.0, 1.0, pts_per_edge)
# Evaluate points on each edge.
all_points = []
for edge in edges:
points = edge.evaluate_multi(s_vals)
# We assume the edges overlap and leave out the first point
# in each.
all_points.append(points[:, 1:])
# Add first point as last point (polygon is closed).
first_edge = all_points[0]
all_points.append(first_edge[:, [0]])
# Add boundary first.
polygon = np.asfortranarray(np.hstack(all_points))
line, = ax.plot(polygon[0, :], polygon[1, :], color=color)
# Reset ``color`` in case it was ``None`` and set from color wheel.
color = line.get_color()
# ``polygon`` is stored Fortran-contiguous with ``x-y`` points in each
# column but ``Path()`` wants ``x-y`` points in each row.
path = _path_mod.Path(polygon.T)
patch = patches.PathPatch(path, facecolor=color, alpha=0.625)
ax.add_patch(patch) |
java | public static Message.Builder addDefaultInstanceToRepeatedField(final Descriptors.FieldDescriptor repeatedFieldDescriptor, final Message.Builder builder) throws CouldNotPerformException {
if (repeatedFieldDescriptor == null) {
throw new NotAvailableException("repeatedFieldDescriptor");
}
return addDefaultInstanceToRepeatedField(repeatedFieldDescriptor.getName(), builder);
} |
python | def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]:
"""
input:
------
E: 1-D vector of energy bins [eV]
E0: characteristic energy (scalar or vector) [eV]
Q0: flux coefficient (scalar or vector) (to yield overall flux Q)
output:
-------
Phi: differential number flux
Q: total flux
Tanaka 2006 Eqn. 1
http://odin.gi.alaska.edu/lumm/Papers/Tanaka_2006JA011744.pdf
"""
E0 = np.atleast_1d(E0)
Q0 = np.atleast_1d(Q0)
assert E0.ndim == Q0.ndim == 1
assert (Q0.size == 1 or Q0.size == E0.size)
Phi = Q0/(2*pi*E0**3) * E[:, None] * np.exp(-E[:, None]/E0)
Q = np.trapz(Phi, E, axis=0)
logging.info('total maxwellian flux Q: ' + (' '.join('{:.1e}'.format(q) for q in Q)))
return Phi, Q |
python | def get_tu(source, lang='c', all_warnings=False, flags=None):
"""Obtain a translation unit from source and language.
By default, the translation unit is created from source file "t.<ext>"
where <ext> is the default file extension for the specified language. By
default it is C, so "t.c" is the default file name.
Supported languages are {c, cpp, objc}.
all_warnings is a convenience argument to enable all compiler warnings.
"""
args = list(flags or [])
name = 't.c'
if lang == 'cpp':
name = 't.cpp'
args.append('-std=c++11')
elif lang == 'objc':
name = 't.m'
elif lang != 'c':
raise Exception('Unknown language: %s' % lang)
if all_warnings:
args += ['-Wall', '-Wextra']
return TranslationUnit.from_source(name, args, unsaved_files=[(name,
source)]) |
python | def p_const_vector_elem_list_list(p):
""" const_number_list : const_number_list COMMA expr
"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], symbols.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
api.errmsg.syntax_error_not_constant(p.lineno(2))
p[0] = None
return
else:
tmp = p[3]
if p[1] is not None:
p[1].append(tmp)
p[0] = p[1] |
python | def localize(self, name, **kwargs):
"""Find the best-fit position of a source. Localization is
performed in two steps. First a TS map is computed centered
on the source with half-width set by ``dtheta_max``. A fit is
then performed to the maximum TS peak in this map. The source
position is then further refined by scanning the likelihood in
the vicinity of the peak found in the first step. The size of
the scan region is set to encompass the 99% positional
uncertainty contour as determined from the peak fit.
Parameters
----------
name : str
Source name.
{options}
optimizer : dict
Dictionary that overrides the default optimizer settings.
Returns
-------
localize : dict
Dictionary containing results of the localization
analysis.
"""
timer = Timer.create(start=True)
name = self.roi.get_source_by_name(name).name
schema = ConfigSchema(self.defaults['localize'],
optimizer=self.defaults['optimizer'])
schema.add_option('use_cache', True)
schema.add_option('prefix', '')
config = utils.create_dict(self.config['localize'],
optimizer=self.config['optimizer'])
config = schema.create_config(config, **kwargs)
self.logger.info('Running localization for %s' % name)
free_state = FreeParameterState(self)
loc = self._localize(name, **config)
free_state.restore()
self.logger.info('Finished localization.')
if config['make_plots']:
self._plotter.make_localization_plots(loc, self.roi,
prefix=config['prefix'])
outfile = \
utils.format_filename(self.workdir, 'loc',
prefix=[config['prefix'],
name.lower().replace(' ', '_')])
if config['write_fits']:
loc['file'] = os.path.basename(outfile) + '.fits'
self._make_localize_fits(loc, outfile + '.fits',
**config)
if config['write_npy']:
np.save(outfile + '.npy', dict(loc))
self.logger.info('Execution time: %.2f s', timer.elapsed_time)
return loc |
java | private Transactional readAnnotation(MethodInvocation invocation)
{
final Method method = invocation.getMethod();
if (method.isAnnotationPresent(Transactional.class))
{
return method.getAnnotation(Transactional.class);
}
else
{
throw new RuntimeException("Could not find Transactional annotation");
}
} |
java | private Long performCommit(JPACommit commit) throws EDBException {
synchronized (entityManager) {
long timestamp = System.currentTimeMillis();
try {
beginTransaction();
persistCommitChanges(commit, timestamp);
commitTransaction();
} catch (Exception ex) {
try {
rollbackTransaction();
} catch (Exception e) {
throw new EDBException("Failed to rollback transaction to EDB", e);
}
throw new EDBException("Failed to commit transaction to EDB", ex);
}
return timestamp;
}
} |
python | def clean(self):
""" Removes any Units that are not applicable given the current semantic or phonetic category.
Modifies:
- self.unit_list: Removes Units from this list that do not fit into the clustering category.
it does by by either combining units to make compound words, combining units with the
same stem, or eliminating units altogether if they do not conform to the category.
If the type is phonetic, this method also generates phonetic clusters for all Unit
objects in self.unit_list.
This method performs three main tasks:
1. Removes words that do not conform to the clustering category (i.e. start with the
wrong letter, or are not an animal).
2. Combine adjacent words with the same stem into a single unit. The NLTK Porter Stemmer
is used for determining whether stems are the same.
http://www.nltk.org/_modules/nltk/stem/porter.html
3. In the case of PHONETIC clustering, compute the phonetic representation of each unit.
"""
if not self.quiet:
print
print "Preprocessing input..."
print "Raw response:"
print self.display()
if not self.quiet:
print
print "Cleaning words..."
#weed out words not starting with the right letter or in the right category
current_index = 0
while current_index < len(self.unit_list):
word = self.unit_list[current_index].text
if self.type == "PHONETIC":
test = (word.startswith(self.letter_or_category) and #starts with required letter
not word.endswith('-') and # Weed out word fragments
'_' not in word and # Weed out, e.g., 'filledpause_um'
word.lower() in self.english_words) #make sure the word is english
elif self.type == "SEMANTIC":
test = word in self.permissible_words
if not test: #if test fails remove word
self.remove_unit(index = current_index)
else: # otherwise just increment, but check to see if you're at the end of the list
current_index += 1
#combine words with the same stem
current_index = 0
finished = False
while current_index < len(self.unit_list) - 1:
#don't combine for lists of length 0, 1
if stemmer.stem(self.unit_list[current_index].text) == \
stemmer.stem(self.unit_list[current_index + 1].text):
#if same stem as next, merge next unit with current unit
self.combine_same_stem_units(index = current_index)
else: # if not same stem, increment index
current_index += 1
#get phonetic representations
if self.type == "PHONETIC":
for unit in self.unit_list:
word = unit.text
#get phonetic representation
if word in self.cmudict:
# If word in CMUdict, get its phonetic representation
phonetic_representation = self.cmudict[word]
if word not in self.cmudict:
# Else, generate a phonetic representation for it
phonetic_representation = self.generate_phonetic_representation(word)
phonetic_representation = self.modify_phonetic_representation(phonetic_representation)
unit.phonetic_representation = phonetic_representation
if not self.quiet:
print
print "Cleaned response:"
print self.display() |
python | def get_brain(brain_or_object):
"""Return a ZCatalog brain for the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: True if the object is a catalog brain
:rtype: bool
"""
if is_brain(brain_or_object):
return brain_or_object
if is_root(brain_or_object):
return brain_or_object
# fetch the brain by UID
uid = get_uid(brain_or_object)
uc = get_tool("uid_catalog")
results = uc({"UID": uid}) or search(query={'UID': uid})
if len(results) == 0:
return None
if len(results) > 1:
fail(500, "More than one object with UID={} found in portal_catalog".format(uid))
return results[0] |
java | public static void printStackTrace(SQLException e, PrintWriter pw) {
SQLException next = e;
while (next != null) {
next.printStackTrace(pw);
next = next.getNextException();
if (next != null) {
pw.println("Next SQLException:");
}
}
} |
java | static double pow(final double a, final double b) {
long tmp = Double.doubleToLongBits(a);
long tmp2 = (long) (b * (tmp - 4606921280493453312L)) + 4606921280493453312L;
return Double.longBitsToDouble(tmp2);
} |
java | public static <TimeInstantT extends TimeInstant> TimePickerFragment newInstance(int pickerId, TimeInstantT selectedInstant) {
TimePickerFragment f = new TimePickerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PICKER_ID, pickerId);
args.putParcelable(ARG_SELECTED_INSTANT, selectedInstant);
f.setArguments(args);
return f;
} |
java | @Override
public void onUpdateBusinessLogicTime(boolean taskOrKeyPresent, boolean externalTaskPresent, long businessLogicTime) {
loops.recordEvent();
if (taskOrKeyPresent) {
this.businessLogicTime.recordValue((int) businessLogicTime);
} else {
if (!externalTaskPresent) {
idleLoops.recordEvent();
} else {
idleLoopsWaitingExternalTask.recordEvent();
}
}
if (next != null) {
next.onUpdateBusinessLogicTime(taskOrKeyPresent, externalTaskPresent, businessLogicTime);
}
} |
java | public <T> List<T> query(String query, Class<T> classOfT) {
InputStream instream = null;
List<T> result = new ArrayList<T>();
try {
Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
if (json.has("rows")) {
if (!includeDocs) {
log.warning("includeDocs set to false and attempting to retrieve doc. " +
"null object will be returned");
}
for (JsonElement e : json.getAsJsonArray("rows")) {
result.add(jsonToObject(client.getGson(), e, "doc", classOfT));
}
} else {
log.warning("No ungrouped result available. Use queryGroups() if grouping set");
}
return result;
} catch (UnsupportedEncodingException e1) {
// This should never happen as every implementation of the java platform is required
// to support UTF-8.
throw new RuntimeException(e1);
} finally {
close(instream);
}
} |
java | public void marshall(SubmitTaskStateChangeRequest submitTaskStateChangeRequest, ProtocolMarshaller protocolMarshaller) {
if (submitTaskStateChangeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(submitTaskStateChangeRequest.getCluster(), CLUSTER_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getTask(), TASK_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getStatus(), STATUS_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getReason(), REASON_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getContainers(), CONTAINERS_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getAttachments(), ATTACHMENTS_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getPullStartedAt(), PULLSTARTEDAT_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getPullStoppedAt(), PULLSTOPPEDAT_BINDING);
protocolMarshaller.marshall(submitTaskStateChangeRequest.getExecutionStoppedAt(), EXECUTIONSTOPPEDAT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
if full_name not in self._descriptors:
self._FindFileContainingSymbolInDb(full_name)
return self._descriptors[full_name] |
java | protected void configureParser(LSParser parser) {
for (Map.Entry<String, Object> setting : parseSettings.entrySet()) {
setParserConfigParameter(parser, setting.getKey(), setting.getValue());
}
} |
java | public void paintSliderThumbBackground(SynthContext context, Graphics g, int x, int y, int w, int h, int orientation) {
if (context.getComponent().getClientProperty("Slider.paintThumbArrowShape") == Boolean.TRUE) {
if (orientation == JSlider.HORIZONTAL) {
orientation = JSlider.VERTICAL;
} else {
orientation = JSlider.HORIZONTAL;
}
paintBackground(context, g, x, y, w, h, orientation);
} else {
paintBackground(context, g, x, y, w, h, orientation);
}
} |
python | def crossvalidate_model(self, classifier, data, num_folds, rnd, output=None):
"""
Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data: the data to evaluate on
:type data: Instances
:param num_folds: the number of folds
:type num_folds: int
:param rnd: the random number generator to use
:type rnd: Random
:param output: the output generator to use
:type output: PredictionOutput
"""
if output is None:
generator = []
else:
generator = [output.jobject]
javabridge.call(
self.jobject, "crossValidateModel",
"(Lweka/classifiers/Classifier;Lweka/core/Instances;ILjava/util/Random;[Ljava/lang/Object;)V",
classifier.jobject, data.jobject, num_folds, rnd.jobject, generator) |
java | private String trackKindToString(final Track.Kind kind) {
if (kind == null) {
return null;
}
switch (kind) {
case SUBTITLES:
return "subtitles";
case CAPTIONS:
return "captions";
case DESCRIPTIONS:
return "descriptions";
case CHAPTERS:
return "chapters";
case METADATA:
return "metadata";
default:
LOG.error("Unknown track kind " + kind);
return null;
}
} |
python | def hsig(self, es):
"""return "OK-signal" for rank-one update, `True` (OK) or `False`
(stall rank-one update), based on the length of an evolution path
"""
self._update_ps(es)
if self.ps is None:
return True
squared_sum = sum(self.ps**2) / (1 - (1 - self.cs)**(2 * es.countiter))
# correction with self.countiter seems not necessary,
# as pc also starts with zero
return squared_sum / es.N - 1 < 1 + 4. / (es.N + 1) |
python | def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format(
host_setting)) |
python | def plot_curvature(self, curv_type='mean', **kwargs):
"""
Plots the curvature of the external surface of the grid
Parameters
----------
curv_type : str, optional
One of the following strings indicating curvature types
- mean
- gaussian
- maximum
- minimum
**kwargs : optional
Optional keyword arguments. See help(vtki.plot)
Returns
-------
cpos : list
Camera position, focal point, and view up. Used for storing and
setting camera view.
"""
trisurf = self.extract_surface().tri_filter()
return trisurf.plot_curvature(curv_type, **kwargs) |
java | public static void traceMessageId(TraceComponent callersTrace, String action, SIBusMessage message)
{
if (light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) {
_traceMessageId(callersTrace, action, msgToString(message));
}
} |
java | public static void addEarToServerDropins(LibertyServer server, String earName, boolean addEarResources,
String warName, boolean addWarResources, String jarName, boolean addJarResources, String... packageNames) throws Exception {
addEarToServer(server, DIR_DROPINS, earName, addEarResources, warName, addWarResources, jarName, addJarResources,
packageNames);
} |
java | @Override
public UpdateTemplateResult updateTemplate(UpdateTemplateRequest request) {
request = beforeClientExecution(request);
return executeUpdateTemplate(request);
} |
java | public void setRemoteSeparator(final String value) {
if (value != null && value.length() != 1) {
throw new BuildException("remote separator must be a single character");
}
this.remoteSeparator = value.charAt(0);
} |
java | public void setReadOnly(final boolean readOnly) throws SQLException {
try {
logger.debug("conn={}({}) - set read-only to value {} {}",
protocol.getServerThreadId(),
protocol.isMasterConnection() ? "M" : "S",
readOnly);
stateFlag |= ConnectionState.STATE_READ_ONLY;
protocol.setReadonly(readOnly);
} catch (SQLException e) {
throw ExceptionMapper.getException(e, this, null, false);
}
} |
java | public void store(String path, Class<?> clazz) {
this.store(FileUtil.getAbsolutePath(path, clazz));
} |
python | def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
balance, indent, account_fragment = match.group(1, 2, 3)
return {
'balance': decimal.Decimal(balance),
'indent': len(indent),
'account_fragment': account_fragment,
'parent': None,
'children': [],
} |
java | public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
if (map == null) {
throw new NullPointerException(StringUtils.simpleFormat(message, values));
}
if (map.isEmpty()) {
throw new IllegalArgumentException(StringUtils.simpleFormat(message, values));
}
return map;
} |
java | public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
if (mAdapter instanceof SectionIndexerAdapterWrapper) {
((SectionIndexerAdapterWrapper) mAdapter).mSectionIndexerDelegate = null;
}
if (mAdapter != null) {
mAdapter.mDelegate = null;
}
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
} |
java | @Override
public int filterCountByCompanyId(long companyId) {
if (!InlineSQLHelperUtil.isEnabled(companyId, 0)) {
return countByCompanyId(companyId);
}
StringBundler query = new StringBundler(2);
query.append(_FILTER_SQL_COUNT_COMMERCEACCOUNT_WHERE);
query.append(_FINDER_COLUMN_COMPANYID_COMPANYID_2);
String sql = InlineSQLHelperUtil.replacePermissionCheck(query.toString(),
CommerceAccount.class.getName(),
_FILTER_ENTITY_TABLE_FILTER_PK_COLUMN);
Session session = null;
try {
session = openSession();
SQLQuery q = session.createSynchronizedSQLQuery(sql);
q.addScalar(COUNT_COLUMN_NAME,
com.liferay.portal.kernel.dao.orm.Type.LONG);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(companyId);
Long count = (Long)q.uniqueResult();
return count.intValue();
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} |
java | public void setSystemPropertyName (@Nullable final String systemPropertyName)
{
m_sSystemPropertyName = systemPropertyName == null ? SYSTEM_PROPERTY : systemPropertyName.trim ();
} |
java | public int getIntField(String name)
throws NumberFormatException
{
String val = valueParameters(get(name),null);
if (val!=null)
return Integer.parseInt(val);
return -1;
} |
java | public T get(int index) {
final int size = size();
int normalisedIndex = normaliseIndex(index, size);
if (normalisedIndex < 0) {
throw new IndexOutOfBoundsException("Negative index [" + normalisedIndex + "] too large for list size " + size);
}
// either index >= size or the normalised index is negative
if (normalisedIndex >= size) {
// find out the number of gaps to fill with null/the default value
final int gapCount = normalisedIndex - size;
// fill all gaps
for (int i = 0; i < gapCount; i++) {
final int idx = size();
// if we lazily create default values, use 'null' as placeholder
if (lazyDefaultValues)
delegate.add(idx, null);
else
delegate.add(idx, getDefaultValue(idx));
}
// add the first/last element being always the default value
final int idx = normalisedIndex;
delegate.add(idx, getDefaultValue(idx));
// normalise index again to get positive index
normalisedIndex = normaliseIndex(index, size());
}
T item = delegate.get(normalisedIndex);
if (item == null && lazyDefaultValues) {
item = getDefaultValue(normalisedIndex);
delegate.set(normalisedIndex, item);
}
return item;
} |
java | public static CellPosition of(final String address) {
ArgUtils.notEmpty(address, "address");
if(!matchedCellAddress(address)) {
throw new IllegalArgumentException(address + " is wrong cell address pattern.");
}
return of(new CellReference(address));
} |
java | public void marshall(CreateGroupRequest createGroupRequest, ProtocolMarshaller protocolMarshaller) {
if (createGroupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGroupRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(createGroupRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(createGroupRequest.getResourceQuery(), RESOURCEQUERY_BINDING);
protocolMarshaller.marshall(createGroupRequest.getTags(), TAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def _compile_int(self):
"""Time Domain Simulation routine execution"""
string = '"""\n'
# evaluate the algebraic equations g
string += 'system.dae.init_fg(resetz=False)\n'
for gcall, call in zip(self.gcall, self.gcalls):
if gcall:
string += call
string += '\n'
string += 'system.dae.reset_small_g()\n'
# handle islands
string += self.gisland
# evaluate differential equations f
for fcall, call in zip(self.fcall, self.fcalls):
if fcall:
string += call
string += 'system.dae.reset_small_f()\n'
string += '\n'
fg_string = string + '"""'
self.int_fg = compile(eval(fg_string), '', 'exec')
# rebuild constant Jacobian elements if needed
string += 'if system.dae.factorize:\n'
string += ' system.dae.init_jac0()\n'
for jac0, call in zip(self.jac0, self.jac0s):
if jac0:
string += ' ' + call
string += ' system.dae.temp_to_spmatrix(\'jac0\')\n'
# evaluate Jacobians Gy and Fx
string += 'system.dae.setup_FxGy()\n'
for gycall, call in zip(self.gycall, self.gycalls):
if gycall:
string += call
string += '\n'
for fxcall, call in zip(self.fxcall, self.fxcalls):
if fxcall:
string += call
string += self.gyisland
string += 'system.dae.temp_to_spmatrix(\'jac\')\n'
string += '"""'
if SHOW_INT_CALL:
logger.debug(string)
self.int = compile(eval(string), '', 'exec') |
python | def get_variable(self, key, per_reference=None, access_key=None, default=None):
"""Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference
"""
key = str(key)
if self.variable_exist(key):
unlock = True
if self.is_locked(key):
if self.__access_keys[key] == access_key:
unlock = False
else:
if not access_key:
access_key = self.lock_variable(key, block=True)
else:
raise RuntimeError("Wrong access key for accessing global variable")
else:
access_key = self.lock_variable(key, block=True)
# --- variable locked
if self.variable_can_be_referenced(key):
if per_reference or per_reference is None:
return_value = self.__global_variable_dictionary[key]
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
else:
if per_reference:
self.unlock_variable(key, access_key)
raise RuntimeError("Variable cannot be accessed by reference")
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
return return_value
else:
# logger.warning("Global variable '{0}' not existing, returning default value".format(key))
return default |
java | public EClass getFullyQualifiedName() {
if (fullyQualifiedNameEClass == null) {
fullyQualifiedNameEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(356);
}
return fullyQualifiedNameEClass;
} |
java | public void addWeightParam(@NonNull String paramKey, @NonNull long... paramShape) {
Preconditions.checkArgument(paramShape.length > 0, "Provided weight parameter shape is"
+ " invalid: length 0 provided for shape. Parameter: " + paramKey);
weightParams.put(paramKey, paramShape);
paramsList = null;
weightParamsList = null;
biasParamsList = null;
} |
java | public void throwException(String errorString) {
ResourceBundle rb = ResourceBundle.getBundle(LoggingUtil.SESSION_LOGGER_CORE.getResourceBundleName());
String msg = (String) rb.getObject(errorString);
RuntimeException re = new RuntimeException(msg);
throw re;
} |
java | static WorkClassLoader createWorkClassLoader(final ClassBundle cb)
{
return AccessController.doPrivileged(new PrivilegedAction<WorkClassLoader>()
{
public WorkClassLoader run()
{
return new WorkClassLoader(cb);
}
});
} |
python | def get(self, request, *args, **kwargs):
"""
Return a HTTPResponse either of a PDF file or HTML.
:rtype: HttpResponse
"""
if 'html' in request.GET:
# Output HTML
content = self.render_html(*args, **kwargs)
return HttpResponse(content)
else:
# Output PDF
content = self.render_pdf(*args, **kwargs)
response = HttpResponse(content, content_type='application/pdf')
if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET:
response['Content-Disposition'] = 'attachment; filename=%s' % self.get_filename()
response['Content-Length'] = len(content)
return response |
python | def get_type_item(self, value, map_name=None, instances=None):
"""
Converts the input to a InputConfigId tuple. It can be from a single string, list, or tuple. Single values
(also single-element lists or tuples) are considered to be a container configuration on the default map. A string
with two elements separated by a dot or two-element lists / tuples are considered to be referring to a specific
map and configuration. Three strings concatenated with a dot or three-element lists / tuples are considered to be
referring to a map, configuration, and instances. Multiple instances can be specified in the third element by
passing a tuple or list.
:param value: Input value for conversion.
:param map_name: Map name; provides the default map name unless otherwise specified in ``value``.
:type map_name: unicode | str
:param instances: Instance names; instances to set if not otherwise specified in ``value``.
:type instances: unicode | str | tuple[unicode | str | NoneType]
:return: InputConfigId tuple.
:rtype: InputConfigId
"""
if isinstance(value, InputConfigId):
return value
elif isinstance(value, MapConfigId):
if value.instance_name:
v_instances = value.instance_name,
else:
v_instances = None
return InputConfigId(value.config_type, value.map_name, value.config_name, v_instances or instances)
elif isinstance(value, six.string_types):
s_map_name, __, s_config_name = value.partition('.')
if s_config_name:
config_name, __, s_instance = s_config_name.partition('.')
if s_instance:
s_instances = s_instance,
else:
s_instances = None
else:
config_name = s_map_name
s_map_name = map_name
s_instances = None
return InputConfigId(ItemType.CONTAINER, s_map_name, config_name, s_instances or instances)
elif isinstance(value, (tuple, list)):
v_len = len(value)
if v_len == 3:
v_instances = value[2]
if not v_instances:
return InputConfigId(ItemType.CONTAINER, value[0], value[1])
if isinstance(v_instances, tuple):
return InputConfigId(ItemType.CONTAINER, *value)
elif isinstance(v_instances, list):
return InputConfigId(ItemType.CONTAINER, value[0], value[1], tuple(v_instances))
elif isinstance(v_instances, six.string_types):
return InputConfigId(ItemType.CONTAINER, value[0], value[1], (v_instances,))
raise ValueError(
"Invalid type of instance specification in '{0}'; expected a list, tuple, or string type, "
"found {1}.".format(value, type(v_instances).__name__), v_instances)
elif v_len == 2:
return InputConfigId(ItemType.CONTAINER, value[0] or map_name, value[1], instances)
elif v_len == 1:
return InputConfigId(ItemType.CONTAINER, map_name, value[0], instances)
raise ValueError("Invalid element length; only tuples and lists of length 1-3 can be converted to a "
"InputConfigId tuple. Found length {0}.".format(v_len))
elif isinstance(value, dict):
kwargs = {
'config_type': ItemType.CONTAINER,
'map_name': map_name,
'instance_names': instances,
}
kwargs.update(value)
return InputConfigId(**kwargs)
raise ValueError(
"Invalid type; expected a list, tuple, dict, or string type, found {0}.".format(type(value).__name__)) |
python | def get_max(self, field=None):
"""
Create a max aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods
"""
if not field:
raise AttributeError("Please provide field to apply aggregation to!")
agg = A("max", field=field)
self.aggregations['max_' + field] = agg
return self |
java | public boolean alsoShow(Object filter){
switch(this.defaultState){
case HIDE_ALL:
return this.deltaPool.add(filter);
case SHOW_ALL:
return this.deltaPool.remove(filter);
default:
throw new IllegalStateException("Unknown default state setting: " + this.defaultState);
}
} |
java | private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
JsonGenerator generator = createJsonGenerator(byteStream, Charsets.UTF_8);
if (pretty) {
generator.enablePrettyPrint();
}
generator.serialize(item);
generator.flush();
return byteStream;
} |
java | protected static Kernel1D_F32 derivative1D_F32(int order, double sigma, int radius, boolean normalize) {
Kernel1D_F32 ret = new Kernel1D_F32(radius * 2 + 1);
float[] gaussian = ret.data;
int index = 0;
switch( order ) {
case 1:
for (int i = radius; i >= -radius; i--) {
gaussian[index++] = (float) UtilGaussian.derivative1(0, sigma, i);
}
break;
case 2:
for (int i = radius; i >= -radius; i--) {
gaussian[index++] = (float) UtilGaussian.derivative2(0, sigma, i);
}
break;
case 3:
for (int i = radius; i >= -radius; i--) {
gaussian[index++] = (float) UtilGaussian.derivative3(0, sigma, i);
}
break;
case 4:
for (int i = radius; i >= -radius; i--) {
gaussian[index++] = (float) UtilGaussian.derivative4(0, sigma, i);
}
break;
default:
throw new IllegalArgumentException("Only derivatives of order 1 to 4 are supported");
}
// multiply by the same factor as the gaussian would be normalized by
// otherwise it will effective change the intensity of the input image
if( normalize ) {
double sum = 0;
for (int i = radius; i >= -radius; i--) {
sum += UtilGaussian.computePDF(0, sigma, i);
}
for (int i = 0; i < gaussian.length; i++) {
gaussian[i] /= sum;
}
}
return ret;
} |
java | @SuppressWarnings("unchecked")
public <T> T toProxyBean(Class<T> interfaceClass) {
return (T) Proxy.newProxyInstance(ClassLoaderUtil.getClassLoader(), new Class<?>[]{interfaceClass}, this);
} |
python | def update(self, role_sid=values.unset, attributes=values.unset,
friendly_name=values.unset):
"""
Update the UserInstance
:param unicode role_sid: The SID id of the Role assigned to this user
:param unicode attributes: A valid JSON string that contains application-specific data
:param unicode friendly_name: A string to describe the resource
:returns: Updated UserInstance
:rtype: twilio.rest.chat.v2.service.user.UserInstance
"""
data = values.of({'RoleSid': role_sid, 'Attributes': attributes, 'FriendlyName': friendly_name, })
payload = self._version.update(
'POST',
self._uri,
data=data,
)
return UserInstance(
self._version,
payload,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
) |
java | public static String getIconClasses(CmsExplorerTypeSettings typeSettings, String resourceName, boolean small) {
String result = null;
if (typeSettings == null) {
typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
(resourceName != null) && CmsResource.isFolder(resourceName)
? CmsResourceTypeUnknownFile.RESOURCE_TYPE_NAME
: CmsResourceTypeUnknownFolder.RESOURCE_TYPE_NAME);
}
if (!typeSettings.getIconRules().isEmpty() && (resourceName != null)) {
String extension = CmsResource.getExtension(resourceName);
if (extension != null) {
// check for a matching sub type icon rule
CmsIconRule rule = typeSettings.getIconRules().get(extension);
if (rule != null) {
result = small ? rule.getSmallIconStyle() : rule.getBigIconStyle();
}
}
}
if (result == null) {
if (small && (typeSettings.getSmallIconStyle() != null)) {
result = typeSettings.getSmallIconStyle();
} else if (small && (typeSettings.getIcon() == null)) {
result = CmsExplorerTypeSettings.ICON_STYLE_DEFAULT_SMALL;
} else if (!small && (typeSettings.getBigIconStyle() != null)) {
result = typeSettings.getBigIconStyle();
} else if (!small && (typeSettings.getBigIcon() == null)) {
result = CmsExplorerTypeSettings.ICON_STYLE_DEFAULT_BIG;
}
if (result != null) {
result = CmsGwtConstants.TYPE_ICON_CLASS + " " + result;
} else {
result = getResourceIconClasses(typeSettings.getName(), resourceName, small);
}
}
return result;
} |
python | def _add_variants(self, key, value, schema):
''' also possible to define some function that takes
current value and creates a new value from it
'''
variants = schema.get('variants')
obj = {}
if variants:
for _key, func in variants.iteritems():
_value = func(value, self.store)
obj.update({_key: _value})
return obj |
python | def run(self):
""" Run the receiver thread """
dataOut = array.array('B', [0xFF])
waitTime = 0
emptyCtr = 0
# Try up to 10 times to enable the safelink mode
with self._radio_manager as cradio:
for _ in range(10):
resp = cradio.send_packet((0xff, 0x05, 0x01))
if resp and resp.data and tuple(resp.data) == (
0xff, 0x05, 0x01):
self._has_safelink = True
self._curr_up = 0
self._curr_down = 0
break
self._link.needs_resending = not self._has_safelink
while (True):
if (self._sp):
break
with self._radio_manager as cradio:
try:
if self._has_safelink:
ackStatus = self._send_packet_safe(cradio, dataOut)
else:
ackStatus = cradio.send_packet(dataOut)
except Exception as e:
import traceback
self._link_error_callback(
'Error communicating with crazy radio ,it has '
'probably been unplugged!\nException:%s\n\n%s' % (
e, traceback.format_exc()))
# Analyse the in data packet ...
if ackStatus is None:
logger.info('Dongle reported ACK status == None')
continue
if (self._link_quality_callback is not None):
# track the mean of a sliding window of the last N packets
retry = 10 - ackStatus.retry
self._retries.append(retry)
self._retry_sum += retry
if len(self._retries) > 100:
self._retry_sum -= self._retries.popleft()
link_quality = float(self._retry_sum) / len(self._retries) * 10
self._link_quality_callback(link_quality)
# If no copter, retry
if ackStatus.ack is False:
self._retry_before_disconnect = \
self._retry_before_disconnect - 1
if (self._retry_before_disconnect == 0 and
self._link_error_callback is not None):
self._link_error_callback('Too many packets lost')
continue
self._retry_before_disconnect = _nr_of_retries
data = ackStatus.data
# If there is a copter in range, the packet is analysed and the
# next packet to send is prepared
if (len(data) > 0):
inPacket = CRTPPacket(data[0], list(data[1:]))
self._in_queue.put(inPacket)
waitTime = 0
emptyCtr = 0
else:
emptyCtr += 1
if (emptyCtr > 10):
emptyCtr = 10
# Relaxation time if the last 10 packet where empty
waitTime = 0.01
else:
waitTime = 0
# get the next packet to send of relaxation (wait 10ms)
outPacket = None
try:
outPacket = self._out_queue.get(True, waitTime)
except queue.Empty:
outPacket = None
dataOut = array.array('B')
if outPacket:
dataOut.append(outPacket.header)
for X in outPacket.data:
if type(X) == int:
dataOut.append(X)
else:
dataOut.append(ord(X))
else:
dataOut.append(0xFF) |