language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | private Entity processInteraction(Interaction interaction, Set<String> avail,
Provenance pro, boolean isComplex)
{
Entity bpInteraction = null; //interaction or complex
boolean isGeneticInteraction = false;
// get interaction name/short name
String name = null;
String shortName = null;
if (interaction.hasNames()) {
Names names = interaction.getNames();
name = (names.hasFullName()) ? names.getFullName() : "";
shortName = (names.hasShortLabel()) ? names.getShortLabel() : "";
}
final Set<InteractionVocabulary> interactionVocabularies = new HashSet<InteractionVocabulary>();
if (interaction.hasInteractionTypes()) {
for(CvType interactionType : interaction.getInteractionTypes()) {
//generate InteractionVocabulary and set interactionType
InteractionVocabulary cv = findOrCreateControlledVocabulary(interactionType, InteractionVocabulary.class);
if(cv != null)
interactionVocabularies.add(cv);
}
}
// using experiment descriptions, create Evidence objects
// (yet, no experimental forms/roles/entities are created here)
Set<Evidence> bpEvidences = new HashSet<Evidence>();
if (interaction.hasExperiments()) {
bpEvidences = createBiopaxEvidences(interaction);
}
//A hack for e.g. IntAct or BIND "gene-protein" interactions (ChIp and EMSA experiments)
// where the interactor type should probably not be 'gene' (but 'dna' or 'rna')
Set<String> participantTypes = new HashSet<String>();
for(Participant p : interaction.getParticipants()) {
if(p.hasInteractor()) {
String type = getName(p.getInteractor().getInteractorType().getNames());
if(type==null) type = "protein"; //default type (if unspecified)
participantTypes.add(type.toLowerCase());
} else if (p.hasInteraction()) {
participantTypes.add("complex"); //hierarchical complex build up
} // else? (impossible!)
}
// If there are both genes and physical entities present, let's
// replace 'gene' with 'dna' (esp. true for "ch-ip", "emsa" experiments);
// (this won't affect experimental form entities if experimentalInteractor element exists)
if(participantTypes.size() > 1 && participantTypes.contains("gene")) {
//TODO a better criteria to reliably detect whether 'gene' interactor type actually means Dna/DnaRegion or Rna/RnaRegion, or indeed Gene)
LOG.warn("Interaction: " + interaction.getId() + ", name(s): " + shortName + " " + name
+ "; has both 'gene' and physical entity type participants: " + participantTypes
+ "; so we'll replace 'gene' with 'dna' (a quick fix)");
for(Participant p : interaction.getParticipants()) {
if(p.hasInteractor() && p.getInteractor().getInteractorType().hasNames()) {
String type = getName(p.getInteractor().getInteractorType().getNames());
if("gene".equalsIgnoreCase(type)) {
p.getInteractor().getInteractorType().getNames().setShortLabel("dna");
}
}
}
}
// interate through the psi-mi participants, create corresp. biopax entities
final Set<Entity> bpParticipants = new HashSet<Entity>();
for (Participant participant : interaction.getParticipants()) {
// get paxtools physical entity participant and add to participant list
// (this also adds experimental evidence and forms)
Entity bpParticipant = createBiopaxEntity(participant, avail, pro);
if (bpParticipant != null) {
if(!bpParticipants.contains(bpParticipant))
bpParticipants.add(bpParticipant);
}
}
// Process interaction attributes.
final Set<String> comments = new HashSet<String>();
// Set GeneticInteraction flag.
// As of BioGRID v3.1.72 (at least), genetic interaction code can reside
// as an attribute of the Interaction via "BioGRID Evidence Code" key
if (interaction.hasAttributes()) {
for (Attribute attribute : interaction.getAttributes()) {
String key = attribute.getName(); //may be reset below
String value = (attribute.hasValue()) ? attribute.getValue() : "";
if(key.equalsIgnoreCase(BIOGRID_EVIDENCE_CODE)
&& GENETIC_INTERACTIONS.contains(value))
{
isGeneticInteraction = true; // important!
}
comments.add(key + ":" + value);
}
}
// or, if all participants are 'gene' type, make a biopax GeneticInteraction
if(participantTypes.size() == 1 && participantTypes.contains("gene")) {
isGeneticInteraction = true;
}
//or, check another genetic interaction flag (criteria)
if(!isGeneticInteraction) {
isGeneticInteraction = isGeneticInteraction(bpEvidences);
}
if ((isComplex || forceInteractionToComplex) && !isGeneticInteraction) {
bpInteraction = createComplex(bpParticipants, interaction.getImexId(), interaction.getId());
} else if(isGeneticInteraction) {
bpInteraction = createGeneticInteraction(bpParticipants, interactionVocabularies,
interaction.getImexId(), interaction.getId()
);
} else {
bpInteraction = createMolecularInteraction(bpParticipants, interactionVocabularies,
interaction.getImexId(), interaction.getId());
}
for(String c : comments) {
bpInteraction.addComment(c);
}
//add evidences to the interaction/complex bpEntity
for (Evidence evidence : bpEvidences) {
bpInteraction.addEvidence(evidence);
//TODO: shall we add IntAct "figure legend" comment to the evidences as well?
}
addAvailabilityAndProvenance(bpInteraction, avail, pro);
if (name != null)
bpInteraction.addName(name);
if (shortName != null) {
if(shortName.length()<51)
bpInteraction.setDisplayName(shortName);
else
bpInteraction.addName(shortName);
}
// add xrefs
Set<Xref> bpXrefs = new HashSet<Xref>();
if (interaction.hasXref()) {
bpXrefs.addAll(getXrefs(interaction.getXref()));
}
for (Xref bpXref : bpXrefs) {
bpInteraction.addXref(bpXref);
}
return bpInteraction;
} |
java | public int fieldChanged(boolean bDisplayOption, int iMoveMode)
{
int iErrorCode = this.setupGridOrder();
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
return super.fieldChanged(bDisplayOption, iMoveMode);
} |
java | public static MultipleAlignmentJmol display(MultipleAlignment multAln)
throws StructureException {
List<Atom[]> rotatedAtoms = MultipleAlignmentDisplay.getRotatedAtoms(multAln);
MultipleAlignmentJmol jmol =
new MultipleAlignmentJmol(multAln, rotatedAtoms);
jmol.setTitle(jmol.getStructure().getPDBHeader().getTitle());
return jmol;
} |
python | def get_vault_lookup_session(self):
"""Gets the OsidSession associated with the vault lookup service.
return: (osid.authorization.VaultLookupSession) - a
``VaultLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_vault_lookup() is false``
*compliance: optional -- This method must be implemented if
``supports_vault_lookup()`` is true.*
"""
if not self.supports_vault_lookup():
raise errors.Unimplemented()
# pylint: disable=no-member
return sessions.VaultLookupSession(runtime=self._runtime) |
python | def get_cookie_jar(self):
"""Returns our cookie jar."""
cookie_file = self._get_cookie_file()
cookie_jar = LWPCookieJar(cookie_file)
if os.path.exists(cookie_file):
cookie_jar.load()
else:
safe_mkdir_for(cookie_file)
# Save an empty cookie jar so we can change the file perms on it before writing data to it.
with self._lock:
cookie_jar.save()
os.chmod(cookie_file, 0o600)
return cookie_jar |
python | def check_handle_syntax(string):
'''
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'prefix/suffix'
try:
arr = string.split('/')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None', expected_syntax=expected)
if len(arr) < 2:
msg = 'No slash'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[0]) == 0:
msg = 'Empty prefix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[1]) == 0:
msg = 'Empty suffix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if ':' in string:
check_handle_syntax_with_index(string, base_already_checked=True)
return True |
python | def _get_aggregated_object(self, composite_key):
""" method talks with the map of instances of aggregated objects
:param composite_key presents tuple, comprising of domain_name and timeperiod"""
if composite_key not in self.aggregated_objects:
self.aggregated_objects[composite_key] = self._init_sink_object(composite_key)
return self.aggregated_objects[composite_key] |
java | public CollectionAssert allElementsMatch(String regex) {
isNotNull();
isNotEmpty();
for (Object anActual : this.actual) {
if (anActual == null) {
failWithMessageRelatedToRegex(regex, anActual);
}
String value = anActual.toString();
if (!value.matches(regex)) {
failWithMessageRelatedToRegex(regex, value);
}
}
return this;
} |
java | private void outputReportFiles(List<String> reportNames, File reportDirectory, TestResult testResult,
boolean tranSummary) throws IOException {
if (reportNames.isEmpty()) {
return;
}
String title = (tranSummary) ? "Transaction Summary" : "Performance Report";
String htmlFileName = (tranSummary) ? (TRANSACTION_REPORT_NAME + ".html") : "HTML.html";
File htmlIndexFile = new File(reportDirectory, INDEX_HTML_NAME);
BufferedWriter writer = new BufferedWriter(new FileWriter(htmlIndexFile));
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>%n");
writer.write("<HTML><HEAD>%n");
writer.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">%n");
writer.write(String.format("<TITLE>%s</TITLE>%n", title));
writer.write("</HEAD>%n");
writer.write("<BODY>%n");
writer.write(
"<table style=\"font-size:15px;width:100%;max-width:100%;border-left:1px solid #DDD;border-right:1px " +
"solid #DDD;border-bottom:1px solid #DDD;\">%n");
writer.write(
"<tr style=\"background-color: #F1F1F1;\"><th style=\"padding:8px;line-height:1.42857;" +
"vertical-align:top;border-top:1px solid #DDD;\">Name</th></tr>%n");
boolean rolling = true;
for (String report : reportNames) {
if (rolling) {
writer.write(String.format(
"<tr style=\"background-color: #FFF;\"><td style=\"padding:8px;line-height:1.42857;" +
"vertical-align:top;border-top:1px solid #DDD;" +
"\"><a href=\"./%s/%s\">%s</a></td></tr>%n",
report, htmlFileName, report));
rolling = false;
} else {
writer.write(String.format(
"<tr style=\"background-color: #F1F1F1;\"><td style=\"padding:8px;line-height:1.42857;" +
"vertical-align:top;border-top:1px solid #DDD;" +
"\"><a href=\"./%s/%s\">%s</a></td></tr>%n",
report, htmlFileName, report));
rolling = true;
}
}
writer.write("</table>%n");
writer.write("</BODY>%n");
writer.flush();
writer.close();
File indexFile = new File(reportDirectory, REPORT_INDEX_NAME);
writer = new BufferedWriter(new FileWriter(indexFile));
Iterator<SuiteResult> resultIterator = null;
if ((testResult != null) && (!testResult.getSuites().isEmpty())) {
resultIterator = testResult.getSuites().iterator();//get the first
}
for (String report : reportNames) {
SuiteResult suitResult = null;
if ((resultIterator != null) && resultIterator.hasNext()) {
suitResult = resultIterator.next();
}
if (suitResult == null) {
writer.write(report + "\t##\t##\t##%n");
} else {
int iDuration = (int) suitResult.getDuration();
StringBuilder bld = new StringBuilder();
String duration = "";
if ((iDuration / SECS_IN_DAY) > 0) {
bld.append(String.format("%dday ", iDuration / SECS_IN_DAY));
iDuration = iDuration % SECS_IN_DAY;
}
if ((iDuration / SECS_IN_HOUR) > 0) {
bld.append(String.format("%02dhr ", iDuration / SECS_IN_HOUR));
iDuration = iDuration % SECS_IN_HOUR;
} else if (!duration.isEmpty()) {
bld.append("00hr ");
}
if ((iDuration / SECS_IN_MINUTE) > 0) {
bld.append(String.format("%02dmin ", iDuration / SECS_IN_MINUTE));
iDuration = iDuration % SECS_IN_MINUTE;
} else if (!duration.isEmpty()) {
bld.append("00min ");
}
bld.append(String.format("%02dsec", iDuration));
duration = bld.toString();
int iPassCount = 0;
int iFailCount = 0;
for (Iterator i = suitResult.getCases().iterator(); i.hasNext(); ) {
CaseResult caseResult = (CaseResult) i.next();
iPassCount += caseResult.getPassCount();
iFailCount += caseResult.getFailCount();
}
writer.write(
String.format("%s\t%s\t%d\t%d%n",
report,
duration,
iPassCount,
iFailCount));
}
}
writer.flush();
writer.close();
} |
python | def on_view_not_found(
self,
environ: Dict[str, Any],
start_response: Callable) -> Iterable[bytes]: # pragma: nocover
""" called when view is not found"""
raise NotImplementedError() |
java | private Set<Impact> collectResult(
List<Impact> singleEntityChanges,
List<Impact> wholeRepoActions,
Set<String> dependentEntityIds) {
Set<String> wholeRepoIds =
union(
wholeRepoActions.stream().map(Impact::getEntityTypeId).collect(toImmutableSet()),
dependentEntityIds);
ImmutableSet.Builder<Impact> result = ImmutableSet.builder();
result.addAll(wholeRepoActions);
dependentEntityIds.stream().map(Impact::createWholeRepositoryImpact).forEach(result::add);
singleEntityChanges
.stream()
.filter(action -> !wholeRepoIds.contains(action.getEntityTypeId()))
.forEach(result::add);
return result.build();
} |
python | def maybe_submit_measurement(self):
"""Check for configured instrumentation backends and if found, submit
the message measurement info.
"""
if self.statsd:
self.submit_statsd_measurements()
if self.influxdb:
self.submit_influxdb_measurement() |
python | def _load_stream_py3(dc, chunks):
"""
Given a decompression stream and chunks, yield chunks of
decompressed data until the compression window ends.
"""
while not dc.eof:
res = dc.decompress(dc.unconsumed_tail + next(chunks))
yield res |
python | def uniform(self, a: float, b: float, precision: int = 15) -> float:
"""Get a random number in the range [a, b) or [a, b] depending on rounding.
:param a: Minimum value.
:param b: Maximum value.
:param precision: Round a number to a given
precision in decimal digits, default is 15.
"""
return round(a + (b - a) * self.random(), precision) |
java | protected List<BubbleGlyph> getAndExpireBubbles (Name speaker)
{
int num = _bubbles.size();
// first, get all the old bubbles belonging to the user
List<BubbleGlyph> oldbubs = Lists.newArrayList();
if (speaker != null) {
for (int ii=0; ii < num; ii++) {
BubbleGlyph bub = _bubbles.get(ii);
if (bub.isSpeaker(speaker)) {
oldbubs.add(bub);
}
}
}
// see if we need to expire this user's oldest bubble
if (oldbubs.size() >= MAX_BUBBLES_PER_USER) {
BubbleGlyph bub = oldbubs.remove(0);
_bubbles.remove(bub);
_target.abortAnimation(bub);
// or some other old bubble
} else if (num >= MAX_BUBBLES) {
_target.abortAnimation(_bubbles.remove(0));
}
// return the speaker's old bubbles
return oldbubs;
} |
python | def _prepare_request_json(self, kwargs):
"""Prepare request args for sending to device as JSON."""
# Check for python keywords in dict
kwargs = self._check_for_python_keywords(kwargs)
# Check for the key 'check' in kwargs
if 'check' in kwargs:
od = OrderedDict()
od['check'] = kwargs['check']
kwargs.pop('check')
od.update(kwargs)
return od
return kwargs |
java | public String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException {
String result;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey =
new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = new String(Base64.encodeBase64(rawHmac));
}
catch (Exception e) {
throw new SignatureException("Failed to generate HMAC", e);
}
return result;
} |
python | def resnet50(pretrained=False, **kwargs):
"""Constructs a ResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model |
python | def load_path_with_default(self, path, default_constructor):
'''
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
'''
try:
imported_obj = self.load_path(path)
except (ImportError, ConfigurationError):
imported_obj = default_constructor(path)
else:
# Ugly but seemingly expedient way to check a module was an
# namespace type module
if (isinstance(imported_obj, ModuleType) and
imported_obj.__spec__.origin == 'namespace'):
imported_obj = default_constructor(path)
return imported_obj |
java | public static double hypergeometric(int k, int n, int Kp, int Np) {
if(k<0 || n<0 || Kp<0 || Np<0) {
throw new IllegalArgumentException("All the parameters must be positive.");
}
Kp = Math.max(k, Kp);
Np = Math.max(n, Np);
/*
//slow!
$probability=StatsUtilities::combination($Kp,$k)*StatsUtilities::combination($Np-$Kp,$n-$k)/StatsUtilities::combination($Np,$n);
*/
//fast and can handle large numbers
//Cdf(k)-Cdf(k-1)
double probability = approxHypergeometricCdf(k,n,Kp,Np);
if(k>0) {
probability -= approxHypergeometricCdf(k-1,n,Kp,Np);
}
return probability;
} |
java | @Override
public TextColumn unique() {
List<String> strings = new ArrayList<>(asSet());
return TextColumn.create(name() + " Unique values", strings);
} |
java | public ApiResponse<List<MarketPricesResponse>> getMarketsPricesWithHttpInfo(String datasource, String ifNoneMatch)
throws ApiException {
com.squareup.okhttp.Call call = getMarketsPricesValidateBeforeCall(datasource, ifNoneMatch, null);
Type localVarReturnType = new TypeToken<List<MarketPricesResponse>>() {
}.getType();
return apiClient.execute(call, localVarReturnType);
} |
python | def process(dest, rulefiles):
"""process rules"""
deploy = False
while not rulefiles.empty():
rulefile = rulefiles.get()
base = os.path.basename(rulefile)
dest = os.path.join(dest, base)
if os.path.exists(dest):
# check if older
oldtime = os.stat(rulefile).st_mtime
newtime = os.stat(dest).st_mtime
if oldtime > newtime:
deploy = True
deploy_file(rulefile, dest)
else:
deploy = True
deploy_file(rulefile, dest)
return deploy |
java | public boolean isEditable(final int row, final int column) {
if (isEditable(column)) {
final int actualIndex = getTableColumn(column).getIndex();
final JKTableRecord record = getRecord(row);
return record.isColumnEnabled(actualIndex);
}
return false;
} |
java | private Instance getExistingKey(final String _key)
{
Instance ret = null;
try {
final QueryBuilder queryBldr = new QueryBuilder(Type.get(DBPropertiesUpdate.TYPE_PROPERTIES));
queryBldr.addWhereAttrEqValue("Key", _key);
queryBldr.addWhereAttrEqValue("BundleID", this.bundleInstance);
final InstanceQuery query = queryBldr.getQuery();
query.executeWithoutAccessCheck();
if (query.next()) {
ret = query.getCurrentValue();
}
} catch (final EFapsException e) {
DBPropertiesUpdate.LOG.error("getExisting()", e);
}
return ret;
} |
python | def guess_autoescape(self, template_name):
"""Given a template Name I will gues using its
extension if we should autoscape or not.
Default autoscaped extensions: ('html', 'xhtml', 'htm', 'xml')
"""
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in ('html', 'xhtml', 'htm', 'xml') |
java | public KeySnapshot filter(KVFilter kvf){
ArrayList<KeyInfo> res = new ArrayList<>();
for(KeyInfo kinfo: _keyInfos)
if(kvf.filter(kinfo))res.add(kinfo);
return new KeySnapshot(res.toArray(new KeyInfo[res.size()]));
} |
java | public static KieServicesConfiguration newJMSConfiguration( ConnectionFactory connectionFactory, Queue requestQueue, Queue responseQueue) {
return new KieServicesConfigurationImpl( connectionFactory, requestQueue, responseQueue );
} |
python | def _pool(self, pool_name, pool_function, k_height, k_width, d_height,
d_width, mode, input_layer, num_channels_in):
"""Construct a pooling layer."""
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = num_channels_in
name = pool_name + str(self.counts[pool_name])
self.counts[pool_name] += 1
if self.use_tf_layers:
pool = pool_function(
input_layer, [k_height, k_width], [d_height, d_width],
padding=mode,
data_format=self.channel_pos,
name=name)
else:
if self.data_format == "NHWC":
ksize = [1, k_height, k_width, 1]
strides = [1, d_height, d_width, 1]
else:
ksize = [1, 1, k_height, k_width]
strides = [1, 1, d_height, d_width]
pool = tf.nn.max_pool(
input_layer,
ksize,
strides,
padding=mode,
data_format=self.data_format,
name=name)
self.top_layer = pool
return pool |
python | def is_disabled_action(view):
"""
Checks whether Link action is disabled.
"""
if not isinstance(view, core_views.ActionsViewSet):
return False
action = getattr(view, 'action', None)
return action in view.disabled_actions if action is not None else False |
java | public ByteBuffer getScaleKeyBuffer() {
ByteBuffer buf = m_scaleKeys.duplicate();
buf.order(ByteOrder.nativeOrder());
return buf;
} |
java | @Override
public void renderBranch( PositionedText target, double x, double y,
Size size, Collection<Diagram.Figure> branches, boolean forward )
{
throw new UnsupportedOperationException( "not implemented" );
} |
java | public GVRAndroidResource addResource(GVRAndroidResource resource)
{
String fileName = resource.getResourcePath();
GVRAndroidResource resourceValue = resourceMap.get(fileName);
if (resourceValue != null)
{
return resourceValue;
}
// Only put the resourceKey into the map for the first time, later put
// will simply return the first resource
resourceValue = resourceMap.putIfAbsent(fileName, resource);
return resourceValue == null ? resource : resourceValue;
} |
python | def _add_exac(self, variant_obj, gemini_variant):
"""Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow)
"""
exac = gemini_variant['aaf_exac_all']
if exac:
exac = float(exac)
variant_obj.add_frequency('ExAC', exac)
logger.debug("Updating ExAC to: {0}".format(
exac)) |
java | private TrackType findTrackType() {
TrackType result = TRACK_TYPE_MAP.get(packetBytes[42]);
if (result == null) {
return TrackType.UNKNOWN;
}
return result;
} |
python | def reset(self):
"""Reset the widget, and clear the scene."""
self.minimum = None
self.maximum = None
self.start_time = None # datetime, absolute start time
self.idx_current = None
self.idx_markers = []
self.idx_annot = []
if self.scene is not None:
self.scene.clear()
self.scene = None |
java | public static SQLiteConnectionPool open(com.couchbase.lite.internal.database.sqlite.SQLiteDatabaseConfiguration configuration,
com.couchbase.lite.internal.database.sqlite.SQLiteConnectionListener connectionListener) {
if (configuration == null) {
throw new IllegalArgumentException("configuration must not be null.");
}
// Create the pool.
SQLiteConnectionPool pool = new SQLiteConnectionPool(configuration, connectionListener);
pool.open(); // might throw
return pool;
} |
python | def data2md(table):
"""
Creates a markdown table. The first row will be headers.
Parameters
----------
table : list of lists of str
A list of rows containing strings. If any of these strings
consist of multiple lines, they will be converted to single line
because markdown tables do not support multiline cells.
Returns
-------
str
The markdown formatted string
Example
-------
>>> table_data = [
... ["Species", "Coolness"],
... ["Dog", "Awesome"],
... ["Cat", "Meh"],
... ]
>>> print(data2md(table_data))
| Species | Coolness |
|---------|----------|
| Dog | Awesome |
| Cat | Meh |
"""
table = copy.deepcopy(table)
table = ensure_table_strings(table)
table = multis_2_mono(table)
table = add_cushions(table)
widths = []
for column in range(len(table[0])):
widths.append(get_column_width(column, table))
output = '|'
for i in range(len(table[0])):
output = ''.join(
[output, center_line(widths[i], table[0][i]), '|'])
output = output + '\n|'
for i in range(len(table[0])):
output = ''.join([
output, center_line(widths[i], "-" * widths[i]), '|'])
output = output + '\n|'
for row in range(1, len(table)):
for column in range(len(table[row])):
output = ''.join(
[output, center_line(widths[column],
table[row][column]), '|'])
output = output + '\n|'
split = output.split('\n')
split.pop()
table_string = '\n'.join(split)
return table_string |
python | def lagrange_interpolate(x, y, precision=250, **kwargs):
"""
Interpolate x, y using Lagrange polynomials
https://en.wikipedia.org/wiki/Lagrange_polynomial
"""
n = len(x) - 1
delta_x = [x2 - x1 for x1, x2 in zip(x, x[1:])]
for i in range(n + 1):
yield x[i], y[i]
if i == n or delta_x[i] == 0:
continue
for s in range(1, precision):
X = x[i] + s * delta_x[i] / precision
s = 0
for k in range(n + 1):
p = 1
for m in range(n + 1):
if m == k:
continue
if x[k] - x[m]:
p *= (X - x[m]) / (x[k] - x[m])
s += y[k] * p
yield X, s |
python | def read_pipette_id(self, mount) -> Optional[str]:
'''
Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None
'''
res: Optional[str] = None
if self.simulating:
res = '1234567890'
else:
try:
res = self._read_from_pipette(
GCODES['READ_INSTRUMENT_ID'], mount)
except UnicodeDecodeError:
log.exception("Failed to decode pipette ID string:")
res = None
return res |
java | public <T2, R> ValueTransformer<W,R> zip(Iterable<? extends T2> iterable,
BiFunction<? super T, ? super T2, ? extends R> fn) {
return this.unitAnyM(this.transformerStream().map(v->v.zip(iterable,fn)));
} |
python | def base_create_agent_configurations(cls) -> ConfigObject:
"""
This is used when initializing agent config via builder pattern.
It also calls `create_agent_configurations` that can be used by BaseAgent subclasses for custom configs.
:return: Returns an instance of a ConfigObject object.
"""
config = ConfigObject()
location_config = config.add_header_name(BOT_CONFIG_MODULE_HEADER)
location_config.add_value(LOOKS_CONFIG_KEY, str,
description='Path to loadout config from runner')
location_config.add_value(PYTHON_FILE_KEY, str,
description="Bot's python file.\nOnly need this if RLBot controlled")
location_config.add_value(BOT_NAME_KEY, str, default='nameless',
description='The name that will be displayed in game')
details_config = config.add_header_name(BOT_CONFIG_DETAILS_HEADER)
details_config.add_value('developer', str, description="Name of the bot's creator/developer")
details_config.add_value('description', str, description="Short description of the bot")
details_config.add_value('fun_fact', str, description="Fun fact about the bot")
details_config.add_value('github', str, description="Link to github repository")
details_config.add_value('language', str, description="Programming language")
cls.create_agent_configurations(config)
return config |
java | boolean expectAutoboxesToIterable(Node n, JSType type, String msg) {
// Note: we don't just use JSType.autobox() here because that removes null and undefined.
// We want to keep null and undefined around.
if (type.isUnionType()) {
for (JSType alt : type.toMaybeUnionType().getAlternates()) {
alt = alt.isBoxableScalar() ? alt.autoboxesTo() : alt;
if (!alt.isSubtypeOf(getNativeType(ITERABLE_TYPE))) {
mismatch(n, msg, type, ITERABLE_TYPE);
return false;
}
}
} else {
JSType autoboxedType = type.isBoxableScalar() ? type.autoboxesTo() : type;
if (!autoboxedType.isSubtypeOf(getNativeType(ITERABLE_TYPE))) {
mismatch(n, msg, type, ITERABLE_TYPE);
return false;
}
}
return true;
} |
python | def main():
""" Main function called from dynamic-dynamodb """
try:
if get_global_option('show_config'):
print json.dumps(config.get_configuration(), indent=2)
elif get_global_option('daemon'):
daemon = DynamicDynamoDBDaemon(
'{0}/dynamic-dynamodb.{1}.pid'.format(
get_global_option('pid_file_dir'),
get_global_option('instance')))
if get_global_option('daemon') == 'start':
logger.debug('Starting daemon')
try:
daemon.start()
logger.info('Daemon started')
except IOError as error:
logger.error('Could not create pid file: {0}'.format(error))
logger.error('Daemon not started')
elif get_global_option('daemon') == 'stop':
logger.debug('Stopping daemon')
daemon.stop()
logger.info('Daemon stopped')
sys.exit(0)
elif get_global_option('daemon') == 'restart':
logger.debug('Restarting daemon')
daemon.restart()
logger.info('Daemon restarted')
elif get_global_option('daemon') in ['foreground', 'fg']:
logger.debug('Starting daemon in foreground')
daemon.run()
logger.info('Daemon started in foreground')
else:
print(
'Valid options for --daemon are start, '
'stop, restart, and foreground')
sys.exit(1)
else:
if get_global_option('run_once'):
execute()
else:
while True:
execute()
except Exception as error:
logger.exception(error) |
java | public <T> Completes<Optional<T>> maybeActorOf(final Class<T> protocol, final Address address) {
return directoryScanner.maybeActorOf(protocol, address).andThen(proxy -> proxy);
} |
java | public QueryBuilder<T, ID> offset(Long startRow) throws SQLException {
if (databaseType.isOffsetSqlSupported()) {
offset = startRow;
return this;
} else {
throw new SQLException("Offset is not supported by this database");
}
} |
python | def unchunk(self):
"""
Reconstitute the chunked array back into a full ndarray.
Returns
-------
ndarray
"""
if self.padding != len(self.shape)*(0,):
shape = self.values.shape
arr = empty(shape, dtype=object)
for inds in product(*[arange(s) for s in shape]):
slices = []
for i, p, n in zip(inds, self.padding, shape):
start = None if (i == 0 or p == 0) else p
stop = None if (i == n-1 or p == 0) else -p
slices.append(slice(start, stop, None))
arr[inds] = self.values[inds][tuple(slices)]
else:
arr = self.values
return allstack(arr.tolist()) |
python | def escape(cls, s):
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv |
python | def rst_add_mathjax(content):
"""Adds mathjax script for reStructuredText"""
# .rst is the only valid extension for reStructuredText files
_, ext = os.path.splitext(os.path.basename(content.source_path))
if ext != '.rst':
return
# If math class is present in text, add the javascript
# note that RST hardwires mathjax to be class "math"
if 'class="math"' in content._content:
content._content += "<script type='text/javascript'>%s</script>" % rst_add_mathjax.mathjax_script |
python | def pvremove(devices, override=True):
'''
Remove a physical device being used as an LVM physical volume
override
Skip devices, if they are already not used as LVM physical volumes
CLI Examples:
.. code-block:: bash
salt mymachine lvm.pvremove /dev/sdb1,/dev/sdb2
'''
if isinstance(devices, six.string_types):
devices = devices.split(',')
cmd = ['pvremove', '-y']
for device in devices:
if pvdisplay(device):
cmd.append(device)
elif not override:
raise CommandExecutionError('{0} is not a physical volume'.format(device))
if not cmd[2:]:
# Nothing to do
return True
out = __salt__['cmd.run_all'](cmd, python_shell=False)
if out.get('retcode'):
raise CommandExecutionError(out.get('stderr'))
# Verify pvcremove was successful
for device in devices:
if pvdisplay(device, quiet=True):
raise CommandExecutionError('Device "{0}" was not affected.'.format(device))
return True |
python | def module_summary(self):
"""Count the malicious and suspicious sections, check for CVE description"""
suspicious = 0
malicious = 0
count = 0
cve = False
taxonomies = []
for section in self.results:
if section['submodule_section_content']['class'] == 'malicious':
malicious += 1
elif section['submodule_section_content']['class'] == 'suspicious':
suspicious += 1
if 'CVE' in section['submodule_section_content']['clsid_description']:
cve = True
count += 1
if malicious > 0:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'MaliciousRTFObjects', malicious))
if suspicious > 0:
taxonomies.append(self.build_taxonomy('suspicious', 'FileInfo', 'SuspiciousRTFObjects', suspicious))
if cve:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'PossibleCVEExploit', 'True'))
taxonomies.append(self.build_taxonomy('info', 'FileInfo', 'RTFObjects', count))
self.summary['taxonomies'] = taxonomies
return self.summary |
python | def copy_all(self, ctxt):
'''
copies all values into the current context from given context
:param ctxt:
'''
for key, value in ctxt.iteritems:
self.set_attribute(key, value) |
java | private AttributeAtom rewriteWithRelationVariable(Atom parentAtom){
if (parentAtom.isResource() && ((AttributeAtom) parentAtom).getRelationVariable().isReturned()) return rewriteWithRelationVariable();
return this;
} |
java | @Override
public void draw(Canvas c, Projection projection) {
final double zoomLevel = projection.getZoomLevel();
if (zoomLevel < minZoom) {
return;
}
final Rect rect = projection.getIntrinsicScreenRect();
int _screenWidth = rect.width();
int _screenHeight = rect.height();
boolean screenSizeChanged = _screenHeight!=screenHeight || _screenWidth != screenWidth;
screenHeight = _screenHeight;
screenWidth = _screenWidth;
final IGeoPoint center = projection.fromPixels(screenWidth / 2, screenHeight / 2, null);
if (zoomLevel != lastZoomLevel || center.getLatitude() != lastLatitude || screenSizeChanged) {
lastZoomLevel = zoomLevel;
lastLatitude = center.getLatitude();
rebuildBarPath(projection);
}
int offsetX = xOffset;
int offsetY = yOffset;
if (alignBottom) offsetY *=-1;
if (alignRight ) offsetX *=-1;
if (centred && latitudeBar)
offsetX += -latitudeBarRect.width() / 2;
if (centred && longitudeBar)
offsetY += -longitudeBarRect.height() / 2;
projection.save(c, false, true);
c.translate(offsetX, offsetY);
if (latitudeBar && bgPaint != null)
c.drawRect(latitudeBarRect, bgPaint);
if (longitudeBar && bgPaint != null) {
// Don't draw on top of latitude background...
int offsetTop = latitudeBar ? latitudeBarRect.height() : 0;
c.drawRect(longitudeBarRect.left, longitudeBarRect.top + offsetTop,
longitudeBarRect.right, longitudeBarRect.bottom, bgPaint);
}
c.drawPath(barPath, barPaint);
if (latitudeBar) {
drawLatitudeText(c, projection);
}
if (longitudeBar) {
drawLongitudeText(c, projection);
}
projection.restore(c, true);
} |
java | boolean containsRule( Rule rule ) {
for( int i = state.stackIdx - 1; i >= 0; i-- ) {
if( rule == state.stack.get( i ).mixin ) {
return true;
}
}
return false;
} |
java | private void readPropertiesFiles() {
if (this.configurationFileWildcard.isEmpty() || this.configurationFileExtension.isEmpty()) {
// Skip configuration loading
LOGGER.log(SKIP_CONF_LOADING);
} else {
// Assemble the regex pattern
final Pattern filePattern = Pattern.compile(this.configurationFileWildcard + "\\." + this.configurationFileExtension);
// Retrieve all resources from default classpath
final Collection<String> list = ClasspathUtility.getClasspathResources(filePattern);
LOGGER.log(CONFIG_FOUND, list.size(), list.size() > 1 ? "s" : "");
for (final String confFilename : list) {
readPropertiesFile(confFilename);
}
}
} |
python | def latent_prediction_model(inputs,
ed_attention_bias,
latents_discrete,
latents_dense,
hparams,
vocab_size=None,
name=None):
"""Transformer-based latent prediction model.
It is an autoregressive decoder over latents_discrete given inputs.
Args:
inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to
attend to for the decoder on latents.
ed_attention_bias: Tensor which broadcasts with shape [batch,
hparams.num_heads, length_q, length_kv]. Encoder-decoder attention bias.
latents_discrete: Tensor of shape [batch, length_q, vocab_size].
One-hot latents to compute log-probability of given inputs.
latents_dense: Tensor of shape [batch, length_q, hparams.hidden_size].
length_q is the latent length, which is
height * width * hparams.num_latents / (2**hparams.num_compress_steps).
hparams: HParams.
vocab_size: int or None. If None, it is 2**hparams.bottleneck_bits.
name: string, variable scope.
Returns:
latents_pred: Tensor of shape [batch, length_q, hparams.hidden_size].
latents_pred_loss: Tensor of shape [batch, length_q].
"""
with tf.variable_scope(name, default_name="latent_prediction"):
if hparams.mode != tf.estimator.ModeKeys.PREDICT:
latents_pred = transformer_latent_decoder(tf.stop_gradient(latents_dense),
inputs,
ed_attention_bias,
hparams,
name)
if vocab_size is None:
vocab_size = 2**hparams.bottleneck_bits
if not hparams.soft_em:
# TODO(trandustin): latents_discrete is not one-hot from
# discrete_bottleneck unless hparams.soft_em is True. Refactor.
latents_discrete = tf.one_hot(latents_discrete, depth=vocab_size)
_, latent_pred_loss = ae_latent_softmax(
latents_pred, tf.stop_gradient(latents_discrete), vocab_size, hparams)
return latents_pred, latent_pred_loss |
java | public void marshall(DescribeCustomKeyStoresRequest describeCustomKeyStoresRequest, ProtocolMarshaller protocolMarshaller) {
if (describeCustomKeyStoresRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeCustomKeyStoresRequest.getCustomKeyStoreId(), CUSTOMKEYSTOREID_BINDING);
protocolMarshaller.marshall(describeCustomKeyStoresRequest.getCustomKeyStoreName(), CUSTOMKEYSTORENAME_BINDING);
protocolMarshaller.marshall(describeCustomKeyStoresRequest.getLimit(), LIMIT_BINDING);
protocolMarshaller.marshall(describeCustomKeyStoresRequest.getMarker(), MARKER_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @Override
public BufferedReader getReader() throws IOException {
try {
collaborator.preInvoke(componentMetaData);
return request.getReader();
} finally {
collaborator.postInvoke();
}
} |
python | def expander_to_zone(self, address, channel, panel_type=ADEMCO):
"""
Convert an address and channel into a zone number.
:param address: expander address
:type address: int
:param channel: channel
:type channel: int
:returns: zone number associated with an address and channel
"""
zone = -1
if panel_type == ADEMCO:
# TODO: This is going to need to be reworked to support the larger
# panels without fixed addressing on the expanders.
idx = address - 7 # Expanders start at address 7.
zone = address + channel + (idx * 7) + 1
elif panel_type == DSC:
zone = (address * 8) + channel
return zone |
python | def plot_labels(labels, lattice=None, coords_are_cartesian=False, ax=None,
**kwargs):
"""
Adds labels to a matplotlib Axes
Args:
labels: dict containing the label as a key and the coordinates as value.
lattice: Lattice object used to convert from reciprocal to cartesian coordinates
coords_are_cartesian: Set to True if you are providing.
coordinates in cartesian coordinates. Defaults to False.
Requires lattice if False.
ax: matplotlib :class:`Axes` or None if a new figure should be created.
kwargs: kwargs passed to the matplotlib function 'text'. Color defaults to blue
and size to 25.
Returns:
matplotlib figure and matplotlib ax
"""
ax, fig, plt = get_ax3d_fig_plt(ax)
if "color" not in kwargs:
kwargs["color"] = "b"
if "size" not in kwargs:
kwargs["size"] = 25
for k, coords in labels.items():
label = k
if k.startswith("\\") or k.find("_") != -1:
label = "$" + k + "$"
off = 0.01
if coords_are_cartesian:
coords = np.array(coords)
else:
if lattice is None:
raise ValueError(
"coords_are_cartesian False requires the lattice")
coords = lattice.get_cartesian_coords(coords)
ax.text(*(coords + off), s=label, **kwargs)
return fig, ax |
python | def _is_dir(self, f):
'''Check if the given in-dap file is a directory'''
return self._tar.getmember(f).type == tarfile.DIRTYPE |
java | public static ShearCaptcha createShearCaptcha(int width, int height, int codeCount, int thickness) {
return new ShearCaptcha(width, height, codeCount, thickness);
} |
python | def _wait_and_kill(pid_to_wait, pids_to_kill):
""" Helper function.
Wait for a process to finish if it exists, and then try to kill a list of
processes.
Used by local_train
Args:
pid_to_wait: the process to wait for.
pids_to_kill: a list of processes to kill after the process of pid_to_wait finishes.
"""
# cloud workers don't have psutil
import psutil
if psutil.pid_exists(pid_to_wait):
psutil.Process(pid=pid_to_wait).wait()
for pid_to_kill in pids_to_kill:
if psutil.pid_exists(pid_to_kill):
p = psutil.Process(pid=pid_to_kill)
p.kill()
p.wait() |
java | public float getFloat(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return 0.0f;
}
if (fieldValue instanceof Number) {
return ((Number) fieldValue).floatValue();
}
throw new DBFException("Unsupported type for Number at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} |
java | public Match parseUntil(String src,String delimiter) {
return this.parseUntil(src,delimiter,new Options());
} |
java | public Object remove(Object key) {
mCacheMap.remove(key);
return mBackingMap.remove(key);
} |
python | def on_person_update(self, people):
"""
People have changed
Should always include all people
(all that were added via on_person_new)
:param people: People to update
:type people: list[paps.people.People]
:rtype: None
:raises Exception: On error (for now just an exception)
"""
try:
self.sensor_client.person_update(people)
except:
self.exception("Failed to update people")
raise Exception("Updating people failed") |
java | public void decrease(final DeviceControllerChannel channel, final int steps)
throws IOException {
if (channel == null) {
throw new RuntimeException("null-channel is not allowed. For devices "
+ "knowing just one wiper Channel.A is mandatory for "
+ "parameter 'channel'");
}
// decrease only works on volatile-wiper
byte memAddr = channel.getVolatileMemoryAddress();
increaseOrDecrease(memAddr, false, steps);
} |
java | private ProjectFile handleDirectory(File directory) throws Exception
{
ProjectFile result = handleDatabaseInDirectory(directory);
if (result == null)
{
result = handleFileInDirectory(directory);
}
return result;
} |
java | public Nfs3MknodResponse wrapped_sendMknod(NfsMknodRequest request) throws IOException {
RpcResponseHandler<Nfs3MknodResponse> responseHandler = new NfsResponseHandler<Nfs3MknodResponse>() {
/* (non-Javadoc)
* @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewResponse()
*/
protected Nfs3MknodResponse makeNewResponse() {
return new Nfs3MknodResponse();
}
};
_rpcWrapper.callRpcWrapped(request, responseHandler);
return responseHandler.getResponse();
} |
python | def hscroll(clicks, x=None, y=None, pause=None, _pause=True):
"""Performs an explicitly horizontal scroll of the mouse scroll wheel,
if this is supported by the operating system. (Currently just Linux.)
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.
Args:
clicks (int, float): The amount of scrolling to perform.
x (int, float, None, tuple, optional): The x position on the screen where the
click happens. None by default. If tuple, this is used for x and y.
y (int, float, None, optional): The y position on the screen where the
click happens. None by default.
Returns:
None
"""
_failSafeCheck()
if type(x) in (tuple, list):
x, y = x[0], x[1]
x, y = position(x, y)
platformModule._hscroll(clicks, x, y)
_autoPause(pause, _pause) |
java | private WMenu buildMenu(final WText selectedMenuText) {
WMenu menu = new WMenu(WMenu.MenuType.FLYOUT);
// The Colours menu just shows simple text
WSubMenu colourMenu = new WSubMenu("Colours");
addMenuItem(colourMenu, "Red", selectedMenuText);
addMenuItem(colourMenu, "Green", selectedMenuText);
addMenuItem(colourMenu, "Blue", selectedMenuText);
colourMenu.addSeparator();
colourMenu.add(new WMenuItem("Disable colour menu", new ToggleDisabledAction(colourMenu)));
menu.add(colourMenu);
// The Shapes menu shows grouping of items
WSubMenu shapeMenu = new WSubMenu("Shapes");
addMenuItem(shapeMenu, "Circle", selectedMenuText);
WMenuItemGroup triangleGroup = new WMenuItemGroup("Triangles");
shapeMenu.add(triangleGroup);
addMenuItem(triangleGroup, "Equilateral", selectedMenuText);
addMenuItem(triangleGroup, "Isosceles", selectedMenuText);
addMenuItem(triangleGroup, "Scalene", selectedMenuText);
addMenuItem(triangleGroup, "Right-angled", selectedMenuText);
addMenuItem(triangleGroup, "Obtuse", selectedMenuText);
WMenuItemGroup quadGroup = new WMenuItemGroup("Quadrilaterals");
shapeMenu.add(quadGroup);
addMenuItem(quadGroup, "Square", selectedMenuText);
addMenuItem(quadGroup, "Rectangle", selectedMenuText);
addMenuItem(quadGroup, "Rhombus", selectedMenuText);
addMenuItem(quadGroup, "Trapezoid", selectedMenuText);
addMenuItem(quadGroup, "Parallelogram", selectedMenuText);
shapeMenu.addSeparator();
shapeMenu.add(new WMenuItem("Disable shape menu", new ToggleDisabledAction(shapeMenu)));
menu.add(shapeMenu);
// The Image menu shows use of decorated labels and images
WSubMenu imageMenu = new WSubMenu("Images");
imageMenu.add(createImageMenuItem("/image/flag.png", "Flag", "eg-menu-image-1",
selectedMenuText));
imageMenu.add(createImageMenuItem("/image/attachment.png", "Attachment", "eg-menu-image-2",
selectedMenuText));
imageMenu.add(createImageMenuItem("/image/settings.png", "Settings", "eg-menu-image-3",
selectedMenuText));
imageMenu.addSeparator();
imageMenu.add(new WMenuItem("Disable image menu", new ToggleDisabledAction(imageMenu)));
menu.add(imageMenu);
WSubMenu sitesMenu = new WSubMenu("External apps");
sitesMenu.add(new WMenuItem("Example website", "http://www.example.com/"));
WMenuItem google = new WMenuItem("Example (new window)", "http://www.example.com/");
google.setTargetWindow("exampleWindow");
sitesMenu.add(google);
menu.add(sitesMenu);
// Add an item to toggle the states of all the menus
menu.add(new WMenuItem("Toggle top-level menus", new ToggleDisabledAction(colourMenu,
shapeMenu, imageMenu,
sitesMenu)));
menu.add(new WMenuItem("Link", "http://www.example.com"));
menu.add(new WMenuItem("No Action"));
return menu;
} |
python | def add_qemu_path(self, instance):
"""
Add the qemu path to the hypervisor conf data
:param instance: Hypervisor instance
"""
tmp_conf = {'qemu_path': self.old_top[instance]['qemupath']}
if len(self.topology['conf']) == 0:
self.topology['conf'].append(tmp_conf)
else:
self.topology['conf'][self.hv_id].update(tmp_conf) |
java | public byte[] convertToXmlByteArray(BucketWebsiteConfiguration websiteConfiguration) {
XmlWriter xml = new XmlWriter();
xml.start("WebsiteConfiguration", "xmlns", Constants.XML_NAMESPACE);
if (websiteConfiguration.getIndexDocumentSuffix() != null) {
XmlWriter indexDocumentElement = xml.start("IndexDocument");
indexDocumentElement.start("Suffix").value(websiteConfiguration.getIndexDocumentSuffix()).end();
indexDocumentElement.end();
}
if (websiteConfiguration.getErrorDocument() != null) {
XmlWriter errorDocumentElement = xml.start("ErrorDocument");
errorDocumentElement.start("Key").value(websiteConfiguration.getErrorDocument()).end();
errorDocumentElement.end();
}
RedirectRule redirectAllRequestsTo = websiteConfiguration.getRedirectAllRequestsTo();
if (redirectAllRequestsTo != null) {
XmlWriter redirectAllRequestsElement = xml.start("RedirectAllRequestsTo");
if (redirectAllRequestsTo.getprotocol() != null) {
xml.start("Protocol").value(redirectAllRequestsTo.getprotocol()).end();
}
if (redirectAllRequestsTo.getHostName() != null) {
xml.start("HostName").value(redirectAllRequestsTo.getHostName()).end();
}
if (redirectAllRequestsTo.getReplaceKeyPrefixWith() != null) {
xml.start("ReplaceKeyPrefixWith").value(redirectAllRequestsTo.getReplaceKeyPrefixWith()).end();
}
if (redirectAllRequestsTo.getReplaceKeyWith() != null) {
xml.start("ReplaceKeyWith").value(redirectAllRequestsTo.getReplaceKeyWith()).end();
}
redirectAllRequestsElement.end();
}
if (websiteConfiguration.getRoutingRules() != null && websiteConfiguration.getRoutingRules().size() > 0) {
XmlWriter routingRules = xml.start("RoutingRules");
for (RoutingRule rule : websiteConfiguration.getRoutingRules()) {
writeRule(routingRules, rule);
}
routingRules.end();
}
xml.end();
return xml.getBytes();
} |
java | private void add2MBR(int[] entrySorting, double[] ub, double[] lb, int index) {
SpatialComparable currMBR = node.getEntry(entrySorting[index]);
for(int d = 0; d < currMBR.getDimensionality(); d++) {
double max = currMBR.getMax(d);
if(max > ub[d]) {
ub[d] = max;
}
double min = currMBR.getMin(d);
if(min < lb[d]) {
lb[d] = min;
}
}
} |
python | def _update_functions(self):
"""
Uses internal settings to update the functions.
"""
self.f = []
self.bg = []
self._fnames = []
self._bgnames = []
self._odr_models = [] # Like f, but different parameters, for use in ODR
f = self._f_raw
bg = self._bg_raw
# make sure f and bg are lists of matching length
if not _s.fun.is_iterable(f) : f = [f]
if not _s.fun.is_iterable(bg): bg = [bg]
while len(bg) < len(f): bg.append(None)
# get a comma-delimited string list of parameter names for the "normal" function
pstring = 'x, ' + ', '.join(self._pnames)
# get the comma-delimited string for the ODR function
pstring_odr = 'x, '
for n in range(len(self._pnames)): pstring_odr = pstring_odr+'p['+str(n)+'], '
# update the globals for the functions
# the way this is done, we must redefine the functions
# every time we change a constant
for cname in self._cnames: self._globals[cname] = self[cname]
# loop over all the functions and create the master list
for n in range(len(f)):
# if f[n] is a string, define a function on the fly.
if isinstance(f[n], str):
# "Normal" least squares function (y-error bars only)
self.f.append( eval('lambda ' + pstring + ': ' + f[n], self._globals))
self._fnames.append(f[n])
# "ODR" compatible function (for x-error bars), based on self.f
self._odr_models.append( _odr.Model(eval('lambda p,x: self.f[n]('+pstring_odr+')', dict(self=self, n=n))))
# Otherwise, just append it.
else:
self.f.append(f[n])
self._fnames.append(f[n].__name__)
# if bg[n] is a string, define a function on the fly.
if isinstance(bg[n], str):
self.bg.append(eval('lambda ' + pstring + ': ' + bg[n], self._globals))
self._bgnames.append(bg[n])
else:
self.bg.append(bg[n])
if bg[n] is None: self._bgnames.append("None")
else: self._bgnames.append(bg[n].__name__)
# update the format of all the settings
for k in list(self._settings.keys()): self[k] = self[k]
# make sure we don't think our fit results are valid!
self.clear_results() |
java | private boolean logIfEnabled(Level level, Throwable t, String msgTemplate, Object... arguments) {
return logIfEnabled(FQCN, level, t, msgTemplate, arguments);
} |
python | def on_foreground_image(self, *args):
"""When I get a new ``foreground_image``, store its texture in my
``foreground_texture``.
"""
if self.foreground_image is not None:
self.foreground_texture = self.foreground_image.texture |
python | def summary(args):
"""
%prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC
"""
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
gff_file, ref = args
s = Fasta(ref)
g = make_index(gff_file)
geneseqs, exonseqs, intronseqs = [], [], [] # Calc % GC
for f in g.features_of_type("gene"):
fid = f.id
fseq = s.sequence({'chr': f.chrom, 'start': f.start, 'stop': f.stop})
geneseqs.append(fseq)
exons = set((c.chrom, c.start, c.stop) for c in g.children(fid, 2) \
if c.featuretype == "exon")
exons = list(exons)
for chrom, start, stop in exons:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
exonseqs.append(fseq)
introns = range_interleave(exons)
for chrom, start, stop in introns:
fseq = s.sequence({'chr': chrom, 'start': start, 'stop': stop})
intronseqs.append(fseq)
r = {} # Report
for t, tseqs in zip(("Gene", "Exon", "Intron"), (geneseqs, exonseqs, intronseqs)):
tsizes = [len(x) for x in tseqs]
tsummary = SummaryStats(tsizes, dtype="int")
r[t, "Number"] = tsummary.size
r[t, "Average size (bp)"] = tsummary.mean
r[t, "Median size (bp)"] = tsummary.median
r[t, "Total length (Mb)"] = human_size(tsummary.sum, precision=0, target="Mb")
r[t, "% of genome"] = percentage(tsummary.sum, s.totalsize, precision=0, mode=-1)
r[t, "% GC"] = gc(tseqs)
print(tabulate(r), file=sys.stderr) |
java | protected void connect(InetAddress address, int port) throws SocketException {
BlockGuard.getThreadPolicy().onNetwork();
connect0(address, port);
connectedAddress = address;
connectedPort = port;
connected = true;
} |
python | def is_constrained_reaction(model, rxn):
"""Return whether a reaction has fixed constraints."""
lower_bound, upper_bound = helpers.find_bounds(model)
if rxn.reversibility:
return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound
else:
return rxn.lower_bound > 0 or rxn.upper_bound < upper_bound |
java | private double getWidthForMappingLine(RendererModel model) {
double scale = model.getParameter(Scale.class).getValue();
return mappingLineWidth.getValue() / scale;
} |
java | @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "We never need to synchronize with the preloader.")
void preloadContainerLifecycleEvent(Class<?> eventRawType, Type... typeParameters) {
executor.submit(new PreloadingTask(new ParameterizedTypeImpl(eventRawType, typeParameters, null)));
} |
java | @Override
public synchronized int update(T dto) throws Exception {
return db.update(transformer.getTableName(), transformer.transform(dto),transformer.getWhereClause(dto), null);
} |
java | public static final Object deserialize(byte[] bytes) throws Exception {
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(tc, "deserialize");
Object o;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream oin = new ObjectInputStream(bis);
o = oin.readObject();
oin.close();
} catch (IOException e) {
FFDCFilter.processException(e, ConnectorService.class.getName(), "151");
if (trace && tc.isEntryEnabled())
Tr.exit(tc, "deserialize", new Object[] { toString(bytes), e });
throw e;
}
if (trace && tc.isEntryEnabled())
Tr.exit(tc, "deserialize", o == null ? null : o.getClass());
return o;
} |
python | def _create_pipeline_parser():
""" Create the parser for the %pipeline magics.
Note that because we use the func default handler dispatch mechanism of
argparse, our handlers can take only one argument which is the parsed args. So
we must create closures for the handlers that bind the cell contents and thus
must recreate this parser for each cell upon execution.
"""
parser = google.datalab.utils.commands.CommandParser(
prog='%pipeline', description="""
Execute various pipeline-related operations. Use "%pipeline <command> -h"
for help on a specific command.
""")
# %%pipeline create
_add_command(parser, _create_create_subparser, _create_cell)
return parser |
java | public static JwtClaims verifyJwt(String jwt, boolean ignoreExpiry, boolean isToken) throws InvalidJwtException, ExpiredTokenException {
JwtClaims claims;
if(Boolean.TRUE.equals(enableJwtCache)) {
claims = cache.getIfPresent(jwt);
if(claims != null) {
if(!ignoreExpiry) {
try {
// if using our own client module, the jwt token should be renewed automatically
// and it will never expired here. However, we need to handle other clients.
if ((NumericDate.now().getValue() - secondsOfAllowedClockSkew) >= claims.getExpirationTime().getValue())
{
logger.info("Cached jwt token is expired!");
throw new ExpiredTokenException("Token is expired");
}
} catch (MalformedClaimException e) {
// This is cached token and it is impossible to have this exception
logger.error("MalformedClaimException:", e);
}
}
// this claims object is signature verified already
return claims;
}
}
JwtConsumer consumer = new JwtConsumerBuilder()
.setSkipAllValidators()
.setDisableRequireSignature()
.setSkipSignatureVerification()
.build();
JwtContext jwtContext = consumer.process(jwt);
claims = jwtContext.getJwtClaims();
JsonWebStructure structure = jwtContext.getJoseObjects().get(0);
// need this kid to load public key certificate for signature verification
String kid = structure.getKeyIdHeaderValue();
// so we do expiration check here manually as we have the claim already for kid
// if ignoreExpiry is false, verify expiration of the token
if(!ignoreExpiry) {
try {
if ((NumericDate.now().getValue() - secondsOfAllowedClockSkew) >= claims.getExpirationTime().getValue())
{
logger.info("jwt token is expired!");
throw new ExpiredTokenException("Token is expired");
}
} catch (MalformedClaimException e) {
logger.error("MalformedClaimException:", e);
throw new InvalidJwtException("MalformedClaimException", new ErrorCodeValidator.Error(ErrorCodes.MALFORMED_CLAIM, "Invalid ExpirationTime Format"), e, jwtContext);
}
}
// get the public key certificate from the cache that is loaded from security.yml if it is not there,
// go to OAuth2 server /oauth2/key endpoint to get the public key certificate with kid as parameter.
X509Certificate certificate = certMap == null? null : certMap.get(kid);
if(certificate == null) {
certificate = isToken? getCertForToken(kid) : getCertForSign(kid);
if(certMap == null) certMap = new HashMap<>(); // null if bootstrapFromKeyService is true
certMap.put(kid, certificate);
}
X509VerificationKeyResolver x509VerificationKeyResolver = new X509VerificationKeyResolver(certificate);
x509VerificationKeyResolver.setTryAllOnNoThumbHeader(true);
consumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setAllowedClockSkewInSeconds(315360000) // use seconds of 10 years to skip expiration validation as we need skip it in some cases.
.setSkipDefaultAudienceValidation()
.setVerificationKeyResolver(x509VerificationKeyResolver)
.build();
// Validate the JWT and process it to the Claims
jwtContext = consumer.process(jwt);
claims = jwtContext.getJwtClaims();
if(Boolean.TRUE.equals(enableJwtCache)) {
cache.put(jwt, claims);
}
return claims;
} |
python | def _register_bundle_factories(self, bundle):
# type: (Bundle) -> None
"""
Registers all factories found in the given bundle
:param bundle: A bundle
"""
# Load the bundle factories
factories = _load_bundle_factories(bundle)
for context, factory_class in factories:
try:
# Register each found factory
self._register_factory(context.name, factory_class, False)
except ValueError as ex:
# Already known factory
_logger.error(
"Cannot register factory '%s' of bundle %d (%s): %s",
context.name,
bundle.get_bundle_id(),
bundle.get_symbolic_name(),
ex,
)
_logger.error(
"class: %s -- module: %s",
factory_class,
factory_class.__module__,
)
else:
# Instantiate components
for name, properties in context.get_instances().items():
self.instantiate(context.name, name, properties) |
python | def path_manager_callback(self):
"""Spyder path manager"""
from spyder.widgets.pathmanager import PathManager
self.remove_path_from_sys_path()
project_path = self.projects.get_pythonpath()
dialog = PathManager(self, self.path, project_path,
self.not_active_path, sync=True)
dialog.redirect_stdio.connect(self.redirect_internalshell_stdio)
dialog.exec_()
self.add_path_to_sys_path()
try:
encoding.writelines(self.path, self.SPYDER_PATH) # Saving path
encoding.writelines(self.not_active_path,
self.SPYDER_NOT_ACTIVE_PATH)
except EnvironmentError:
pass
self.sig_pythonpath_changed.emit() |
java | public static final Function<Float,Boolean> eq(final Float object) {
return (Function<Float,Boolean>)((Function)FnObject.eq(object));
} |
java | public boolean canImport(String label, String namespace) {
if (!exported.containsKey(label)) {
return false;
}
Set<String> scopes = exportScopes.get(label);
for (String scope : scopes) {
if (scope.equals(namespace)) {
return true;
} else if (scope.endsWith("*") && namespace.startsWith(scope.substring(0, scope.length() - 1))) {
return true;
}
}
return false;
} |
python | def _receiveFromListener(self, quota: Quota) -> int:
"""
Receives messages from listener
:param quota: number of messages to receive
:return: number of received messages
"""
i = 0
incoming_size = 0
while i < quota.count and incoming_size < quota.size:
try:
ident, msg = self.listener.recv_multipart(flags=zmq.NOBLOCK)
if not msg:
# Router probing sends empty message on connection
continue
incoming_size += len(msg)
i += 1
self._verifyAndAppend(msg, ident)
except zmq.Again:
break
if i > 0:
logger.trace('{} got {} messages through listener'.
format(self, i))
return i |
java | @Override
public StringMap getReadOnlyContextData() {
StringMap map = localMap.get();
if (map == null) {
map = createStringMap();
localMap.set(map);
}
return map;
} |
python | def getMugshot(self):
"""
Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image.
"""
mugshot = self.store.findUnique(
Mugshot, Mugshot.person == self, default=None)
if mugshot is not None:
return mugshot
return Mugshot.placeholderForPerson(self) |
python | def edit_file(self, filename, line):
"""Handle %edit magic petitions."""
if encoding.is_text_file(filename):
# The default line number sent by ipykernel is always the last
# one, but we prefer to use the first.
self.edit_goto.emit(filename, 1, '') |
java | public FieldInfo getFieldInfo(String name) {
if (name != null) {
if (ignoreCase) {
name = name.toLowerCase(Locale.US);
}
name = name.intern();
}
return nameToFieldInfoMap.get(name);
} |
java | @Override
public GetDimensionValuesResult getDimensionValues(GetDimensionValuesRequest request) {
request = beforeClientExecution(request);
return executeGetDimensionValues(request);
} |
java | public SimpleFeature convertDwgPoint( String typeName, String layerName, DwgPoint point, int id ) {
double[] p = point.getPoint();
Point2D pto = new Point2D.Double(p[0], p[1]);
CoordinateList coordList = new CoordinateList();
Coordinate coord = new Coordinate(pto.getX(), pto.getY(), 0.0);
coordList.add(coord);
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName(typeName);
b.setCRS(crs);
b.add(THE_GEOM, MultiPoint.class);
b.add(LAYER, String.class);
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
Geometry points = gF.createMultiPoint(coordList.toCoordinateArray());
Object[] values = new Object[]{points, layerName};
builder.addAll(values);
return builder.buildFeature(typeName + "." + id);
} |
java | protected void invokeHandler(Event event, ApiContext apiContext)
throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, InstantiationException
{
String topic[] = event.getTopic().split("\\.");
String eventCategory = topic[0].substring(0, 1).toUpperCase() + topic[0].substring(1);
String eventAction = topic[1];
// get list of registered handlers
Object handler = EventManager.getInstance().getRegisteredClassHandlers(eventCategory);
if (handler !=null) {
String methodName = eventAction;
String className = handler.getClass().getName();
try {
Method m;
m = handler.getClass().getMethod(methodName, ApiContext.class, Event.class);
m.invoke(handler, apiContext, event);
} catch (NoSuchMethodException e) {
logger.warn("No " + eventAction + " method on class " + className);
throw e;
} catch (SecurityException e) {
logger.warn("Security exception: " + e.getMessage());
throw e;
} catch (IllegalAccessException e) {
logger.warn("Illegal access for method " + eventAction + " on class " + className);
throw e;
} catch (IllegalArgumentException e) {
logger.warn("Illegal argument exception for method " + eventAction + " on class " + className);
throw e;
} catch (InvocationTargetException e) {
logger.warn("Invocation target exception for method " + eventAction + " on class " + className);
throw e;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.