language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def random_insertion(self,fastq,rate,max_inserts=1):
"""Perform the permutation on the sequence. If authorized to do multiple bases they are done at hte rate defined here.
:param fastq: FASTQ sequence to permute
:type fastq: format.fastq.FASTQ
:param rate: how frequently to permute
:type rate: float
:param max_inserts: the maximum number of bases to insert (default 1)
:type rate: int
:return: Permutted FASTQ
:rtype: format.fastq.FASTQ
"""
sequence = fastq.sequence
quality = fastq.qual
seq = ''
qual = None
ibase = rate_to_phred33(rate)
if quality: qual = ''
z = 0
while self.random.random() < rate and z < max_inserts:
if self._before_base: break # can't do this one
if self._after_base:
if self._after_base != sequence[1]: break
z += 1
if self._modified_base:
seq += self._modified_base
if quality: qual += ibase
else:
seq += self.random.random_nt()
if quality: qual += ibase
z = 0
for i in range(len(sequence)):
# check context
prev = sequence[i]
next = None
if i < len(sequence)-1: next = sequence[i+1]
if self._before_base and (not prev or prev != self._before_base):
seq+=sequence[i]
if quality: qual+=quality[i]
continue
if self._after_base and (not next or next != self._after_base):
seq+=sequence[i]
if quality: qual+= quality[i]
continue
seq += sequence[i]
if quality: qual += quality[i]
while self.random.random() < rate and z < max_inserts:
z+=1
if self._modified_base:
seq += self._modified_base
if quality: qual += ibase
else:
seq += self.random.random_nt()
if quality: qual += ibase
z = 0
return FASTQ('@'+fastq.name+"\n"+seq+"\n+\n"+qual+"\n") |
python | async def read(cls, fabric: Union[Fabric, int]):
"""Get list of `Vlan`'s for `fabric`.
:param fabric: Fabric to get all VLAN's for.
:type fabric: `Fabric` or `int`
"""
if isinstance(fabric, int):
fabric_id = fabric
elif isinstance(fabric, Fabric):
fabric_id = fabric.id
else:
raise TypeError(
"fabric must be a Fabric or int, not %s"
% type(fabric).__name__)
data = await cls._handler.read(fabric_id=fabric_id)
return cls(
cls._object(
item, local_data={"fabric_id": fabric_id})
for item in data) |
java | public ServiceFuture<ManagementLockObjectInner> getByScopeAsync(String scope, String lockName, final ServiceCallback<ManagementLockObjectInner> serviceCallback) {
return ServiceFuture.fromResponse(getByScopeWithServiceResponseAsync(scope, lockName), serviceCallback);
} |
python | def trace_on (full=False):
"""Start tracing of the current thread (and the current thread only)."""
if full:
sys.settrace(_trace_full)
else:
sys.settrace(_trace) |
python | def normal(self):
'''
:return: Line
Returns a Line normal (perpendicular) to this Line.
'''
d = self.B - self.A
return Line([-d.y, d.x], [d.y, -d.x]) |
java | @Override
protected void setProperty(final String _name,
final String _value)
throws CacheReloadException
{
if ("Align".equals(_name)) {
this.align = _value;
} else if ("UIProvider".equals(_name) || "ClassNameUI".equals(_name)) {
try {
this.uiProvider = (IUIProvider) Class.forName(_value).newInstance();
} catch (final ClassNotFoundException e) {
throw new CacheReloadException("could not found class '" + _value + "' for '" + getName() + "'", e);
} catch (final InstantiationException e) {
throw new CacheReloadException("could not instantiate class '" + _value + "' for '" + getName() + "'",
e);
} catch (final IllegalAccessException e) {
throw new CacheReloadException("could not access class '" + _value + "' for '" + getName() + "'", e);
}
} else if ("Columns".equals(_name)) {
this.cols = Integer.parseInt(_value);
} else if ("Classification".equals(_name)) {
this.classificationName = _value;
} else if ("CreateValue".equals(_name)) {
this.createValue = _value;
} else if ("SelectAlternateOID".equals(_name)) {
this.selectAlternateOID = _value;
} else if ("Select".equals(_name)) {
this.select = _value;
} else if ("Attribute".equals(_name)) {
this.attribute = _value;
} else if ("Phrase".equals(_name)) {
this.phrase = _value;
} else if ("MsgPhrase".equals(_name)) {
this.msgPhrase = _value;
} else if ("SortAble".equals(_name)) {
this.sortAble = !"false".equals(_value);
} else if ("FilterBase".equals(_name)) {
this.filter.evalBase(_value);
} else if ("FilterDefault".equals(_name)) {
this.filter.setDefaultValue(_value.trim());
} else if ("FilterType".equals(_name)) {
this.filter.evalType(_value);
} else if ("FilterRequired".equals(_name)) {
this.filter.setRequired("TRUE".equalsIgnoreCase(_value));
} else if ("FilterAttributes".equals(_name)) {
this.filter.setAttributes(_value);
} else if ("HideLabel".equals(_name)) {
this.hideLabel = "true".equals(_value);
} else if ("HRef".equals(_name)) {
this.reference = _value;
} else if ("Icon".equals(_name)) {
this.icon = _value;
} else if ("Label".equals(_name)) {
this.label = _value;
} else if ("ModeConnect".equals(_name)) {
this.mode2display.put(TargetMode.CONNECT, Field.Display.valueOf(_value.toUpperCase()));
} else if ("ModeCreate".equals(_name)) {
this.mode2display.put(TargetMode.CREATE, Field.Display.valueOf(_value.toUpperCase()));
} else if ("ModeEdit".equals(_name)) {
this.mode2display.put(TargetMode.EDIT, Field.Display.valueOf(_value.toUpperCase()));
} else if ("ModePrint".equals(_name)) {
this.mode2display.put(TargetMode.PRINT, Field.Display.valueOf(_value.toUpperCase()));
} else if ("ModeSearch".equals(_name)) {
this.mode2display.put(TargetMode.SEARCH, Field.Display.valueOf(_value.toUpperCase()));
} else if ("ModeView".equals(_name)) {
this.mode2display.put(TargetMode.VIEW, Field.Display.valueOf(_value.toUpperCase()));
} else if ("Required".equals(_name)) {
this.required = "true".equalsIgnoreCase(_value);
} else if ("Rows".equals(_name)) {
this.rows = Integer.parseInt(_value);
} else if ("RowSpan".equals(_name)) {
this.rowSpan = Integer.parseInt(_value);
} else if ("ShowTypeIcon".equals(_name)) {
this.showTypeIcon = "true".equalsIgnoreCase(_value);
} else if ("ShowNumbering".equals(_name)) {
this.showNumbering = "true".equalsIgnoreCase(_value);
} else if ("Target".equals(_name)) {
if ("content".equals(_value)) {
this.target = Target.CONTENT;
} else if ("hidden".equals(_value)) {
this.target = Target.HIDDEN;
} else if ("popup".equals(_value)) {
this.target = Target.POPUP;
}
}
super.setProperty(_name, _value);
} |
python | def golfclap(rest):
"Clap for something"
clapv = random.choice(phrases.clapvl)
adv = random.choice(phrases.advl)
adj = random.choice(phrases.adjl)
if rest:
clapee = rest.strip()
karma.Karma.store.change(clapee, 1)
return "/me claps %s for %s, %s %s." % (clapv, rest, adv, adj)
return "/me claps %s, %s %s." % (clapv, adv, adj) |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "operationVersion")
public JAXBElement<String> createOperationVersion(String value) {
return new JAXBElement<String>(_OperationVersion_QNAME, String.class, null, value);
} |
python | def _map_center(self, coord, val):
''' Identitify the center of the Image correspond to one coordinate. '''
if self.ppd in [4, 8, 16, 32, 64]:
res = {'lat': 0, 'long': 360}
return res[coord] / 2.0
elif self.ppd in [128]:
res = {'lat': 90, 'long': 90}
return (val // res[coord] + 1) * res[coord] - res[coord] / 2.0
elif self.ppd in [256]:
res = {'lat': 60, 'long': 90}
return (val // res[coord] + 1) * res[coord] - res[coord] / 2.0 |
java | public String getProperty(String key, String defaultValue) {
return props.getProperty(prefix + key, defaultValue);
} |
python | def grains(tgt=None, tgt_type='glob', **kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Return cached grains of the targeted minions.
tgt
Target to match minion ids.
.. versionchanged:: 2017.7.5,2018.3.0
The ``tgt`` argument is now required to display cached grains. If
not used, the function will not return grains. This optional
argument will become mandatory in the Salt ``Sodium`` release.
tgt_type
The type of targeting to use for matching, such as ``glob``, ``list``,
etc.
CLI Example:
.. code-block:: bash
salt-run cache.grains '*'
'''
if tgt is None:
# Change ``tgt=None`` to ``tgt`` (mandatory kwarg) in Salt Sodium.
# This behavior was changed in PR #45588 to fix Issue #45489.
salt.utils.versions.warn_until(
'Sodium',
'Detected missing \'tgt\' option. Cached grains will not be returned '
'without a specified \'tgt\'. This option will be required starting in '
'Salt Sodium and this warning will be removed.'
)
pillar_util = salt.utils.master.MasterPillarUtil(tgt, tgt_type,
use_cached_grains=True,
grains_fallback=False,
opts=__opts__)
cached_grains = pillar_util.get_minion_grains()
return cached_grains |
python | def handle_decoded_payload(self, data):
'''
Override this method if you wish to handle the decoded data
differently.
'''
# Ensure payload is unicode. Disregard failure to decode binary blobs.
if six.PY2:
data = salt.utils.data.decode(data, keep=True)
if 'user' in data:
log.info(
'User %s Executing command %s with jid %s',
data['user'], data['fun'], data['jid']
)
else:
log.info(
'Executing command %s with jid %s',
data['fun'], data['jid']
)
log.debug('Command details %s', data)
# Don't duplicate jobs
log.trace('Started JIDs: %s', self.jid_queue)
if self.jid_queue is not None:
if data['jid'] in self.jid_queue:
return
else:
self.jid_queue.append(data['jid'])
if len(self.jid_queue) > self.opts['minion_jid_queue_hwm']:
self.jid_queue.pop(0)
if isinstance(data['fun'], six.string_types):
if data['fun'] == 'sys.reload_modules':
self.functions, self.returners, self.function_errors, self.executors = self._load_modules()
self.schedule.functions = self.functions
self.schedule.returners = self.returners
process_count_max = self.opts.get('process_count_max')
process_count_max_sleep_secs = self.opts.get('process_count_max_sleep_secs')
if process_count_max > 0:
process_count = len(salt.utils.minion.running(self.opts))
while process_count >= process_count_max:
log.warning('Maximum number of processes (%s) reached while '
'executing jid %s, waiting %s seconds...',
process_count_max,
data['jid'],
process_count_max_sleep_secs)
yield tornado.gen.sleep(process_count_max_sleep_secs)
process_count = len(salt.utils.minion.running(self.opts))
# We stash an instance references to allow for the socket
# communication in Windows. You can't pickle functions, and thus
# python needs to be able to reconstruct the reference on the other
# side.
instance = self
multiprocessing_enabled = self.opts.get('multiprocessing', True)
if multiprocessing_enabled:
if sys.platform.startswith('win'):
# let python reconstruct the minion on the other side if we're
# running on windows
instance = None
with default_signals(signal.SIGINT, signal.SIGTERM):
process = SignalHandlingMultiprocessingProcess(
target=self._target, args=(instance, self.opts, data, self.connected)
)
else:
process = threading.Thread(
target=self._target,
args=(instance, self.opts, data, self.connected),
name=data['jid']
)
if multiprocessing_enabled:
with default_signals(signal.SIGINT, signal.SIGTERM):
# Reset current signals before starting the process in
# order not to inherit the current signal handlers
process.start()
else:
process.start()
# TODO: remove the windows specific check?
if multiprocessing_enabled and not salt.utils.platform.is_windows():
# we only want to join() immediately if we are daemonizing a process
process.join()
else:
self.win_proc.append(process) |
java | public static HeaderTypes create(final String name) {
if (name == null) {
throw new IllegalArgumentException("header name may not be null");
}
String type = name.trim().toLowerCase(Locale.ENGLISH);
if (type.length() == 0) {
throw new IllegalArgumentException("header name may not be empty");
}
return new HeaderTypes(name);
} |
java | @Override
public void onMessage(Message message, Session session) throws JMSException {
StandardLogger logger = LoggerUtil.getStandardLogger();
try {
String txt = ((TextMessage) message).getText();
if (logger.isDebugEnabled()) {
logger.debug("JMS Spring ExternalEvent Listener receives request: " + txt);
}
String resp;
ListenerHelper helper = new ListenerHelper();
Map<String, String> metaInfo = new HashMap<String, String>();
metaInfo.put(Listener.METAINFO_PROTOCOL, Listener.METAINFO_PROTOCOL_JMS);
metaInfo.put(Listener.METAINFO_REQUEST_PATH, ((Queue)message.getJMSDestination()).getQueueName());
metaInfo.put(Listener.METAINFO_SERVICE_CLASS, this.getClass().getName());
metaInfo.put(Listener.METAINFO_REQUEST_ID, message.getJMSMessageID());
metaInfo.put(Listener.METAINFO_CORRELATION_ID, message.getJMSCorrelationID());
if (message.getJMSReplyTo() != null)
metaInfo.put("ReplyTo", message.getJMSReplyTo().toString());
resp = helper.processEvent(txt, metaInfo);
String correlId = message.getJMSCorrelationID();
Queue respQueue = (Queue) message.getJMSReplyTo();
if (resp != null && respQueue != null) {
mdwMessageProducer.sendMessage(resp, respQueue, correlId);
if (logger.isDebugEnabled()) {
logger.debug("JMS Listener sends response (corr id='" + correlId + "'): "
+ resp);
}
}
}
catch (Throwable ex) {
logger.severeException(ex.getMessage(), ex);
}
} |
java | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache,no-store");
String url=request.getParameter("URL");
if (url!=null && url.length()>0)
{
response.sendRedirect(url);
}
else
{
PrintWriter pout = response.getWriter();
Page page=null;
try{
page = new Page();
page.title("SendRedirect Servlet");
page.add(new Heading(1,"SendRedirect Servlet"));
page.add(new Heading(1,"Form to generate Dump content"));
TableForm tf = new TableForm
(response.encodeURL(URI.addPaths(request.getContextPath(),
request.getServletPath())+
"/action"));
tf.method("GET");
tf.addTextField("URL","URL",40,request.getContextPath()+"/dump");
tf.addButton("Redirect","Redirect");
page.add(tf);
page.write(pout);
pout.close();
}
catch (Exception e)
{
log.warn(LogSupport.EXCEPTION,e);
}
}
} |
java | public JsonObject export() {
JsonObject result = JsonObject.create();
injectParams(result);
JsonObject queryJson = JsonObject.create();
queryPart.injectParamsAndBoost(queryJson);
return result.put("query", queryJson);
} |
java | protected Map<String, String> getElementAttributes() {
// Preserve order of attributes
Map<String, String> attrs = new HashMap<>();
if (this.getInput() != null) {
attrs.put("input", this.getInput().toString());
}
if (this.getAction() != null) {
attrs.put("action", this.getAction().toString());
}
if (this.getStatusCallback() != null) {
attrs.put("statusCallback", this.getStatusCallback().toString());
}
if (this.getStatusCallbackMethod() != null) {
attrs.put("statusCallbackMethod", this.getStatusCallbackMethod().toString());
}
if (this.getTimeout() != null) {
attrs.put("timeout", this.getTimeout().toString());
}
if (this.getMaxAttempts() != null) {
attrs.put("maxAttempts", this.getMaxAttempts().toString());
}
if (this.isSecurityCode() != null) {
attrs.put("securityCode", this.isSecurityCode().toString());
}
if (this.getPostalCode() != null) {
attrs.put("postalCode", this.getPostalCode());
}
if (this.getPaymentConnector() != null) {
attrs.put("paymentConnector", this.getPaymentConnector());
}
if (this.getTokenType() != null) {
attrs.put("tokenType", this.getTokenType().toString());
}
if (this.getChargeAmount() != null) {
attrs.put("chargeAmount", this.getChargeAmount());
}
if (this.getCurrency() != null) {
attrs.put("currency", this.getCurrency());
}
if (this.getDescription() != null) {
attrs.put("description", this.getDescription());
}
if (this.getValidCardTypess() != null) {
attrs.put("validCardTypes", this.getValidCardTypessAsString());
}
if (this.getLanguage() != null) {
attrs.put("language", this.getLanguage().toString());
}
return attrs;
} |
java | public Iterator<Page> getSortedPages()
{
return new AbstractIterator<Page>()
{
private int currentPosition;
private final PageBuilder pageBuilder = new PageBuilder(types);
private final int[] outputChannels = new int[types.size()];
{
Arrays.setAll(outputChannels, IntUnaryOperator.identity());
}
@Override
public Page computeNext()
{
currentPosition = buildPage(currentPosition, outputChannels, pageBuilder);
if (pageBuilder.isEmpty()) {
return endOfData();
}
Page page = pageBuilder.build();
pageBuilder.reset();
return page;
}
};
} |
python | def process_request(self, request_object):
"""Return a list of resources"""
resources = (request_object.entity_cls.query
.filter(**request_object.filters)
.offset((request_object.page - 1) * request_object.per_page)
.limit(request_object.per_page)
.order_by(request_object.order_by)
.all())
return ResponseSuccess(Status.SUCCESS, resources) |
java | public void map(Object key, Object value, OutputCollector output, Reporter reporter) throws IOException {
if (outerrThreadsThrowable != null) {
mapRedFinished();
throw new IOException ("MROutput/MRErrThread failed:"
+ StringUtils.stringifyException(
outerrThreadsThrowable));
}
try {
// 1/4 Hadoop in
numRecRead_++;
maybeLogRecord();
if (debugFailDuring_ && numRecRead_ == 3) {
throw new IOException("debugFailDuring_");
}
// 2/4 Hadoop to Tool
if (numExceptions_ == 0) {
if (!this.ignoreKey) {
write(key);
clientOut_.write(getInputSeparator());
}
write(value);
if (!ignoreNewLine) {
clientOut_.write('\n');
}
if(skipping) {
//flush the streams on every record input if running in skip mode
//so that we don't buffer other records surrounding a bad record.
clientOut_.flush();
}
} else {
numRecSkipped_++;
}
} catch (IOException io) {
numExceptions_++;
if (numExceptions_ > 1 || numRecWritten_ < minRecWrittenToEnableSkip_) {
// terminate with failure
String msg = logFailure(io);
appendLogToJobLog("failure");
mapRedFinished();
throw new IOException(msg);
} else {
// terminate with success:
// swallow input records although the stream processor failed/closed
}
}
} |
java | @NotNull
@Deprecated
@ObjectiveCName("requestStartAuthCommandWithEmail:")
public Command<AuthState> requestStartEmailAuth(final String email) {
return modules.getAuthModule().requestStartEmailAuth(email);
} |
java | public int getOrCreateVarIndex(final Variable var) {
Integer index = this.name2idx.get(var.name());
if (index == null) {
index = this.name2idx.size() + 1;
this.name2idx.put(var.name(), index);
this.idx2name.put(index, var.name());
}
return index;
} |
python | def _init_jupyter(run):
"""Asks for user input to configure the machine if it isn't already and creates a new run.
Log pushing and system stats don't start until `wandb.monitor()` is called.
"""
from wandb import jupyter
# TODO: Should we log to jupyter?
# global logging had to be disabled because it set the level to debug
# I also disabled run logging because we're rairly using it.
# try_to_set_up_global_logging()
# run.enable_logging()
api = InternalApi()
if not api.api_key:
termerror(
"Not authenticated. Copy a key from https://app.wandb.ai/profile?message=true")
key = getpass.getpass("API Key: ").strip()
if len(key) == 40:
os.environ[env.API_KEY] = key
util.write_netrc(api.api_url, "user", key)
else:
raise ValueError("API Key must be 40 characters long")
# Ensure our api client picks up the new key
api = InternalApi()
os.environ["WANDB_JUPYTER"] = "true"
run.resume = "allow"
api.set_current_run_id(run.id)
print("W&B Run: %s" % run.get_url(api))
print("Call `%%wandb` in the cell containing your training loop to display live results.")
try:
run.save(api=api)
except (CommError, ValueError) as e:
termerror(str(e))
run.set_environment()
run._init_jupyter_agent()
ipython = get_ipython()
ipython.register_magics(jupyter.WandBMagics)
def reset_start():
"""Reset START_TIME to when the cell starts"""
global START_TIME
START_TIME = time.time()
ipython.events.register("pre_run_cell", reset_start)
ipython.events.register('post_run_cell', run._stop_jupyter_agent) |
java | @Override
public XMLValidator createValidator(ValidationContext ctxt)
throws XMLStreamException
{
if (mFullyValidating) {
return new DTDValidator(this, ctxt, mHasNsDefaults,
getElementMap(), getGeneralEntityMap());
}
return new DTDTypingNonValidator(this, ctxt, mHasNsDefaults,
getElementMap(), getGeneralEntityMap());
} |
java | @Inject
void postConstruction(NetworkService networkService, ExecutorService executorService) {
this.network = networkService;
this.network.addListener(new NetworkStartListener(), executorService.getExecutorService());
} |
java | byte[] pickleMetrics(List<MetricTuple> metrics) throws IOException {
// Extremely rough estimate of 75 bytes per message
ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75);
Writer pickled = new OutputStreamWriter(out, charset);
pickled.append(MARK);
pickled.append(LIST);
for (MetricTuple tuple : metrics) {
// start the outer tuple
pickled.append(MARK);
// the metric name is a string.
pickled.append(STRING);
// the single quotes are to match python's repr("abcd")
pickled.append(QUOTE);
pickled.append(tuple.name);
pickled.append(QUOTE);
pickled.append(LF);
// start the inner tuple
pickled.append(MARK);
// timestamp is a long
pickled.append(LONG);
pickled.append(Long.toString(tuple.timestamp));
// the trailing L is to match python's repr(long(1234))
pickled.append(LONG);
pickled.append(LF);
// and the value is a string.
pickled.append(STRING);
pickled.append(QUOTE);
pickled.append(tuple.value);
pickled.append(QUOTE);
pickled.append(LF);
pickled.append(TUPLE); // inner close
pickled.append(TUPLE); // outer close
pickled.append(APPEND);
}
// every pickle ends with STOP
pickled.append(STOP);
pickled.flush();
return out.toByteArray();
} |
java | public void marshall(FileLocation fileLocation, ProtocolMarshaller protocolMarshaller) {
if (fileLocation == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(fileLocation.getStream(), STREAM_BINDING);
protocolMarshaller.marshall(fileLocation.getS3Location(), S3LOCATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | private VarOptItemsSketch<T> markMovingGadgetCoercer() {
final int resultK = gadget_.getHRegionCount() + gadget_.getRRegionCount();
int resultH = 0;
int resultR = 0;
int nextRPos = resultK; // = (resultK+1)-1, to fill R region from back to front
final ArrayList<T> data = new ArrayList<>(resultK + 1);
final ArrayList<Double> weights = new ArrayList<>(resultK + 1);
// Need arrays filled to use set() and be able to fill from end forward.
// Ideally would create as arrays but trying to avoid forcing user to pass a Class<?>
for (int i = 0; i < (resultK + 1); ++i) {
data.add(null);
weights.add(null);
}
final VarOptItemsSamples<T> sketchSamples = gadget_.getSketchSamples();
// insert R region items, ignoring weights
// Currently (May 2017) this next block is unreachable; this coercer is used only in the
// pseudo-exact case in which case there are no items natively in R, only marked items in H
// that will be moved into R as part of the coercion process.
Iterator<VarOptItemsSamples<T>.WeightedSample> sketchIterator;
sketchIterator = sketchSamples.getRIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
++resultR;
--nextRPos;
}
double transferredWeight = 0;
// insert H region items
sketchIterator = sketchSamples.getHIterator();
while (sketchIterator.hasNext()) {
final VarOptItemsSamples<T>.WeightedSample ws = sketchIterator.next();
if (ws.getMark()) {
data.set(nextRPos, ws.getItem());
weights.set(nextRPos, -1.0);
transferredWeight += ws.getWeight();
++resultR;
--nextRPos;
} else {
data.set(resultH, ws.getItem());
weights.set(resultH, ws.getWeight());
++resultH;
}
}
assert (resultH + resultR) == resultK;
assert Math.abs(transferredWeight - outerTauNumer) < 1e-10;
final double resultRWeight = gadget_.getTotalWtR() + transferredWeight;
final long resultN = n_;
// explicitly set values for the gap
data.set(resultH, null);
weights.set(resultH, -1.0);
// create sketch with the new values
return newInstanceFromUnionResult(data, weights, resultK, resultN, resultH, resultR, resultRWeight);
} |
java | private List<Map<String, Object>> selectionToList(CSLItemData[] selection) {
MapJsonBuilderFactory mjbf = new MapJsonBuilderFactory();
List<Map<String, Object>> sl = new ArrayList<>();
for (CSLItemData item : selection) {
JsonBuilder jb = mjbf.createJsonBuilder();
@SuppressWarnings("unchecked")
Map<String, Object> mi = (Map<String, Object>)item.toJson(jb);
for (Map.Entry<String, Object> e : mi.entrySet()) {
Object v = e.getValue();
if (e.getKey().equals("id") && v instanceof String &&
((String)v).startsWith("-GEN-")) {
//skip generated ids
continue;
}
if (v instanceof Collection) {
Collection<?> coll = (Collection<?>)v;
if (coll.isEmpty()) {
putSelectionFieldValue(sl, e, "");
} else {
for (Object ao : coll) {
putSelectionFieldValue(sl, e, ao);
}
}
} else if (v instanceof Map && ((Map<?, ?>)v).isEmpty()) {
putSelectionFieldValue(sl, e, "");
} else {
putSelectionFieldValue(sl, e, v);
}
}
}
return sl;
} |
python | def make_mercator(attrs_dict, globe):
"""Handle Mercator projection."""
attr_mapping = [('latitude_true_scale', 'standard_parallel'),
('scale_factor', 'scale_factor_at_projection_origin')]
kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)
# Work around the fact that in CartoPy <= 0.16 can't handle the easting/northing
# in Mercator
if not kwargs.get('false_easting'):
kwargs.pop('false_easting', None)
if not kwargs.get('false_northing'):
kwargs.pop('false_northing', None)
return ccrs.Mercator(globe=globe, **kwargs) |
python | def _create_sagemaker_model(self, instance_type, accelerator_type=None, tags=None):
"""Create a SageMaker Model Entity
Args:
instance_type (str): The EC2 instance type that this Model will be used for, this is only
used to determine if the image needs GPU support or not.
accelerator_type (str): Type of Elastic Inference accelerator to attach to an endpoint for model loading
and inference, for example, 'ml.eia1.medium'. If not specified, no Elastic Inference accelerator
will be attached to the endpoint.
tags(List[dict[str, str]]): Optional. The list of tags to add to the model. Example:
>>> tags = [{'Key': 'tagname', 'Value': 'tagvalue'}]
For more information about tags, see https://boto3.amazonaws.com/v1/documentation\
/api/latest/reference/services/sagemaker.html#SageMaker.Client.add_tags
"""
container_def = self.prepare_container_def(instance_type, accelerator_type=accelerator_type)
self.name = self.name or utils.name_from_image(container_def['Image'])
enable_network_isolation = self.enable_network_isolation()
self.sagemaker_session.create_model(self.name, self.role,
container_def, vpc_config=self.vpc_config,
enable_network_isolation=enable_network_isolation,
tags=tags) |
java | public WorkgroupProperties getWorkgroupProperties() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
WorkgroupProperties request = new WorkgroupProperties();
request.setType(IQ.Type.get);
request.setTo(workgroupJID);
return connection.createStanzaCollectorAndSend(request).nextResultOrThrow();
} |
python | def __roman_to_cyrillic(self, word):
"""
Transliterate a Russian word back into the Cyrillic alphabet.
A Russian word formerly transliterated into the Roman alphabet
in order to ease the stemming process, is transliterated back
into the Cyrillic alphabet, its original form.
:param word: The word that is transliterated.
:type word: str or unicode
:return: word, the transliterated word.
:rtype: unicode
:note: This helper method is invoked by the stem method of the subclass
RussianStemmer. It is not to be invoked directly!
"""
word = (word.replace("i^u", "\u044E").replace("i^a", "\u044F")
.replace("shch", "\u0449").replace("kh", "\u0445")
.replace("t^s", "\u0446").replace("ch", "\u0447")
.replace("e`", "\u044D").replace("i`", "\u0439")
.replace("sh", "\u0448").replace("k", "\u043A")
.replace("e", "\u0435").replace("zh", "\u0436")
.replace("a", "\u0430").replace("b", "\u0431")
.replace("v", "\u0432").replace("g", "\u0433")
.replace("d", "\u0434").replace("e", "\u0435")
.replace("z", "\u0437").replace("i", "\u0438")
.replace("l", "\u043B").replace("m", "\u043C")
.replace("n", "\u043D").replace("o", "\u043E")
.replace("p", "\u043F").replace("r", "\u0440")
.replace("s", "\u0441").replace("t", "\u0442")
.replace("u", "\u0443").replace("f", "\u0444")
.replace("''", "\u044A").replace("y", "\u044B")
.replace("'", "\u044C"))
return word |
java | public boolean foldComposite(final Instruction _instruction) throws ClassParseException {
boolean handled = false;
if (logger.isLoggable(Level.FINE)) {
System.out.println("foldComposite: curr = " + _instruction);
System.out.println(dumpDiagram(_instruction));
// System.out.println(dumpDiagram(null, _instruction));
}
if (_instruction.isForwardBranchTarget() || ((tail != null) && tail.isBranch() && tail.asBranch().isReverseConditional())) {
while (_instruction.isForwardBranchTarget()
|| ((tail != null) && tail.isBranch() && tail.asBranch().isReverseConditional())) {
if (logger.isLoggable(Level.FINE)) {
System.out.println(dumpDiagram(_instruction));
}
handled = false;
if ((tail != null) && tail.isBranch() && tail.asBranch().isReverseConditional()) {
/**
* This looks like an eclipse style for/while loop or possibly a do{}while()
* <pre>
* eclipse for (INIT,??,DELTA){BODY} ...
* [INIT] >> [BODY] [DELTA] ?? ?< ...
* ---------------->
* <-----------------
*
* eclipse for (,??,DELTA){BODY} ...
* >> [BODY] [DELTA] ?? ?< ...
* --------------->
* <-----------------
*
* do {BODY} while(??)
* [BODY] ?? ?< ...
* <-----------
*
* eclipse while (??){BODY} ...
* >> [BODY] ?? ?< ...
* -------->
* <----------
* </pre>
**/
final BranchSet branchSet = ((ConditionalBranch) tail.asBranch()).getOrCreateBranchSet();
Instruction loopTop = branchSet.getTarget().getRootExpr();
final Instruction beginingOfBranch = branchSet.getFirst();
final Instruction startOfBeginningOfBranch = beginingOfBranch.getStartInstruction();
// empty loops sometimes look like eclipse loops!
if (startOfBeginningOfBranch == loopTop) {
loopTop = loopTop.getPrevExpr();
if (loopTop instanceof AssignToLocalVariable) {
final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo();
if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC())
&& (localVariableInfo.getEnd() == _instruction.getThisPC())) {
loopTop = loopTop.getPrevExpr(); // back up over the initialization
}
}
addAsComposites(ByteCode.COMPOSITE_EMPTY_LOOP, loopTop, branchSet);
handled = true;
} else {
if ((loopTop.getPrevExpr() != null) && loopTop.getPrevExpr().isBranch()
&& loopTop.getPrevExpr().asBranch().isForwardUnconditional()) {
if (doesNotContainCompositeOrBranch(branchSet.getTarget().getRootExpr(), branchSet.getFirst().getPrevExpr())) {
branchSet.unhook();
loopTop.getPrevExpr().asBranch().unhook();
loopTop = loopTop.getPrevExpr();
// looptop == the unconditional?
loopTop = loopTop.getPrevExpr();
if (loopTop instanceof AssignToLocalVariable) {
final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo();
if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC())
&& (localVariableInfo.getEnd() == _instruction.getThisPC())) {
loopTop = loopTop.getPrevExpr(); // back up over the initialization
}
}
addAsComposites(ByteCode.COMPOSITE_FOR_ECLIPSE, loopTop, branchSet);
handled = true;
}
}
if (!handled) {
// do{}while()_ do not require any previous instruction
if (loopTop.getPrevExpr() == null) {
throw new IllegalStateException("might be a dowhile with no provious expression");
} else if (!(loopTop.getPrevExpr().isBranch() && loopTop.getPrevExpr().asBranch().isForwardUnconditional())) {
if (doesNotContainCompositeOrBranch(branchSet.getTarget().getRootExpr(), branchSet.getFirst()
.getPrevExpr())) {
loopTop = loopTop.getPrevExpr();
branchSet.unhook();
addAsComposites(ByteCode.COMPOSITE_DO_WHILE, loopTop, branchSet);
handled = true;
}
} else {
throw new IllegalStateException("might be mistaken for a do while!");
}
}
}
}
if (!handled && _instruction.isForwardConditionalBranchTarget() && tail.isBranch()
&& tail.asBranch().isReverseUnconditional()) {
/**
* This is s sun style loop
* <pre>
* sun for (INIT,??,DELTA){BODY} ...
*
* [INIT] ?? ?> [BODY] [DELTA] << ...
* ------------------>
* <-------------------
*
* sun for (,??,DELTA){BODY} ...
*
* ?? ?> [BODY] [DELTA] << ...
* ------------------>
* <-------------------
*
* sun while (?){l} ...
*
* ?? ?> [BODY] << ...
* ----------->
* <------------
*
*</pre>
*/
final ConditionalBranch lastForwardConditional = _instruction.getForwardConditionalBranches().getLast();
final BranchSet branchSet = lastForwardConditional.getOrCreateBranchSet();
final Branch reverseGoto = tail.asBranch();
final Instruction loopBackTarget = reverseGoto.getTarget();
if (loopBackTarget.getReverseUnconditionalBranches().size() > 1) {
throw new ClassParseException(ClassParseException.TYPE.CONFUSINGBRANCHESPOSSIBLYCONTINUE);
}
if (_instruction.isForwardUnconditionalBranchTarget()) {
/**
* Check if we have a break
* <pre>
* ?? ?> [BODY] ?1 ?> >> [BODY] << ...
* -------------------------->
* ---->
* ----------->
* <----------------------------
*
*</pre>
*/
final Branch lastForwardUnconditional = _instruction.getForwardUnconditionalBranches().getLast();
if ((lastForwardUnconditional != null) && lastForwardUnconditional.isAfter(lastForwardConditional)) {
throw new ClassParseException(ClassParseException.TYPE.CONFUSINGBRANCHESPOSSIBLYBREAK);
}
}
if (loopBackTarget != branchSet.getFirst().getStartInstruction()) {
/**
* we may have a if(?1){while(?2){}}else{...} where the else goto has been optimized away.
* <pre>
* One might expect
* ?1 ?> ?2 ?> [BODY] << >> [ELSE] ...
* ------------------->
* ----------->!
* <----------
* -------->
*
* However as above the conditional branch to the unconditional (!) can be optimized away and the conditional inverted and extended
* ?1 ?> ?2 ?> [BODY] << >> [ELSE] ...
* -------------------->
* -----------*--------->
* <-----------
*
* However we can also now remove the forward unconditional completely as it is unreachable
* ?1 ?> ?2 ?> [BODY] << [ELSE] ...
* ----------------->
* ------------------>
* <-----------
*
* </pre>
*/
final Instruction loopbackTargetRoot = loopBackTarget.getRootExpr();
if (loopbackTargetRoot.isBranch() && loopbackTargetRoot.asBranch().isConditional()) {
final ConditionalBranch topOfRealLoop = (ConditionalBranch) loopbackTargetRoot.asBranch();
BranchSet extentBranchSet = topOfRealLoop.getBranchSet();
if (topOfRealLoop.getBranchSet() == null) {
extentBranchSet = topOfRealLoop.findEndOfConditionalBranchSet(_instruction.getNextPC())
.getOrCreateBranchSet();
}
// We believe that this extendBranchSet is the real top of the while.
if (doesNotContainCompositeOrBranch(extentBranchSet.getLast().getNextExpr(), reverseGoto)) {
Instruction loopTop = topOfRealLoop.getPrevExpr();
if (loopTop instanceof AssignToLocalVariable) {
final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo();
if ((localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC())
&& (localVariableInfo.getEnd() == _instruction.getThisPC())) {
loopTop = loopTop.getPrevExpr(); // back up over the initialization
}
}
extentBranchSet.unhook();
addAsComposites(ByteCode.COMPOSITE_FOR_SUN, loopTop, extentBranchSet);
final UnconditionalBranch fakeGoto = new FakeGoto(methodModel, extentBranchSet.getLast().getTarget());
add(fakeGoto);
extentBranchSet.getLast().getTarget().addBranchTarget(fakeGoto);
handled = true;
}
}
} else {
/**
* Just a normal sun style loop
*/
if (doesNotContainCompositeOrBranch(branchSet.getLast().getNextExpr(), reverseGoto)) {
Instruction loopTop = reverseGoto.getTarget().getRootExpr().getPrevExpr();
if (logger.isLoggable(Level.FINEST)) {
Instruction next = branchSet.getFirst().getNextExpr();
System.out.println("### for/while candidate exprs: " + branchSet.getFirst());
while (next != null) {
System.out.println("### expr = " + next);
next = next.getNextExpr();
}
}
if (loopTop instanceof AssignToLocalVariable) {
final LocalVariableInfo localVariableInfo = ((AssignToLocalVariable) loopTop).getLocalVariableInfo();
if ((localVariableInfo != null)
&& (localVariableInfo.getStart() == loopTop.getNextExpr().getStartPC())
&& (localVariableInfo.getEnd() == _instruction.getThisPC())) {
loopTop = loopTop.getPrevExpr(); // back up over the initialization
}
}
branchSet.unhook();
// If there is an inner scope, it is likely that the loop counter var
// is modified using an inner scope variable so use while rather than for
if (reverseGoto.getPrevExpr() instanceof CompositeArbitraryScopeInstruction) {
addAsComposites(ByteCode.COMPOSITE_WHILE, loopTop, branchSet);
} else {
addAsComposites(ByteCode.COMPOSITE_FOR_SUN, loopTop, branchSet);
}
handled = true;
}
}
}
if (!handled && !tail.isForwardBranch() && _instruction.isForwardConditionalBranchTarget()) {
/**
* This an if(exp)
*<pre> *
* if(??){then}...
* ?? ?> [THEN] ...
* -------->
*
*</pre>
*/
final ConditionalBranch lastForwardConditional = _instruction.getForwardConditionalBranches().getLast();
final BranchSet branchSet = lastForwardConditional.getOrCreateBranchSet();
if (doesNotContainContinueOrBreak(branchSet.getLast().getNextExpr(), _instruction)) {
branchSet.unhook();
addAsComposites(ByteCode.COMPOSITE_IF, branchSet.getFirst().getPrevExpr(), branchSet);
handled = true;
}
}
if (!handled && !tail.isForwardBranch() && _instruction.isForwardUnconditionalBranchTarget()) {
final LinkedList<Branch> forwardUnconditionalBranches = _instruction.getForwardUnconditionalBranches();
final Branch lastForwardUnconditional = forwardUnconditionalBranches.getLast();
final Instruction afterGoto = lastForwardUnconditional.getNextExpr();
if (afterGoto.getStartInstruction().isForwardConditionalBranchTarget()) {
final LinkedList<ConditionalBranch> forwardConditionalBranches = afterGoto.getStartInstruction()
.getForwardConditionalBranches();
final ConditionalBranch lastForwardConditional = forwardConditionalBranches.getLast();
final BranchSet branchSet = lastForwardConditional.getOrCreateBranchSet();
if (doesNotContainCompositeOrBranch(branchSet.getLast().getNextExpr(), lastForwardUnconditional)) {
if (doesNotContainContinueOrBreak(afterGoto.getNextExpr(), _instruction)) {
branchSet.unhook();
lastForwardUnconditional.unhook();
addAsComposites(ByteCode.COMPOSITE_IF_ELSE, branchSet.getFirst().getPrevExpr(), branchSet);
handled = true;
}
} else {
//then not clean.
final ExpressionList newHeadTail = new ExpressionList(methodModel, this, lastForwardUnconditional);
handled = newHeadTail.foldComposite(lastForwardUnconditional.getStartInstruction());
newHeadTail.unwind();
// handled = foldCompositeRecurse(lastForwardUnconditional);
if (!handled && (forwardUnconditionalBranches.size() > 1)) {
// BI AI AE BE
// ?> ?> .. >> .. >> C S
// ?---------------------->22
// ?---------->18
// +-------------->31
// +------>31
// Javac sometimes performs the above optimization. Basically the GOTO for the inner IFELSE(AI,AE) instead of targeting the GOTO
// from the outer IFELSE(B1,BE) so instead of AE->BE->... we have AE-->...
//
// So given more than one target we retreat up the list of unconditionals until we find a clean one treating the previously visited GOTO
// as a possible end
for (int i = forwardUnconditionalBranches.size(); i > 1; i--) {
final Branch thisGoto = forwardUnconditionalBranches.get(i - 1);
final Branch elseGoto = forwardUnconditionalBranches.get(i - 2);
final Instruction afterElseGoto = elseGoto.getNextExpr();
if (afterElseGoto.getStartInstruction().isConditionalBranchTarget()) {
final BranchSet elseBranchSet = afterElseGoto.getStartInstruction()
.getForwardConditionalBranches().getLast().getOrCreateBranchSet();
if (doesNotContainCompositeOrBranch(elseBranchSet.getLast().getNextExpr(), elseGoto)) {
if (doesNotContainCompositeOrBranch(afterElseGoto.getNextExpr(), thisGoto)) {
if (logger.isLoggable(Level.FINE)) {
System.out.println(dumpDiagram(_instruction));
}
elseBranchSet.unhook();
elseGoto.unhook();
if (logger.isLoggable(Level.FINE)) {
System.out.println(dumpDiagram(_instruction));
}
final CompositeInstruction composite = CompositeInstruction.create(
ByteCode.COMPOSITE_IF_ELSE, methodModel, elseBranchSet.getFirst(), thisGoto,
elseBranchSet);
replaceInclusive(elseBranchSet.getFirst(), thisGoto.getPrevExpr(), composite);
handled = true;
break;
}
}
}
}
}
}
}
}
if (!handled && !tail.isForwardBranch() && _instruction.isForwardConditionalBranchTarget()
&& _instruction.isForwardUnconditionalBranchTarget()) {
// here we have multiple composites ending at the same point
final Branch lastForwardUnconditional = _instruction.getForwardUnconditionalBranches().getLast();
final ConditionalBranch lastForwardConditional = _instruction.getStartInstruction()
.getForwardConditionalBranches().getLast();
// we will clip the tail and see if recursing helps
if (lastForwardConditional.getTarget().isAfter(lastForwardUnconditional)) {
lastForwardConditional.retarget(lastForwardUnconditional);
final ExpressionList newHeadTail = new ExpressionList(methodModel, this, lastForwardUnconditional);
handled = newHeadTail.foldComposite(lastForwardUnconditional.getStartInstruction());
newHeadTail.unwind();
}
}
if (!handled) {
break;
}
}
} else {
// might be end of arbitrary scope
final LocalVariableTableEntry<LocalVariableInfo> localVariableTable = methodModel.getMethod()
.getLocalVariableTableEntry();
int startPc = Short.MAX_VALUE;
for (final LocalVariableInfo localVariableInfo : localVariableTable) {
if (localVariableInfo.getEnd() == _instruction.getThisPC()) {
logger.fine(localVariableInfo.getVariableName() + " scope " + localVariableInfo.getStart() + " ,"
+ localVariableInfo.getEnd());
if (localVariableInfo.getStart() < startPc) {
startPc = localVariableInfo.getStart();
}
}
}
if (startPc < Short.MAX_VALUE) {
logger.fine("Scope block from " + startPc + " to " + (tail.getThisPC() + tail.getLength()));
for (Instruction i = head; i != null; i = i.getNextPC()) {
if (i.getThisPC() == startPc) {
final Instruction j = i.getRootExpr().getPrevExpr();
final Instruction startInstruction = j == null ? i : j;
logger.fine("Start = " + startInstruction);
addAsComposites(ByteCode.COMPOSITE_ARBITRARY_SCOPE, startInstruction.getPrevExpr(), null);
handled = true;
break;
}
}
}
}
if (Config.instructionListener != null) {
Config.instructionListener.showAndTell("after folding", head, _instruction);
}
return (handled);
} |
java | public Object execute(final Object value, final CsvContext context) {
if (value == null){
throw new SuperCsvConstraintViolationException("null value encountered", context, this);
}
return next.execute(value, context);
} |
python | def is_authorized_default(hijacker, hijacked):
"""Checks if the user has the correct permission to Hijack another user.
By default only superusers are allowed to hijack.
An exception is made to allow staff members to hijack when
HIJACK_AUTHORIZE_STAFF is enabled in the Django settings.
By default it prevents staff users from hijacking other staff users.
This can be disabled by enabling the HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF
setting in the Django settings.
Staff users can never hijack superusers.
"""
if hijacker.is_superuser:
return True
if hijacked.is_superuser:
return False
if hijacker.is_staff and hijack_settings.HIJACK_AUTHORIZE_STAFF:
if hijacked.is_staff and not hijack_settings.HIJACK_AUTHORIZE_STAFF_TO_HIJACK_STAFF:
return False
return True
return False |
python | def getCellStr(self, x, y): # TODO: refactor regarding issue #11
"""
return a string representation of the cell located at x,y.
"""
c = self.board.getCell(x, y)
if c == 0:
return '.' if self.__azmode else ' .'
elif self.__azmode:
az = {}
for i in range(1, int(math.log(self.board.goal(), 2))):
az[2 ** i] = chr(i + 96)
if c not in az:
return '?'
s = az[c]
elif c == 1024:
s = ' 1k'
elif c == 2048:
s = ' 2k'
else:
s = '%3d' % c
return self.__colors.get(c, Fore.RESET) + s + Style.RESET_ALL |
python | def calculate_first_digit(number):
""" This function calculates the first check digit of a
cpf or cnpj.
:param number: cpf (length 9) or cnpf (length 12)
string to check the first digit. Only numbers.
:type number: string
:returns: string -- the first digit
"""
sum = 0
if len(number) == 9:
weights = CPF_WEIGHTS[0]
else:
weights = CNPJ_WEIGHTS[0]
for i in range(len(number)):
sum = sum + int(number[i]) * weights[i]
rest_division = sum % DIVISOR
if rest_division < 2:
return '0'
return str(11 - rest_division) |
java | @Override
public List<GoogleCloudStorageItemInfo> listObjectInfo(
String bucketName, String objectNamePrefix, String delimiter) throws IOException {
return listObjectInfo(bucketName, objectNamePrefix, delimiter, MAX_RESULTS_UNLIMITED);
} |
java | public static KAlignerParameters getByName(String name) {
KAlignerParameters params = knownParameters.get(name);
if (params == null)
return null;
return params.clone();
} |
java | @Override
public GetIntegrationsResult getIntegrations(GetIntegrationsRequest request) {
request = beforeClientExecution(request);
return executeGetIntegrations(request);
} |
java | protected List<ColumnDef> getColumnMetadata(Cassandra.Client client)
throws TException, CharacterCodingException, InvalidRequestException, ConfigurationException
{
return getColumnMeta(client, true, true);
} |
python | def exists(self, client=None):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. The client to use. If not passed, falls back
to the ``client`` stored on the blob's bucket.
:rtype: bool
:returns: True if the blob exists in Cloud Storage.
"""
client = self._require_client(client)
# We only need the status code (200 or not) so we seek to
# minimize the returned payload.
query_params = self._query_params
query_params["fields"] = "name"
try:
# We intentionally pass `_target_object=None` since fields=name
# would limit the local properties.
client._connection.api_request(
method="GET",
path=self.path,
query_params=query_params,
_target_object=None,
)
# NOTE: This will not fail immediately in a batch. However, when
# Batch.finish() is called, the resulting `NotFound` will be
# raised.
return True
except NotFound:
return False |
java | private void readXmlDeclaration() throws IOException, KriptonRuntimeException {
if (bufferStartLine != 0 || bufferStartColumn != 0 || position != 0) {
checkRelaxed("processing instructions must not start with xml");
}
read(START_PROCESSING_INSTRUCTION);
parseStartTag(true, true);
if (attributeCount < 1 || !"version".equals(attributes[2])) {
checkRelaxed("version expected");
}
version = attributes[3];
int pos = 1;
if (pos < attributeCount && "encoding".equals(attributes[2 + 4])) {
encoding = attributes[3 + 4];
pos++;
}
if (pos < attributeCount && "standalone".equals(attributes[4 * pos + 2])) {
String st = attributes[3 + 4 * pos];
if ("yes".equals(st)) {
standalone = Boolean.TRUE;
} else if ("no".equals(st)) {
standalone = Boolean.FALSE;
} else {
checkRelaxed("illegal standalone value: " + st);
}
pos++;
}
if (pos != attributeCount) {
checkRelaxed("unexpected attributes in XML declaration");
}
isWhitespace = true;
text = null;
} |
java | public Observable<ServerInner> beginUpdateAsync(String resourceGroupName, String serverName, ServerUpdateParameters parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() {
@Override
public ServerInner call(ServiceResponse<ServerInner> response) {
return response.body();
}
});
} |
java | @Override
public JsonToken nextToken() throws IOException {
if (nextToken != null) {
_currToken = nextToken;
nextToken = null;
return _currToken;
}
// are we to descend to a container child?
if (startContainer) {
startContainer = false;
// minor optimization: empty containers can be skipped
if (!nodeCursor.currentHasChildren()) {
_currToken = (_currToken == JsonToken.START_OBJECT) ?
JsonToken.END_OBJECT : JsonToken.END_ARRAY;
return _currToken;
}
nodeCursor = nodeCursor.iterateChildren();
_currToken = nodeCursor.nextToken();
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
startContainer = true;
}
return _currToken;
}
// No more content?
if (nodeCursor == null) {
closed = true; // if not already set
return null;
}
// Otherwise, next entry from currentFieldName cursor
_currToken = nodeCursor.nextToken();
if (_currToken != null) {
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
startContainer = true;
}
return _currToken;
}
// null means no more children; need to return end marker
_currToken = nodeCursor.endToken();
nodeCursor = nodeCursor.getParent();
return _currToken;
} |
java | public CreateSnapshotScheduleResult withScheduleDefinitions(String... scheduleDefinitions) {
if (this.scheduleDefinitions == null) {
setScheduleDefinitions(new com.amazonaws.internal.SdkInternalList<String>(scheduleDefinitions.length));
}
for (String ele : scheduleDefinitions) {
this.scheduleDefinitions.add(ele);
}
return this;
} |
java | public org.grails.datastore.mapping.query.api.Criteria order(Order o) {
final Criteria criteria = this.criteria;
addOrderInternal(criteria, o);
return this;
} |
java | public EEnum getIfcBeamTypeEnum() {
if (ifcBeamTypeEnumEEnum == null) {
ifcBeamTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(784);
}
return ifcBeamTypeEnumEEnum;
} |
java | public void write(byte[] b, int off, int len)
{
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
size += len;
} |
java | @Override
public void filter(ContainerRequestContext incomingRequestContext,
ContainerResponseContext outgoingResponseContext) throws IOException {
String methodName = "filter(outgoing)";
Boolean skipped = (Boolean) incomingRequestContext.getProperty(OpentracingContainerFilter.SERVER_SPAN_SKIPPED_ID);
if (skipped != null) {
// Remove it immediately
incomingRequestContext.removeProperty(OpentracingContainerFilter.SERVER_SPAN_SKIPPED_ID);
}
if (skipped != null && skipped) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " skipped");
}
return;
}
// If processing wasn't skipped, then we should have an ActiveSpan
Scope scope = (Scope) incomingRequestContext.getProperty(OpentracingContainerFilter.SERVER_SPAN_PROP_ID);
if (scope == null) {
// This may occur if there's no Tracer (see other method); otherwise, there's
// probably some bug sending the right ActiveSpan (e.g. threading?).
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " no span");
}
return;
}
incomingRequestContext.removeProperty(OpentracingContainerFilter.SERVER_SPAN_PROP_ID);
try {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " span", scope.span());
}
Integer httpStatus = Integer.valueOf(outgoingResponseContext.getStatus());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " httpStatus", httpStatus);
}
scope.span().setTag(Tags.HTTP_STATUS.getKey(), httpStatus);
if (outgoingResponseContext.getStatus() >= 400) {
MultivaluedMap<String, Object> headers = outgoingResponseContext.getHeaders();
Throwable exception = (Throwable) headers.getFirst(EXCEPTION_KEY);
if (exception != null) {
headers.remove(EXCEPTION_KEY);
}
OpentracingService.addSpanErrorInfo(scope.span(), exception);
}
} finally {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " finish span", scope.span());
}
scope.close();
}
} |
java | public void marshall(DeleteEmailIdentityRequest deleteEmailIdentityRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteEmailIdentityRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteEmailIdentityRequest.getEmailIdentity(), EMAILIDENTITY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def get(cls, block_type):
"""Return a :class:`BlockType` instance from the given parameter.
* If it's already a BlockType instance, return that.
* If it exactly matches the command on a :class:`PluginBlockType`,
return the corresponding BlockType.
* If it loosely matches the text on a PluginBlockType, return the
corresponding BlockType.
* If it's a PluginBlockType instance, look for and return the
corresponding BlockType.
"""
if isinstance(block_type, (BlockType, CustomBlockType)):
return block_type
if isinstance(block_type, PluginBlockType):
block_type = block_type.command
block = kurt.plugin.Kurt.block_by_command(block_type)
if block:
return block
blocks = kurt.plugin.Kurt.blocks_by_text(block_type)
for block in blocks: # check the blocks' commands map to unique blocks
if kurt.plugin.Kurt.block_by_command(
block.convert().command) != blocks[0]:
raise ValueError(
"ambigious block text %r, use one of %r instead" %
(block_type, [b.convert().command for b in blocks]))
if blocks:
return blocks[0]
raise UnknownBlock, repr(block_type) |
java | @Override
@SuppressWarnings("checkstyle:linelength")
public Page<Recording> firstPage(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.VIDEO.toString(),
"/v1/Recordings",
client.getRegion()
);
addQueryParams(request);
return pageForRequest(client, request);
} |
java | public synchronized void updateAndAdd(JmxRequest pJmxReq, JSONObject pJson) {
long timestamp = System.currentTimeMillis() / 1000;
pJson.put(KEY_TIMESTAMP,timestamp);
RequestType type = pJmxReq.getType();
HistoryUpdater updater = historyUpdaters.get(type);
if (updater != null) {
updater.updateHistory(pJson,pJmxReq,timestamp);
}
} |
java | public long[] toPrimitiveArray(long[] array) {
for (int i = 0, j = 0; i < array.length; ++i) {
int index = -1;
if (j < indices.length && (index = indices[j]) == i) {
array[i] = values[j];
j++;
}
else
array[i] = 0;
}
return array;
} |
python | def remove_cgc_attachments(self):
"""
Remove CGC attachments.
:return: True if CGC attachments are found and removed, False otherwise
:rtype: bool
"""
cgc_package_list = None
cgc_extended_application = None
for data in self.data:
if data.sort == 'cgc-package-list':
cgc_package_list = data
elif data.sort == 'cgc-extended-application':
cgc_extended_application = data
if not cgc_package_list or not cgc_extended_application:
return False
if cgc_package_list.skip or cgc_extended_application.skip:
# they have already been removed
# so we still return True to indicate that CGC attachments have been removed
return True
# there is a single function referencing them
cgcpl_memory_data = self.cfg.memory_data.get(cgc_package_list.addr, None)
cgcea_memory_data = self.cfg.memory_data.get(cgc_extended_application.addr, None)
refs = self.cfg.model.references
if cgcpl_memory_data is None or cgcea_memory_data is None:
return False
if len(refs.data_addr_to_ref[cgcpl_memory_data.addr]) != 1:
return False
if len(refs.data_addr_to_ref[cgcea_memory_data.addr]) != 1:
return False
# check if the irsb addresses are the same
if next(iter(refs.data_addr_to_ref[cgcpl_memory_data.addr])).block_addr != \
next(iter(refs.data_addr_to_ref[cgcea_memory_data.addr])).block_addr:
return False
insn_addr = next(iter(refs.data_addr_to_ref[cgcpl_memory_data.addr])).insn_addr
# get the basic block
cfg_node = self.cfg.get_any_node(insn_addr, anyaddr=True)
if not cfg_node:
return False
func_addr = cfg_node.function_address
# this function should be calling another function
sub_func_addr = None
if func_addr not in self.cfg.functions:
return False
function = self.cfg.functions[func_addr]
# traverse the graph and make sure there is only one call edge
calling_targets = [ ]
for _, dst, data in function.transition_graph.edges(data=True):
if 'type' in data and data['type'] == 'call':
calling_targets.append(dst.addr)
if len(calling_targets) != 1:
return False
sub_func_addr = calling_targets[0]
# alright. We want to nop this function, as well as the subfunction
proc = next((p for p in self.procedures if p.addr == func_addr), None)
if proc is None:
return False
subproc = next((p for p in self.procedures if p.addr == sub_func_addr), None)
if subproc is None:
return False
# if those two data entries have any label, we should properly modify them
# at this point, we are fairly confident that none of those labels are direct data references to either package
# list or extended application
has_label = True
lowest_address = min(cgc_package_list.addr, cgc_extended_application.addr)
for obj in (cgc_package_list, cgc_extended_application):
labels = obj.labels
for addr, label in labels:
if addr != lowest_address:
label.base_addr = lowest_address
if has_label:
# is there any memory data entry that ends right at the lowest address?
data = next((d for d in self.data if d.addr is not None and d.addr + d.size == lowest_address), None)
if data is None:
# since there is no gap between memory data entries (we guarantee that), this can only be that no other
# data resides in the same memory region that CGC attachments are in
pass
else:
lbl = self.symbol_manager.addr_to_label[lowest_address][0]
if lbl not in data.end_labels:
data.end_labels.append(lbl)
# practically nop the function
proc.asm_code = "\tret\n"
subproc.asm_code = "\tret\n"
# remove those two data entries
cgc_package_list.skip = True
cgc_extended_application.skip = True
l.info('CGC attachments are removed.')
return True |
python | def _create_diffuse_src_from_xml(self, config, src_type='FileFunction'):
"""Load sources from an XML file.
"""
diffuse_xmls = config.get('diffuse_xml')
srcs_out = []
for diffuse_xml in diffuse_xmls:
srcs_out += self.load_xml(diffuse_xml, coordsys=config.get('coordsys', 'CEL'))
return srcs_out |
python | def iter_orgs(self, number=-1, etag=None):
"""Iterate over organizations the user is member of
:param int number: (optional), number of organizations to return.
Default: -1 returns all available organization
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: list of :class:`Event <github3.orgs.Organization>`\ s
"""
# Import here, because a toplevel import causes an import loop
from .orgs import Organization
url = self._build_url('orgs', base_url=self._api)
return self._iter(int(number), url, Organization, etag=etag) |
java | public static CommerceCurrency fetchByUuid_Last(String uuid,
OrderByComparator<CommerceCurrency> orderByComparator) {
return getPersistence().fetchByUuid_Last(uuid, orderByComparator);
} |
java | public <T> void RegisterClazz( Clazz<T> clazz )
{
_ensureMap();
if( clazzz.containsKey( clazz.getReflectedClass() ) )
return;
clazzz.put( clazz.getReflectedClass(), clazz );
} |
python | def schemaNewMemParserCtxt(buffer, size):
"""Create an XML Schemas parse context for that memory buffer
expected to contain an XML Schemas file. """
ret = libxml2mod.xmlSchemaNewMemParserCtxt(buffer, size)
if ret is None:raise parserError('xmlSchemaNewMemParserCtxt() failed')
return SchemaParserCtxt(_obj=ret) |
java | public void getTraceSummaryLine(StringBuilder buff) {
// Get the common fields for control messages
super.getTraceSummaryLine(buff);
buff.append(",tick=");
buff.append(getTick());
} |
java | public ISarlConstructorBuilder addSarlConstructor() {
ISarlConstructorBuilder builder = this.iSarlConstructorBuilderProvider.get();
builder.eInit(getSarlEvent(), getTypeResolutionContext());
return builder;
} |
java | public void with(@javax.annotation.Nonnull final java.util.function.Consumer<T> f, final Predicate<T> filter) {
final T prior = currentValue.get();
if (null != prior) {
f.accept(prior);
}
else {
final T poll = get(filter);
try {
currentValue.set(poll);
f.accept(poll);
} finally {
this.pool.add(poll);
currentValue.remove();
}
}
} |
java | protected static String determineCollectionName(Class<?> entityClass) {
if (entityClass == null) {
throw new InvalidJsonDbApiUsageException(
"No class parameter provided, entity collection can't be determined");
}
Document doc = entityClass.getAnnotation(Document.class);
if (null == doc) {
throw new InvalidJsonDbApiUsageException(
"Entity '" + entityClass.getSimpleName() + "' is not annotated with annotation @Document");
}
String collectionName = doc.collection();
return collectionName;
} |
java | static synchronized ExecutorService getExecutorService() {
if (executorService == null) {
executorService = Executors.newCachedThreadPool(new NamingThreadFactory(new DaemonThreadFactory(), "org.jenkinsci.plugins.pipeline.maven.fix.jenkins49337.GeneralNonBlockingStepExecution"));
}
return executorService;
} |
python | def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons
poly = geometry.Polygon(zip(x, y))
return poly.area |
python | def mecanum_drivetrain(
lr_motor,
rr_motor,
lf_motor,
rf_motor,
x_wheelbase=2,
y_wheelbase=3,
speed=5,
deadzone=None,
):
"""
.. deprecated:: 2018.2.0
Use :class:`MecanumDrivetrain` instead
"""
return MecanumDrivetrain(x_wheelbase, y_wheelbase, speed, deadzone).get_vector(
lr_motor, rr_motor, lf_motor, rf_motor
) |
java | public Optional<PartnerAccount> show(long partnerId, long accountId)
{
return HTTP.GET(String.format("/v2/partners/%d/accounts/%d", partnerId, accountId), PARTNER_ACCOUNT);
} |
java | private void consumeKeyword(char first, char[] expected) throws JsonParserException {
for (int i = 0; i < expected.length; i++)
if (advanceChar() != expected[i])
throw createHelpfulException(first, expected, i);
// The token should end with something other than an ASCII letter
if (isAsciiLetter(peekChar()))
throw createHelpfulException(first, expected, expected.length);
} |
python | def add_to_triplestore(self, output):
"""Method attempts to add output to Blazegraph RDF Triplestore"""
if len(output) > 0:
result = self.ext_conn.load_data(data=output.serialize(),
datatype='rdf') |
python | def build(source_dir, target_dir, package_name=None, version_number=None):
'''
Create a release of a MicroDrop plugin source directory in the target
directory path.
Skip the following patterns:
- ``bld.bat``
- ``.conda-recipe/*``
- ``.git/*``
.. versionchanged:: 0.24.1
Remove temporary archive after extraction.
Change directory into source directory before running ``git archive``.
.. versionchanged:: 0.25
Add optional :data:`version_number` argument.
Parameters
----------
source_dir : str
Source directory.
target_dir : str
Target directory.
package_name : str, optional
Name of plugin Conda package (defaults to name of :data:`target_dir`).
version_number : str, optional
Package version number.
If not specified, assume version package exposes version using
`versioneer <https://github.com/warner/python-versioneer>`_.
'''
source_dir = ph.path(source_dir).realpath()
target_dir = ph.path(target_dir).realpath()
target_dir.makedirs_p()
source_archive = source_dir.joinpath(source_dir.name + '.zip')
if package_name is None:
package_name = str(target_dir.name)
logger.info('Source directory: %s', source_dir)
logger.info('Source archive: %s', source_archive)
logger.info('Target directory: %s', target_dir)
logger.info('Package name: %s', package_name)
# Export git archive, which substitutes version expressions in
# `_version.py` to reflect the state (i.e., revision and tag info) of the
# git repository.
original_dir = ph.path(os.getcwd())
try:
os.chdir(source_dir)
sp.check_call(['git', 'archive', '-o', source_archive, 'HEAD'],
shell=True)
finally:
os.chdir(original_dir)
# Extract exported git archive to Conda MicroDrop plugins directory.
with zipfile.ZipFile(source_archive, 'r') as zip_ref:
zip_ref.extractall(target_dir)
# Extraction is complete. Remove temporary archive.
source_archive.remove()
# Delete Conda build recipe from installed package.
target_dir.joinpath('.conda-recipe').rmtree()
# Delete Conda build recipe from installed package.
for p in target_dir.files('.git*'):
p.remove()
# Write package information to (legacy) `properties.yml` file.
original_dir = ph.path(os.getcwd())
try:
os.chdir(source_dir)
if version_number is None:
# Assume versioneer is being used for managing version.
import _version as v
version_info = {'version': v.get_versions()['version'],
'versioneer': v.get_versions()}
else:
# Version number was specified explicitly.
version_info = {'version': version_number}
finally:
os.chdir(original_dir)
# Create properties dictionary object (cast types, e.g., `ph.path`, to
# strings for cleaner YAML dump).
properties = {'package_name': package_name,
'plugin_name': str(target_dir.name)}
properties.update(version_info)
with target_dir.joinpath('properties.yml').open('w') as properties_yml:
# Dump properties to YAML-formatted file.
# Setting `default_flow_style=False` writes each property on a separate
# line (cosmetic change only).
yaml.dump(properties, properties_yml, default_flow_style=False) |
java | private void svdImpute(double[][] raw, double[][] data) {
SVD svd = Matrix.newInstance(data).svd();
int d = data[0].length;
for (int i = 0; i < raw.length; i++) {
int missing = 0;
for (int j = 0; j < d; j++) {
if (Double.isNaN(raw[i][j])) {
missing++;
} else {
data[i][j] = raw[i][j];
}
}
if (missing == 0) {
continue;
}
DenseMatrix A = Matrix.zeros(d - missing, k);
double[] b = new double[d - missing];
for (int j = 0, m = 0; j < d; j++) {
if (!Double.isNaN(raw[i][j])) {
for (int l = 0; l < k; l++) {
A.set(m, l, svd.getV().get(j, l));
}
b[m++] = raw[i][j];
}
}
double[] s = new double[k];
QR qr = A.qr();
qr.solve(b, s);
for (int j = 0; j < d; j++) {
if (Double.isNaN(raw[i][j])) {
data[i][j] = 0;
for (int l = 0; l < k; l++) {
data[i][j] += s[l] * svd.getV().get(j, l);
}
}
}
}
} |
java | public void commit(ObjectEnvelope mod) throws PersistenceBrokerException
{
mod.doInsert();
mod.setModificationState(StateOldClean.getInstance());
} |
python | def from_dict(cls, d):
"""
Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object.
"""
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_permissions.read = d.get('read')
enclave_permissions.create = d.get('create')
enclave_permissions.update = d.get('update')
return enclave_permissions |
java | public int[] getMetricsTT(int c) {
if (cmapExt != null)
return (int[])cmapExt.get(Integer.valueOf(c));
HashMap map = null;
if (fontSpecific)
map = cmap10;
else
map = cmap31;
if (map == null)
return null;
if (fontSpecific) {
if ((c & 0xffffff00) == 0 || (c & 0xffffff00) == 0xf000)
return (int[])map.get(Integer.valueOf(c & 0xff));
else
return null;
}
else
return (int[])map.get(Integer.valueOf(c));
} |
java | @Override public String convertValueToText(Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
{
String result = "";
if (value instanceof Entry)
{
result = ((Entry) value).getName();
}
return result;
} |
java | public Observable<CertificateOperation> updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, boolean cancellationRequested) {
return updateCertificateOperationWithServiceResponseAsync(vaultBaseUrl, certificateName, cancellationRequested).map(new Func1<ServiceResponse<CertificateOperation>, CertificateOperation>() {
@Override
public CertificateOperation call(ServiceResponse<CertificateOperation> response) {
return response.body();
}
});
} |
python | def description(self):
'''Provide a description for each algorithm available, useful to print in ecc file'''
if 0 < self.algo <= 3:
return "Reed-Solomon with polynomials in Galois field of characteristic %i (2^%i) with generator=%s, prime poly=%s and first consecutive root=%s." % (self.field_charac, self.c_exp, self.gen_nb, hex(self.prim), self.fcr)
elif self.algo == 4:
return "Reed-Solomon with polynomials in Galois field of characteristic %i (2^%i) under US FAA ADSB UAT RS FEC standard with generator=%s, prime poly=%s and first consecutive root=%s." % (self.field_charac, self.c_exp, self.gen_nb, hex(self.prim), self.fcr)
else:
return "No description for this ECC algorithm." |
python | def parse(self, raise_parsing_errors=True):
"""
Process the file content.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'Number A', u'Array A', u'String A', u'Date A', u'Boolean A', u'Data A']
:param raise_parsing_errors: Raise parsing errors.
:type raise_parsing_errors: bool
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Reading elements from: '{0}'.".format(self.path))
element_tree_parser = ElementTree.iterparse(self.path)
self.__parsing_errors = []
for action, element in element_tree_parser:
unmarshal = self.__unserializers.get(element.tag)
if unmarshal:
data = unmarshal(element)
element.clear()
element.text = data
elif element.tag != "plist":
self.__parsing_errors.append(foundations.exceptions.FileStructureParsingError(
"Unknown element: {0}".format(element.tag)))
if self.__parsing_errors:
if raise_parsing_errors:
raise foundations.exceptions.FileStructureParsingError(
"{0} | '{1}' structure is invalid, parsing exceptions occured!".format(self.__class__.__name__,
self.path))
else:
self.__elements = foundations.common.get_first_item(element_tree_parser.root).text
return True |
java | public void activateOptions() {
if (!isActive()) {
// shutdown();
rThread = new Thread(this);
rThread.setDaemon(true);
rThread.start();
if (advertiseViaMulticastDNS) {
zeroConf = new ZeroConfSupport(ZONE, port, getName());
zeroConf.advertise();
}
active = true;
}
} |
java | protected String handleJavaType(String typeStr, ResultSetMetaData rsmd, int column) throws SQLException {
// 当前实现只处理 Oracle
if ( ! dialect.isOracle() ) {
return typeStr;
}
// 默认实现只处理 BigDecimal 类型
if ("java.math.BigDecimal".equals(typeStr)) {
int scale = rsmd.getScale(column); // 小数点右边的位数,值为 0 表示整数
int precision = rsmd.getPrecision(column); // 最大精度
if (scale == 0) {
if (precision <= 9) {
typeStr = "java.lang.Integer";
} else if (precision <= 18) {
typeStr = "java.lang.Long";
} else {
typeStr = "java.math.BigDecimal";
}
} else {
// 非整数都采用 BigDecimal 类型,需要转成 double 的可以覆盖并改写下面的代码
typeStr = "java.math.BigDecimal";
}
}
return typeStr;
} |
python | def learnObject(self,
objectDescription,
randomLocation=False,
useNoise=False,
noisyTrainingTime=1):
"""
Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location representation in the location
layer. Move the sensor over the object, updating the location representation
through path integration. At each point on the object, form reciprocal
connections between the represention of the location and the representation
of the sensory input.
@param objectDescription (dict)
For example:
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "B"}]}
@return locationsAreUnique (bool)
True if this object was assigned a unique set of locations. False if a
location on this object has the same location representation as another
location somewhere else.
"""
self.reset()
self.column.activateRandomLocation()
locationsAreUnique = True
if randomLocation or useNoise:
numIters = noisyTrainingTime
else:
numIters = 1
for i in xrange(numIters):
for iFeature, feature in enumerate(objectDescription["features"]):
self._move(feature, randomLocation=randomLocation, useNoise=useNoise)
featureSDR = self.features[feature["name"]]
self._sense(featureSDR, learn=True, waitForSettle=False)
locationRepresentation = self.column.getSensoryAssociatedLocationRepresentation()
self.locationRepresentations[(objectDescription["name"],
iFeature)].append(locationRepresentation)
self.inputRepresentations[(objectDescription["name"],
iFeature, feature["name"])] = (
self.column.L4.getWinnerCells())
locationTuple = tuple(locationRepresentation)
locationsAreUnique = (locationsAreUnique and
locationTuple not in self.representationSet)
self.representationSet.add(tuple(locationRepresentation))
self.learnedObjects.append(objectDescription)
return locationsAreUnique |
java | public static Response get(String url) throws URISyntaxException, HttpException {
return send(new HttpGet(url), null, null);
} |
java | static final void resize(final WritableMemory mem, final int preambleLongs,
final int srcLgArrLongs, final int tgtLgArrLongs) {
//Note: This copies the Memory data onto the heap and then at the end copies the result
// back to Memory. Even if we tried to do this directly into Memory it would require pre-clearing,
// and the internal loops would be slower. The bulk copies are performed at a low level and
// are quite fast. Measurements reveal that we are not paying much of a penalty.
//Preamble stays in place
final int preBytes = preambleLongs << 3;
//Bulk copy source to on-heap buffer
final int srcHTLen = 1 << srcLgArrLongs; //current value
final long[] srcHTArr = new long[srcHTLen]; //on-heap src buffer
mem.getLongArray(preBytes, srcHTArr, 0, srcHTLen);
//Create destination on-heap buffer
final int dstHTLen = 1 << tgtLgArrLongs;
final long[] dstHTArr = new long[dstHTLen]; //on-heap dst buffer
//Rebuild hash table in destination buffer
final long thetaLong = extractThetaLong(mem);
HashOperations.hashArrayInsert(srcHTArr, dstHTArr, tgtLgArrLongs, thetaLong);
//Bulk copy to destination memory
mem.putLongArray(preBytes, dstHTArr, 0, dstHTLen); //put it back, no need to clear
insertLgArrLongs(mem, tgtLgArrLongs); //update in mem
} |
java | public static DeviceGroupDeleteDeviceResult deviceGroupDeleteDevice(
String accessToken, DeviceGroupDeleteDevice deviceGroupDeleteDevice) {
return deviceGroupDeleteDevice(accessToken,
JsonUtil.toJSONString(deviceGroupDeleteDevice));
} |
python | def get_dialog_state(handler_input):
# type: (HandlerInput) -> Optional[DialogState]
"""Return the dialog state enum from the intent request.
The method retrieves the `dialogState` from the intent request, if
the skill's interaction model includes a dialog model. This can be
used to determine the current status of user conversation and return
the appropriate dialog directives if the conversation is not yet complete.
More information on dialog management can be found here :
https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html
The method returns a ``None`` if there is no dialog model added or
if the intent doesn't have dialog management. The method raises a
:py:class:`TypeError` if the input is not an `IntentRequest`.
:param handler_input: The handler input instance that is generally
passed in the sdk's request and exception components.
:type handler_input: ask_sdk_core.handler_input.HandlerInput
:return: State of the dialog model from the intent request.
:rtype: Optional[ask_sdk_model.dialog_state.DialogState]
:raises: TypeError if the input is not an IntentRequest
"""
request = handler_input.request_envelope.request
if isinstance(request, IntentRequest):
return request.dialog_state
raise TypeError("The provided request is not an IntentRequest") |
python | def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function."""
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
cache = caches[cache_name]
result = cache.get(cache_key)
if result is None:
result = f(*args, **kw)
cache.set(cache_key, result, timeout)
return result
def invalidate():
cache = caches[cache_name]
cache.delete(cache_key)
wrapper.invalidate = invalidate
return wrapper
return decorator |
python | def list_services(self, stack):
"""获得服务列表
列出指定名称的服务组内所有的服务, 返回一组详细的服务信息。
Args:
- stack: 服务所属的服务组名称
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回服务信息列表[<ervice1>, <service2>, ...],失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息
"""
url = '{0}/v3/stacks/{1}/services'.format(self.host, stack)
return self.__get(url) |
python | def is_op(call, op):
"""
:param call: The specific operator instance (a method call)
:param op: The the operator we are testing against
:return: isinstance(call, op), but faster
"""
try:
return call.id == op.id
except Exception as e:
return False |
java | public boolean isAncestorOf(AlluxioURI alluxioURI) throws InvalidPathException {
// To be an ancestor of another URI, authority and scheme must match
if (!Objects.equals(getAuthority(), alluxioURI.getAuthority())) {
return false;
}
if (!Objects.equals(getScheme(), alluxioURI.getScheme())) {
return false;
}
return PathUtils.hasPrefix(PathUtils.normalizePath(alluxioURI.getPath(), SEPARATOR),
PathUtils.normalizePath(getPath(), SEPARATOR));
} |
java | @NonNull
public static ResolvedTypeWithMembers resolveMembers(@NonNull ResolvedType mainType)
{
return memberResolver.resolve(mainType, null, null);
} |
java | public static int earliestIndexOfAny(String s, Iterable<String> probes, int from) {
int earliestIdx = -1;
for (final String probe : probes) {
final int probeIdx = s.indexOf(probe, from);
// if we found something for this probe
if (probeIdx >= 0
// and either we haven't found anything else yet or
// this is earlier than anything we've found yet
&& (earliestIdx == -1 || probeIdx < earliestIdx)) {
// then this is our new earliest match
earliestIdx = probeIdx;
}
}
return earliestIdx;
} |
java | public static <W extends Comparable<W>, S extends GenericSemiring<W>> UnionSemiring<W, S> makeForNaturalOrdering(
S weightSemiring) {
return makeForOrdering(weightSemiring, Ordering.natural(), defaultMerge());
} |
java | public static <T> Collection<T> takeWhile(Iterable<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure condition) {
Collection<T> result = createSimilarCollection(self);
addAll(result, takeWhile(self.iterator(), condition));
return result;
} |
java | public void seekToRecord(long recordNumber) throws IOException {
if (currentRecordNumber == recordNumber)
return;
long skip;
if (recordNumber < fileIndex.getStartingRecordNumber()) {
if (currentRecordNumber < recordNumber)
skip = recordNumber - currentRecordNumber;
else {
skip = recordNumber;
seek0(0);
}
} else if (recordNumber > fileIndex.getLastRecordNumber()) {
if (currentRecordNumber < recordNumber)
skip = recordNumber - currentRecordNumber;
else {
long record = fileIndex.getLastRecordNumber();
skip = recordNumber - record;
seek0(fileIndex.getNearestPosition(record));
}
} else if (recordNumber > currentRecordNumber && recordNumber - currentRecordNumber < fileIndex.getStep()) {
skip = recordNumber - currentRecordNumber;
} else {
seek0(fileIndex.getNearestPosition(recordNumber));
skip = recordNumber - fileIndex.getNearestRecordNumber(recordNumber);
}
for (; skip > 0; --skip)
skip();
currentRecordNumber = recordNumber;
} |
java | public static StackTraceElement getMyStackTraceElement () {
StackTraceElement myStackTraceElement = null;
StackTraceElement[] stackTraceElements = Thread.currentThread ().getStackTrace ();
if (stackTraceElements != null) {
if (stackTraceElements.length > 2) {
myStackTraceElement = stackTraceElements[2];
}
}
return myStackTraceElement;
} |
java | public static MozuUrl createPackageUrl(String responseFields, String returnId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{returnId}/packages?responseFields={responseFields}");
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("returnId", returnId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} |
java | private void processCustomizeOptions(TypeElement component, MethodSpec.Builder initBuilder,
List<CodeBlock> staticInitParameters) {
getComponentCustomizeOptions(elements,
component).forEach(customizeOptions -> this.processCustomizeOptions(customizeOptions,
initBuilder,
staticInitParameters));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.