language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public static JavaRDD<String> listPaths(JavaSparkContext sc, String path, boolean recursive, Set<String> allowedExtensions) throws IOException {
return listPaths(sc, path, recursive, allowedExtensions, sc.hadoopConfiguration());
} |
java | private void initState() {
skipPhase = false;
beforeMethodException = false;
//noinspection unchecked
List<PhaseListener> listeners =
(List<PhaseListener>) getStateHelper().get(PropertyKeys.phaseListeners);
phaseListenerIterator =
((listeners != null) ? listeners.listIterator() : null);
} |
python | def fastp_filtered_reads_chart(self):
""" Function to generate the fastp filtered reads bar plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['filtering_result_passed_filter_reads'] = { 'name': 'Passed Filter' }
keys['filtering_result_low_quality_reads'] = { 'name': 'Low Quality' }
keys['filtering_result_too_many_N_reads'] = { 'name': 'Too Many N' }
keys['filtering_result_too_short_reads'] = { 'name': 'Too short' }
# Config for the plot
pconfig = {
'id': 'fastp_filtered_reads_plot',
'title': 'Fastp: Filtered Reads',
'ylab': '# Reads',
'cpswitch_counts_label': 'Number of Reads',
'hide_zero_cats': False,
}
return bargraph.plot(self.fastp_data, keys, pconfig) |
python | def resample(self, sampling_rate=None, variables=None, force_dense=False,
in_place=False, kind='linear'):
''' Resample all dense variables (and optionally, sparse ones) to the
specified sampling rate.
Args:
sampling_rate (int, float): Target sampling rate (in Hz). If None,
uses the instance sampling rate.
variables (list): Optional list of Variables to resample. If None,
all variables are resampled.
force_dense (bool): if True, all sparse variables will be forced to
dense.
in_place (bool): When True, all variables are overwritten in-place.
When False, returns resampled versions of all variables.
kind (str): Argument to pass to scipy's interp1d; indicates the
kind of interpolation approach to use. See interp1d docs for
valid values.
'''
# Store old sampling rate-based variables
sampling_rate = sampling_rate or self.sampling_rate
_variables = {}
for name, var in self.variables.items():
if variables is not None and name not in variables:
continue
if isinstance(var, SparseRunVariable):
if force_dense and is_numeric_dtype(var.values):
_variables[name] = var.to_dense(sampling_rate)
else:
# None if in_place; no update needed
_var = var.resample(sampling_rate,
inplace=in_place,
kind=kind)
if not in_place:
_variables[name] = _var
if in_place:
for k, v in _variables.items():
self.variables[k] = v
self.sampling_rate = sampling_rate
else:
return _variables |
python | def request_issuance(self, csr):
"""
Request a certificate.
Authorizations should have already been completed for all of the names
requested in the CSR.
Note that unlike `acme.client.Client.request_issuance`, the certificate
resource will have the body data as raw bytes.
.. seealso:: `txacme.util.csr_for_names`
.. todo:: Delayed issuance is not currently supported, the server must
issue the requested certificate immediately.
:param csr: A certificate request message: normally
`txacme.messages.CertificateRequest` or
`acme.messages.CertificateRequest`.
:rtype: Deferred[`acme.messages.CertificateResource`]
:return: The issued certificate.
"""
action = LOG_ACME_REQUEST_CERTIFICATE()
with action.context():
return (
DeferredContext(
self._client.post(
self.directory[csr], csr,
content_type=DER_CONTENT_TYPE,
headers=Headers({b'Accept': [DER_CONTENT_TYPE]})))
.addCallback(self._expect_response, http.CREATED)
.addCallback(self._parse_certificate)
.addActionFinish()) |
python | def stop_sync(self):
"""Safely stop this BLED112 instance without leaving it in a weird state"""
# Stop to scan
if self.scanning:
self.stop_scan()
# Disconnect all connected devices
for connection_id in list(self.connections.get_connections()):
self.disconnect_sync(connection_id)
# Stop the baBLE interface
self.bable.stop()
# Stop the connection manager
self.connections.stop()
self.stopped = True |
python | def _validate(cls, message):
"""Confirm the validitiy of a given dict as an OpenXC message.
Returns:
``True`` if the message contains at least a ``name`` and ``value``.
"""
valid = False
if(('name' in message and 'value' in message) or
('id' in message and 'data' in message)):
valid = True
return valid |
java | public static <A, B, EA extends A, A1> DecomposableMatchBuilder1<Tuple2<A, B>, A1> tuple2(
DecomposableMatchBuilder1<EA, A1> a, MatchesExact<B> b) {
List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.any(), ArgumentMatchers.eq(b.t));
return new DecomposableMatchBuilder1<Tuple2<A, B>, EA>(
matchers, 0, new Tuple2FieldExtractor<>()).decomposeFirst(a);
} |
java | public boolean fastEquals(NumberRange that) {
return that != null
&& reverse == that.reverse
&& inclusive == that.inclusive
&& compareEqual(from, that.from)
&& compareEqual(to, that.to)
&& compareEqual(stepSize, that.stepSize);
} |
java | protected void backtrack(final int newLevel) {
assert 0 <= newLevel && newLevel <= this.level;
if (newLevel == this.level) { return; }
CLFrame f = this.control.back();
while (f.level() > newLevel) {
assert f.level() == this.level;
assert f.trail() < this.trail.size();
while (f.trail() < this.trail.size()) {
final int lit = this.trail.back();
assert var(lit).level() == f.level();
this.trail.pop();
unassign(lit);
}
assert this.level > 0;
this.level--;
this.trail.shrinkTo(f.trail());
this.next = f.trail();
this.control.pop();
f = this.control.back();
}
assert newLevel == this.level;
} |
python | def ReadClientCrashInfo(self, client_id):
"""Reads the latest client crash record for a single client."""
history = self.crash_history.get(client_id, None)
if not history:
return None
ts = max(history)
res = rdf_client.ClientCrash.FromSerializedString(history[ts])
res.timestamp = ts
return res |
java | void addPTable(PdfPTable ptable) throws DocumentException {
ColumnText ct = new ColumnText(writer.getDirectContent());
// if the table prefers to be on a single page, and it wouldn't
//fit on the current page, start a new page.
if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && currentHeight > 0) {
newPage();
}
// add dummy paragraph if we aren't at the top of a page, so that
// spacingBefore will be taken into account by ColumnText
if (currentHeight > 0) {
Paragraph p = new Paragraph();
p.setLeading(0);
ct.addElement(p);
}
ct.addElement(ptable);
boolean he = ptable.isHeadersInEvent();
ptable.setHeadersInEvent(true);
int loop = 0;
while (true) {
ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight);
int status = ct.go();
if ((status & ColumnText.NO_MORE_TEXT) != 0) {
text.moveText(0, ct.getYLine() - indentTop() + currentHeight);
currentHeight = indentTop() - ct.getYLine();
break;
}
if (indentTop() - currentHeight == ct.getYLine())
++loop;
else
loop = 0;
if (loop == 3) {
add(new Paragraph("ERROR: Infinite table loop"));
break;
}
newPage();
}
ptable.setHeadersInEvent(he);
} |
python | def is_uniform(self):
"""Return if file contains a uniform series of pages."""
# the hashes of IFDs 0, 7, and -1 are the same
pages = self.pages
page = pages[0]
if page.is_scanimage or page.is_nih:
return True
try:
useframes = pages.useframes
pages.useframes = False
h = page.hash
for i in (1, 7, -1):
if pages[i].aspage().hash != h:
return False
except IndexError:
return False
finally:
pages.useframes = useframes
return True |
python | def processPreKeyBundle(self, preKey):
"""
:type preKey: PreKeyBundle
"""
if not self.identityKeyStore.isTrustedIdentity(self.recipientId, preKey.getIdentityKey()):
raise UntrustedIdentityException(self.recipientId, preKey.getIdentityKey())
if preKey.getSignedPreKey() is not None and\
not Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),
preKey.getSignedPreKey().serialize(),
preKey.getSignedPreKeySignature()):
raise InvalidKeyException("Invalid signature on device key!")
if preKey.getSignedPreKey() is None and preKey.getPreKey() is None:
raise InvalidKeyException("Both signed and unsigned prekeys are absent!")
supportsV3 = preKey.getSignedPreKey() is not None
sessionRecord = self.sessionStore.loadSession(self.recipientId, self.deviceId)
ourBaseKey = Curve.generateKeyPair()
theirSignedPreKey = preKey.getSignedPreKey() if supportsV3 else preKey.getPreKey()
theirOneTimePreKey = preKey.getPreKey()
theirOneTimePreKeyId = preKey.getPreKeyId() if theirOneTimePreKey is not None else None
parameters = AliceAxolotlParameters.newBuilder()
parameters.setOurBaseKey(ourBaseKey)\
.setOurIdentityKey(self.identityKeyStore.getIdentityKeyPair())\
.setTheirIdentityKey(preKey.getIdentityKey())\
.setTheirSignedPreKey(theirSignedPreKey)\
.setTheirRatchetKey(theirSignedPreKey)\
.setTheirOneTimePreKey(theirOneTimePreKey if supportsV3 else None)
if not sessionRecord.isFresh():
sessionRecord.archiveCurrentState()
RatchetingSession.initializeSessionAsAlice(sessionRecord.getSessionState(),
3 if supportsV3 else 2,
parameters.create())
sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId,
preKey.getSignedPreKeyId(),
ourBaseKey.getPublicKey())
sessionRecord.getSessionState().setLocalRegistrationId(self.identityKeyStore.getLocalRegistrationId())
sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId())
sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize())
self.sessionStore.storeSession(self.recipientId, self.deviceId, sessionRecord)
self.identityKeyStore.saveIdentity(self.recipientId, preKey.getIdentityKey()) |
java | static public double integrate(Function1D f, double tol, double a, double b)
{
return integrate(f, tol, a, b, 100);
} |
java | public final short readShortLE() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short)((ch2 << 8) + (ch1 << 0));
} |
java | public void addProcedure(ProcedureDef procDef)
{
procDef.setOwner(this);
_procedures.put(procDef.getName(), procDef);
} |
python | def restart(self, restart_only_stale_services=None,
redeploy_client_configuration=None,
restart_service_names=None):
"""
Restart all services in the cluster.
Services are restarted in the appropriate order given their dependencies.
@param restart_only_stale_services: Only restart services that have stale
configuration and their dependent
services. Default is False.
@param redeploy_client_configuration: Re-deploy client configuration for
all services in the cluster. Default
is False.
@param restart_service_names: Only restart services that are specified and their dependent services.
Available since API v11.
@since API v6
@return: Reference to the submitted command.
"""
if self._get_resource_root().version < 6:
return self._cmd('restart')
else:
args = dict()
args['restartOnlyStaleServices'] = restart_only_stale_services
args['redeployClientConfiguration'] = redeploy_client_configuration
if self._get_resource_root().version >= 11:
args['restartServiceNames'] = restart_service_names
return self._cmd('restart', data=args, api_version=6) |
java | public final void mFLOAT() throws RecognitionException {
try {
int _type = FLOAT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:5: ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( Exponent )? ( FloatTypeSuffix )? | '.' ( '0' .. '9' )+ ( Exponent )? ( FloatTypeSuffix )? | ( '0' .. '9' )+ Exponent ( FloatTypeSuffix )? | ( '0' .. '9' )+ FloatTypeSuffix )
int alt13=4;
alt13 = dfa13.predict(input);
switch (alt13) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:9: ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( Exponent )? ( FloatTypeSuffix )?
{
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:9: ( '0' .. '9' )+
int cnt3=0;
loop3:
while (true) {
int alt3=2;
int LA3_0 = input.LA(1);
if ( ((LA3_0 >= '0' && LA3_0 <= '9')) ) {
alt3=1;
}
switch (alt3) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt3 >= 1 ) break loop3;
if (state.backtracking>0) {state.failed=true; return;}
EarlyExitException eee = new EarlyExitException(3, input);
throw eee;
}
cnt3++;
}
match('.'); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:25: ( '0' .. '9' )*
loop4:
while (true) {
int alt4=2;
int LA4_0 = input.LA(1);
if ( ((LA4_0 >= '0' && LA4_0 <= '9')) ) {
alt4=1;
}
switch (alt4) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
break loop4;
}
}
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:37: ( Exponent )?
int alt5=2;
int LA5_0 = input.LA(1);
if ( (LA5_0=='E'||LA5_0=='e') ) {
alt5=1;
}
switch (alt5) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:37: Exponent
{
mExponent(); if (state.failed) return;
}
break;
}
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:47: ( FloatTypeSuffix )?
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0=='B'||LA6_0=='D'||LA6_0=='F'||LA6_0=='d'||LA6_0=='f') ) {
alt6=1;
}
switch (alt6) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( input.LA(1)=='B'||input.LA(1)=='D'||input.LA(1)=='F'||input.LA(1)=='d'||input.LA(1)=='f' ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
}
break;
case 2 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:89:9: '.' ( '0' .. '9' )+ ( Exponent )? ( FloatTypeSuffix )?
{
match('.'); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:89:13: ( '0' .. '9' )+
int cnt7=0;
loop7:
while (true) {
int alt7=2;
int LA7_0 = input.LA(1);
if ( ((LA7_0 >= '0' && LA7_0 <= '9')) ) {
alt7=1;
}
switch (alt7) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt7 >= 1 ) break loop7;
if (state.backtracking>0) {state.failed=true; return;}
EarlyExitException eee = new EarlyExitException(7, input);
throw eee;
}
cnt7++;
}
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:89:25: ( Exponent )?
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0=='E'||LA8_0=='e') ) {
alt8=1;
}
switch (alt8) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:89:25: Exponent
{
mExponent(); if (state.failed) return;
}
break;
}
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:89:35: ( FloatTypeSuffix )?
int alt9=2;
int LA9_0 = input.LA(1);
if ( (LA9_0=='B'||LA9_0=='D'||LA9_0=='F'||LA9_0=='d'||LA9_0=='f') ) {
alt9=1;
}
switch (alt9) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( input.LA(1)=='B'||input.LA(1)=='D'||input.LA(1)=='F'||input.LA(1)=='d'||input.LA(1)=='f' ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
}
break;
case 3 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:90:9: ( '0' .. '9' )+ Exponent ( FloatTypeSuffix )?
{
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:90:9: ( '0' .. '9' )+
int cnt10=0;
loop10:
while (true) {
int alt10=2;
int LA10_0 = input.LA(1);
if ( ((LA10_0 >= '0' && LA10_0 <= '9')) ) {
alt10=1;
}
switch (alt10) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt10 >= 1 ) break loop10;
if (state.backtracking>0) {state.failed=true; return;}
EarlyExitException eee = new EarlyExitException(10, input);
throw eee;
}
cnt10++;
}
mExponent(); if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:90:30: ( FloatTypeSuffix )?
int alt11=2;
int LA11_0 = input.LA(1);
if ( (LA11_0=='B'||LA11_0=='D'||LA11_0=='F'||LA11_0=='d'||LA11_0=='f') ) {
alt11=1;
}
switch (alt11) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( input.LA(1)=='B'||input.LA(1)=='D'||input.LA(1)=='F'||input.LA(1)=='d'||input.LA(1)=='f' ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
}
}
break;
case 4 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:91:9: ( '0' .. '9' )+ FloatTypeSuffix
{
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:91:9: ( '0' .. '9' )+
int cnt12=0;
loop12:
while (true) {
int alt12=2;
int LA12_0 = input.LA(1);
if ( ((LA12_0 >= '0' && LA12_0 <= '9')) ) {
alt12=1;
}
switch (alt12) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:
{
if ( (input.LA(1) >= '0' && input.LA(1) <= '9') ) {
input.consume();
state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
MismatchedSetException mse = new MismatchedSetException(null,input);
recover(mse);
throw mse;
}
}
break;
default :
if ( cnt12 >= 1 ) break loop12;
if (state.backtracking>0) {state.failed=true; return;}
EarlyExitException eee = new EarlyExitException(12, input);
throw eee;
}
cnt12++;
}
mFloatTypeSuffix(); if (state.failed) return;
}
break;
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
} |
java | @Override
public void prepare(@SuppressWarnings("rawtypes") Map conf, TridentOperationContext context)
{
this.objectMapper = new ObjectMapper();
this.javaDateFormat = new SimpleDateFormat(this.dateFormatStr);
} |
python | def outputscreate():
"""
Brain.Outputs table creation
:return:
"""
# Create table with a nested index
r.db("Brain").table_create("Outputs").run()
r.db("Brain").table("Outputs").index_create("Output_job_id", r.row["OutputJob"]["id"]).run()
r.db("Brain").table("Outputs").index_wait("Output_job_id").run() |
java | public static IntBuffer allocate (int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException();
}
ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 4);
bb.order(ByteOrder.nativeOrder());
return bb.asIntBuffer();
} |
java | public static String getProperty(final ResourceBundle bundle, final String key) {
if (bundle == null) {
return key;
}
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
LOG.warn("找不到名为 " + key + " 的资源项", e);
return key;
}
} |
java | public final int getNumberOfCommandLineArgs() {
if (commandLine == null) {
return 0;
}
List<?> args = commandLine.getArgList();
if (args == null) {
return 0;
}
return args.size();
} |
java | public static String getProperty(String name, String defaultValue) {
if (PropertiesManager.props == null) loadProps();
String returnValue = defaultValue;
try {
returnValue = getProperty(name);
} catch (MissingPropertyException mpe) {
// Do nothing, since we have already recorded and logged the missing property.
}
return returnValue;
} |
python | def _try_compile(source, name):
"""Attempts to compile the given source, first as an expression and
then as a statement if the first approach fails.
Utility function to accept strings in functions that otherwise
expect code objects
"""
try:
c = compile(source, name, 'eval')
except SyntaxError:
c = compile(source, name, 'exec')
return c |
java | protected void on(JsonToken token, String fieldName, JsonParser jp) throws JsonParseException, IOException {
switch (token) {
case START_OBJECT:
onStartObject(fieldName, jp);
break;
case END_OBJECT:
onEndObject(fieldName, jp);
break;
case START_ARRAY:
onStartArray(fieldName, jp);
break;
case END_ARRAY:
onEndArray(fieldName, jp);
break;
case FIELD_NAME:
onFieldName(fieldName, jp);
break;
case VALUE_EMBEDDED_OBJECT:
// TODO
break;
case VALUE_STRING:
onString(jp.getText(), fieldName, jp);
break;
case VALUE_NUMBER_INT:
onInt(jp.getValueAsInt(), fieldName, jp);
break;
case VALUE_NUMBER_FLOAT:
onDouble(jp.getValueAsDouble(), fieldName, jp);
break;
case VALUE_TRUE:
onBoolean(true, fieldName, jp);
break;
case VALUE_FALSE:
onBoolean(false, fieldName, jp);
break;
case VALUE_NULL:
onNull(fieldName, jp);
break;
case NOT_AVAILABLE:
break;
default:
log.warn("Unhandled Token " + token + " found for field " + fieldName);
}
} |
java | public long roundHalfFloor(long instant) {
long floor = roundFloor(instant);
long ceiling = roundCeiling(instant);
long diffFromFloor = instant - floor;
long diffToCeiling = ceiling - instant;
if (diffFromFloor <= diffToCeiling) {
// Closer to the floor, or halfway - round floor
return floor;
} else {
return ceiling;
}
} |
java | public void setInitialClusters(List<? extends Cluster<? extends MeanModel>> initialMeans) {
double[][] vecs = new double[initialMeans.size()][];
for(int i = 0; i < vecs.length; i++) {
vecs[i] = initialMeans.get(i).getModel().getMean();
}
this.initialMeans = vecs;
} |
java | @Override
public List<byte[]> sort(final byte[] key, final SortingParams sortingParameters) {
checkIsInMultiOrPipeline();
client.sort(key, sortingParameters);
return client.getBinaryMultiBulkReply();
} |
java | public static LocalCall<Map<String, Xor<Info, List<Info>>>> infoInstalledAllVersions(
List<String> attributes, boolean reportErrors, String... packages) {
LinkedHashMap<String, Object> kwargs = new LinkedHashMap<>();
kwargs.put("attr", attributes.stream().collect(Collectors.joining(",")));
kwargs.put("all_versions", true);
if (reportErrors) {
kwargs.put("errors", "report");
}
return new LocalCall<>("pkg.info_installed", Optional.of(Arrays.asList(packages)),
Optional.of(kwargs), new TypeToken<Map<String, Xor<Info, List<Info>>>>(){});
} |
python | def delete_policy(self, scaling_group, policy):
"""
Deletes the specified policy from the scaling group.
"""
return self._manager.delete_policy(scaling_group=scaling_group,
policy=policy) |
python | def opsview_info(self, verbose=False):
'''
Get information about the current opsview instance
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#opsview_information
'''
url = '{}/{}'.format(self.rest_url, 'info')
return self.__auth_req_get(url, verbose=verbose) |
java | public void evaluate(XPathContext xctxt, FastStringBuffer buf,
int context,
org.apache.xml.utils.PrefixResolver nsNode)
{
buf.append(m_val);
} |
python | def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
state = self.splitter.saveState()
self.set_option('splitter_state', qbytearray_to_str(state))
filenames = []
editorstack = self.editorstacks[0]
active_project_path = None
if self.projects is not None:
active_project_path = self.projects.get_active_project_path()
if not active_project_path:
self.set_open_filenames()
else:
self.projects.set_project_filenames(
[finfo.filename for finfo in editorstack.data])
self.set_option('layout_settings',
self.editorsplitter.get_layout_settings())
self.set_option('windows_layout_settings',
[win.get_layout_settings() for win in self.editorwindows])
# self.set_option('filenames', filenames)
self.set_option('recent_files', self.recent_files)
# Stop autosave timer before closing windows
self.autosave.stop_autosave_timer()
try:
if not editorstack.save_if_changed(cancelable) and cancelable:
return False
else:
for win in self.editorwindows[:]:
win.close()
return True
except IndexError:
return True |
python | def get_names(cs):
"""Return list of every name."""
records = []
for c in cs:
records.extend(c.get('names', []))
return records |
java | @Override
@SuppressWarnings("unchecked")
public <E extends Entity> E getEntity(String attributeName, Class<E> clazz) {
Entity entity = delegate().getEntity(attributeName, clazz);
if (clazz.equals(FileMeta.class)) {
return entity != null ? (E) new FileMeta(newPretendingEntity(entity)) : null;
} else {
throw new UnsupportedOperationException("Can't return typed pretending entities");
}
} |
java | public String camelCase( String lowerCaseAndUnderscoredWord,
boolean uppercaseFirstLetter,
char... delimiterChars ) {
if (lowerCaseAndUnderscoredWord == null) return null;
lowerCaseAndUnderscoredWord = lowerCaseAndUnderscoredWord.trim();
if (lowerCaseAndUnderscoredWord.length() == 0) return "";
if (uppercaseFirstLetter) {
String result = lowerCaseAndUnderscoredWord;
// Replace any extra delimiters with underscores (before the underscores are converted in the next step)...
if (delimiterChars != null) {
for (char delimiterChar : delimiterChars) {
result = result.replace(delimiterChar, '_');
}
}
// Change the case at the beginning at after each underscore ...
return replaceAllWithUppercase(result, "(^|_)(.)", 2);
}
if (lowerCaseAndUnderscoredWord.length() < 2) return lowerCaseAndUnderscoredWord;
return "" + Character.toLowerCase(lowerCaseAndUnderscoredWord.charAt(0))
+ camelCase(lowerCaseAndUnderscoredWord, true, delimiterChars).substring(1);
} |
python | def choropleth():
"""
Returns
"""
path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv')
df=pd.read_csv(path)
del df['Unnamed: 0']
df['z']=[np.random.randint(0,100) for _ in range(len(df))]
return df |
python | def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes
"""
if not isinstance(key, rsa.RSAPrivateKey):
raise TypeError(
"The key must be an instance of rsa.RSAPrivateKey")
sig = key.sign(msg, self.padding, self.hash)
return sig |
java | public FutureData<DataSiftResult> start(FutureData<PreparedHistoricsQuery> query) {
if (query == null) {
throw new IllegalArgumentException("A valid PreparedHistoricsQuery is required");
}
final FutureData<DataSiftResult> future = new FutureData<>();
DataSiftResult h = new BaseDataSiftResult();
FutureResponse<PreparedHistoricsQuery> r = new FutureResponse<PreparedHistoricsQuery>() {
public void apply(PreparedHistoricsQuery data) {
if (data.getId() == null || data.getId().isEmpty()) {
throw new IllegalArgumentException("A valid PreparedHistoricsQuery is required");
}
start(data.getId(), future);
}
};
unwrapFuture(query, future, h, r);
return future;
} |
java | public PutMethodResult withMethodResponses(java.util.Map<String, MethodResponse> methodResponses) {
setMethodResponses(methodResponses);
return this;
} |
java | public static Collection<Channel> filterbyTags(
Collection<Channel> channels, Collection<String> tagNames) {
Collection<Channel> result = new ArrayList<Channel>();
Collection<Channel> input = new ArrayList<Channel>(channels);
for (Channel channel : input) {
if (channel.getTagNames().containsAll(tagNames)) {
result.add(channel);
}
}
return result;
} |
java | public static List<CompiledAutomaton> createAutomata(String prefix,
String regexp, Map<String, Automaton> automatonMap) throws IOException {
List<CompiledAutomaton> list = new ArrayList<>();
Automaton automatonRegexp = null;
if (regexp != null) {
RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + "\u0000*");
automatonRegexp = re.toAutomaton();
}
int step = 500;
List<String> keyList = new ArrayList<>(automatonMap.keySet());
for (int i = 0; i < keyList.size(); i += step) {
int localStep = step;
boolean success = false;
CompiledAutomaton compiledAutomaton = null;
while (!success) {
success = true;
int next = Math.min(keyList.size(), i + localStep);
List<Automaton> listAutomaton = new ArrayList<>();
for (int j = i; j < next; j++) {
listAutomaton.add(automatonMap.get(keyList.get(j)));
}
Automaton automatonList = Operations.union(listAutomaton);
Automaton automaton;
if (automatonRegexp != null) {
automaton = Operations.intersection(automatonList, automatonRegexp);
} else {
automaton = automatonList;
}
try {
compiledAutomaton = new CompiledAutomaton(automaton);
} catch (TooComplexToDeterminizeException e) {
log.debug(e);
success = false;
if (localStep > 1) {
localStep /= 2;
} else {
throw new IOException("TooComplexToDeterminizeException");
}
}
}
list.add(compiledAutomaton);
}
return list;
} |
java | static int maximumDistance(List<Point2D_I32> contour , int indexA , int indexB ) {
Point2D_I32 a = contour.get(indexA);
Point2D_I32 b = contour.get(indexB);
int best = -1;
double bestDistance = -Double.MAX_VALUE;
for (int i = 0; i < contour.size(); i++) {
Point2D_I32 c = contour.get(i);
// can't sum sq distance because some skinny shapes it maximizes one and not the other
// double d = Math.sqrt(distanceSq(a,c)) + Math.sqrt(distanceSq(b,c));
double d = distanceAbs(a,c) + distanceAbs(b,c);
if( d > bestDistance ) {
bestDistance = d;
best = i;
}
}
return best;
} |
java | public static int getWrappedValue(int value, int minValue, int maxValue) {
if (minValue >= maxValue) {
throw new IllegalArgumentException("MIN > MAX");
}
int wrapRange = maxValue - minValue + 1;
value -= minValue;
if (value >= 0) {
return (value % wrapRange) + minValue;
}
int remByRange = (-value) % wrapRange;
if (remByRange == 0) {
return 0 + minValue;
}
return (wrapRange - remByRange) + minValue;
} |
python | def save_outputs(self, rootpath='.', raw=False):
"""Saves TWI, UCA, magnitude and direction of slope to files.
"""
self.save_twi(rootpath, raw)
self.save_uca(rootpath, raw)
self.save_slope(rootpath, raw)
self.save_direction(rootpath, raw) |
java | protected void setJoin(String[] masterLabels, String masterColumn,
String dataColumn, List<String> masterData) {
setJoin(masterLabels, masterColumn, dataColumn, null, false, masterData);
} |
python | def set(self, instance, value, **kw): # noqa
"""Set the value of the refernce field
"""
ref = []
# The value is an UID
if api.is_uid(value):
ref.append(api.get_object_by_uid(value))
# The value is already an object
if api.is_at_content(value):
ref.append(value)
# The value is a dictionary
# -> handle it like a catalog query
if u.is_dict(value):
results = api.search(portal_type=self.allowed_types, **value)
ref = map(api.get_object, results)
# The value is a list
if u.is_list(value):
for item in value:
# uid
if api.is_uid(item):
ref.append(api.get_object_by_uid(item))
continue
# object
if api.is_at_content(item):
ref.append(api.get_object(item))
continue
# path
if api.is_path(item):
ref.append(api.get_object_by_path(item))
continue
# dict (catalog query)
if u.is_dict(item):
# If there is UID of objects, just use it.
uid = item.get('uid', None)
if uid:
obj = api.get_object_by_uid(uid)
ref.append(obj)
else:
results = api.search(portal_type=self.allowed_types, **item)
objs = map(api.get_object, results)
ref.extend(objs)
continue
# Plain string
# -> do a catalog query for title
if isinstance(item, basestring):
results = api.search(portal_type=self.allowed_types, title=item)
objs = map(api.get_object, results)
ref.extend(objs)
continue
# The value is a physical path
if api.is_path(value):
ref.append(api.get_object_by_path(value))
# Handle non multi valued fields
if not self.multi_valued:
if len(ref) > 1:
raise ValueError("Multiple values given for single valued "
"field {}".format(repr(self.field)))
else:
ref = ref[0]
return self._set(instance, ref, **kw) |
java | public static <T extends Message> Marshaller<T> jsonMarshaller(
final T defaultInstance, final Parser parser, final Printer printer) {
final Charset charset = Charset.forName("UTF-8");
return new Marshaller<T>() {
@Override
public InputStream stream(T value) {
try {
return new ByteArrayInputStream(printer.print(value).getBytes(charset));
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL
.withCause(e)
.withDescription("Unable to print json proto")
.asRuntimeException();
}
}
@SuppressWarnings("unchecked")
@Override
public T parse(InputStream stream) {
Builder builder = defaultInstance.newBuilderForType();
Reader reader = new InputStreamReader(stream, charset);
T proto;
try {
parser.merge(reader, builder);
proto = (T) builder.build();
reader.close();
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(e).asRuntimeException();
} catch (IOException e) {
// Same for now, might be unavailable
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence")
.withCause(e).asRuntimeException();
}
return proto;
}
};
} |
java | public void error(
XPathContext xctxt, int sourceNode, String msg, Object[] args)
throws javax.xml.transform.TransformerException
{
String fmsg = XSLMessages.createXPATHMessage(msg, args);
ErrorListener ehandler = xctxt.getErrorListener();
if (null != ehandler)
{
ehandler.fatalError(new TransformerException(fmsg,
(SAXSourceLocator)xctxt.getSAXLocator()));
}
else
{
SourceLocator slocator = xctxt.getSAXLocator();
System.out.println(fmsg + "; file " + slocator.getSystemId()
+ "; line " + slocator.getLineNumber() + "; column "
+ slocator.getColumnNumber());
}
} |
python | def directly_connected(self, ident):
'''Return a generator of labels connected to ``ident``.
``ident`` may be a ``content_id`` or a ``(content_id,
subtopic_id)``.
If no labels are defined for ``ident``, then the generator
will yield no labels.
Note that this only returns *directly* connected labels. It
will not follow transitive relationships.
:param ident: content id or (content id and subtopic id)
:type ident: ``str`` or ``(str, str)``
:rtype: generator of :class:`Label`
'''
content_id, subtopic_id = normalize_ident(ident)
return self.everything(include_deleted=False,
content_id=content_id,
subtopic_id=subtopic_id) |
java | public JsMessage next() throws SIResourceException, SISessionDroppedException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "next");
JsMessage msg = null;
Iterator<BrowseCursor> it = cursors.iterator();
while(it.hasNext() && msg==null)
msg = it.next().next();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "next");
return msg;
} |
java | public EClass getIfcIonConcentrationMeasure() {
if (ifcIonConcentrationMeasureEClass == null) {
ifcIonConcentrationMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(690);
}
return ifcIonConcentrationMeasureEClass;
} |
java | @Override
public boolean existsInStore(IEntityLock lock) throws LockingException {
Class entityType = lock.getEntityType();
String key = lock.getEntityKey();
Integer lockType = lock.getLockType();
Date expiration = lock.getExpirationTime();
String owner = lock.getLockOwner();
IEntityLock[] lockArray = getLockStore().find(entityType, key, lockType, expiration, owner);
return (lockArray.length > 0);
} |
python | def _srels_for(phys_reader, source_uri):
"""
Return |_SerializedRelationships| instance populated with
relationships for source identified by *source_uri*.
"""
rels_xml = phys_reader.rels_xml_for(source_uri)
return _SerializedRelationships.load_from_xml(
source_uri.baseURI, rels_xml) |
python | def post_message(name,
user=None,
device=None,
message=None,
title=None,
priority=None,
expire=None,
retry=None,
sound=None,
api_version=1,
token=None):
'''
Send a message to a PushOver channel.
.. code-block:: yaml
pushover-message:
pushover.post_message:
- user: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- title: Salt Returner
- device: phone
- priority: -1
- expire: 3600
- retry: 5
The following parameters are required:
name
The unique name for this event.
user
The user or group of users to send the message to. Must be ID of user, not name
or email address.
message
The message that is to be sent to the PushOver channel.
The following parameters are optional:
title
The title to use for the message.
device
The device for the user to send the message to.
priority
The priority for the message.
expire
The message should expire after specified amount of seconds.
retry
The message should be resent this many times.
token
The token for PushOver to use for authentication,
if not specified in the configuration options of master or minion.
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to PushOver: {0}'.format(message)
ret['result'] = None
return ret
if not user:
ret['comment'] = 'PushOver user is missing: {0}'.format(user)
return ret
if not message:
ret['comment'] = 'PushOver message is missing: {0}'.format(message)
return ret
result = __salt__['pushover.post_message'](
user=user,
message=message,
title=title,
device=device,
priority=priority,
expire=expire,
retry=retry,
token=token,
)
if result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message: {0}'.format(name)
return ret |
python | def _set_port_list(self, v, load=False):
"""
Setter method for port_list, mapped from YANG variable /tvf_domain_list_state/domain_list/port_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_port_list() directly.
YANG Description: Port with Tvf Domain binding
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=port_list.port_list, is_container='container', presence=False, yang_name="port-list", rest_name="port-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'nsm-tvf-port', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """port_list must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=port_list.port_list, is_container='container', presence=False, yang_name="port-list", rest_name="port-list", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'nsm-tvf-port', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-nsm-operational', defining_module='brocade-nsm-operational', yang_type='container', is_config=False)""",
})
self.__port_list = t
if hasattr(self, '_set'):
self._set() |
python | def properties(self):
"""
Properties for Introspection results.
:return:
:rtype:
"""
properties = defaultdict(list)
for pattern in self.patterns:
for key, values in pattern.properties.items():
extend_safe(properties[key], values)
for rule in self.rules:
for key, values in rule.properties.items():
extend_safe(properties[key], values)
return properties |
java | @Override
public AdminRemoveUserFromGroupResult adminRemoveUserFromGroup(AdminRemoveUserFromGroupRequest request) {
request = beforeClientExecution(request);
return executeAdminRemoveUserFromGroup(request);
} |
java | private PHSFellowshipSupplemental11 getPHSFellowshipSupplemental11() {
PHSFellowshipSupplemental11 phsFellowshipSupplemental = PHSFellowshipSupplemental11.Factory
.newInstance();
phsFellowshipSupplemental.setFormVersion(FormVersion.v1_1.getVersion());
phsFellowshipSupplemental.setApplicationType(getApplicationType());
phsFellowshipSupplemental.setAppendix(getAppendix());
phsFellowshipSupplemental.setAdditionalInformation(getAdditionalInformation());
phsFellowshipSupplemental
.setResearchTrainingPlan(getResearchTrainingPlan());
phsFellowshipSupplemental.setBudget(getBudget());
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(phsFellowshipSupplemental.toString().getBytes());
sortAttachments(byteArrayInputStream);
return phsFellowshipSupplemental;
} |
python | def _find_usage_applications(self):
"""find usage for ElasticBeanstalk applications"""
applications = self.conn.describe_applications()
self.limits['Applications']._add_current_usage(
len(applications['Applications']),
aws_type='AWS::ElasticBeanstalk::Application',
) |
java | @Override
public InsertsType getDefaultInsertsType() {
return InsertsType.valueOf(getDefaultProps().getOrDefault(PROPS_KEY_DEFAULT_INSERTS_TYPE,
InsertsType.BULK.toString()));
} |
java | @Override
public <T> void postProcess(T anyContext) {
Tuple2<List<String>, List<String>> dimsAndMetrics = (Tuple2<List<String>, List<String>>)anyContext;
List<String> dims = dimsAndMetrics._1();
List<String> metrics = dimsAndMetrics._2();
Iterator<Map.Entry<String, String>> colIter = fetchDimensions.entrySet().iterator();
while (colIter.hasNext()) {
Map.Entry<String, String> entry = colIter.next();
if (dims.contains(entry.getKey())) {
//No action.
} else if (metrics.contains(entry.getKey())) {
fetchMetrics.add(entry.getKey());
colIter.remove();
} else {//TODO: Handle error
}
}
} |
python | async def _do(self, ctx, times: int, *, command):
"""Repeats a command a specified number of times."""
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await self.bot.process_commands(msg) |
python | def _filters_to_query(self, includes, excludes, serializer, q=None):
"""
Construct Django Query object from request.
Arguments are dictionaries, which will be passed to Q() as kwargs.
e.g.
includes = { 'foo' : 'bar', 'baz__in' : [1, 2] }
produces:
Q(foo='bar', baz__in=[1, 2])
Arguments:
includes: TreeMap representing inclusion filters.
excludes: TreeMap representing exclusion filters.
serializer: serializer instance of top-level object
q: Q() object (optional)
Returns:
Q() instance or None if no inclusion or exclusion filters
were specified.
"""
def rewrite_filters(filters, serializer):
out = {}
for k, node in six.iteritems(filters):
filter_key, field = node.generate_query_key(serializer)
if isinstance(field, (BooleanField, NullBooleanField)):
node.value = is_truthy(node.value)
out[filter_key] = node.value
return out
q = q or Q()
if not includes and not excludes:
return None
if includes:
includes = rewrite_filters(includes, serializer)
q &= Q(**includes)
if excludes:
excludes = rewrite_filters(excludes, serializer)
for k, v in six.iteritems(excludes):
q &= ~Q(**{k: v})
return q |
python | def forum_topic_get_by_tag_for_user(self, tag=None, author=None):
"""Get all forum topics with a specific tag"""
if not tag:
return None
if author:
r = self._request('ebuio/forum/search/bytag/' + tag + '?u=' + author)
else:
r = self._request('ebuio/forum/search/bytag/' + tag)
if not r:
return None
retour = []
for data in r.json().get('data', []):
retour.append(data)
return retour |
python | def plot_options(cls, obj, percent_size):
"""
Given a holoviews object and a percentage size, apply heuristics
to compute a suitable figure size. For instance, scaling layouts
and grids linearly can result in unwieldy figure sizes when there
are a large number of elements. As ad hoc heuristics are used,
this functionality is kept separate from the plotting classes
themselves.
Used by the IPython Notebook display hooks and the save
utility. Note that this can be overridden explicitly per object
using the fig_size and size plot options.
"""
from .plot import MPLPlot
factor = percent_size / 100.0
obj = obj.last if isinstance(obj, HoloMap) else obj
options = Store.lookup_options(cls.backend, obj, 'plot').options
fig_size = options.get('fig_size', MPLPlot.fig_size)*factor
return dict({'fig_size':fig_size},
**MPLPlot.lookup_options(obj, 'plot').options) |
java | public RelationshipTuple[] getRelationships(Context context,
String pid,
String relationship)
throws ServerException {
return worker.getRelationships(context, pid, relationship);
} |
java | public Observable<EntityRole> getClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId) {
return getClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).map(new Func1<ServiceResponse<EntityRole>, EntityRole>() {
@Override
public EntityRole call(ServiceResponse<EntityRole> response) {
return response.body();
}
});
} |
java | protected final void firePropertyChange(
final String propertyName,
final Object oldValue,
final Object newValue) {
propertySupport.firePropertyChange(propertyName, oldValue, newValue);
} |
java | @Override
public String getFormatPattern(
DisplayStyle style,
Locale locale
) {
return GenericDatePatterns.get("chinese", style, locale); // always redirect to chinese calendar
} |
java | protected static boolean isFolder(CmsResource resource) throws CmsLoaderException {
I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(resource.getTypeId());
return resourceType.isFolder();
} |
java | public static <T> String join(T[] array, CharSequence conjunction, String prefix, String suffix) {
if (null == array) {
return null;
}
final StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (T item : array) {
if (isFirst) {
isFirst = false;
} else {
sb.append(conjunction);
}
if (ArrayUtil.isArray(item)) {
sb.append(join(ArrayUtil.wrap(item), conjunction, prefix, suffix));
} else if (item instanceof Iterable<?>) {
sb.append(IterUtil.join((Iterable<?>) item, conjunction, prefix, suffix));
} else if (item instanceof Iterator<?>) {
sb.append(IterUtil.join((Iterator<?>) item, conjunction, prefix, suffix));
} else {
sb.append(StrUtil.wrap(StrUtil.toString(item), prefix, suffix));
}
}
return sb.toString();
} |
java | public synchronized static void write(int fd, CharBuffer ... data) throws IllegalStateException, IOException {
write(fd, StandardCharsets.US_ASCII, data);
} |
java | public boolean existsResource(String resourcename, CmsResourceFilter filter) {
return m_securityManager.existsResource(m_context, addSiteRoot(resourcename), filter);
} |
java | static public List<ColumnMetaData> createList(ResultSetMetaData m) throws SQLException{
List<ColumnMetaData> result = new ArrayList<ColumnMetaData>(m.getColumnCount());
for (int i = 1; i <= m.getColumnCount(); i ++){
ColumnMetaData cm = new ColumnMetaData(m, i);
result.add(cm);
}
return result;
} |
java | public String getClassificationId(ScopCategory category) {
if(classificationId == null || classificationId.isEmpty()) {
return null;
}
int numParts = 0;
switch(category) {
case Family: numParts++;
case Superfamily: numParts++;
case Fold: numParts++;
case Class: numParts++; break;
default:
throw new IllegalArgumentException("Only Class, Fold, Superfamily, and Family are supported.");
}
int endChar = -1;
for(int i = 0;i<numParts-1;i++) {
endChar = classificationId.indexOf('.', endChar+1);
if(endChar<0) {
// Not enough items in the classification for this category
return null;
}
}
endChar = classificationId.indexOf('.', endChar+1);
if(endChar<0) {
// category goes to the end
return classificationId;
}
else {
return classificationId.substring(0, endChar);
}
} |
python | def get_db_prep_value(self, value, connection, prepared=False):
"""
Further conversion of Python value to database value for QUERYING.
This follows ``get_prep_value()``, and is for backend-specific stuff.
See notes above.
"""
log.debug("get_db_prep_value: {}, {}", value, type(value))
value = super().get_db_prep_value(value, connection, prepared)
if value is None:
return value
# log.debug("connection.settings_dict['ENGINE']: {}",
# connection.settings_dict['ENGINE'])
if connection.settings_dict['ENGINE'] == 'django.db.backends.sqlite3':
return python_utc_datetime_to_sqlite_strftime_string(value)
return value |
java | public void setTime(Date time)
{
String timeString = "";
if (time != null)
timeString = timeFormat.format(time);
jTextField3.setText(timeString);
jTimeButton1.setTargetDate(time);
} |
java | protected Map<Page, Double> getSimilarPages(String pPattern, int pSize) throws WikiApiException {
Title title = new Title(pPattern);
String pattern = title.getWikiStyleTitle();
// a mapping of the most similar pages and their similarity values
// It is returned by this method.
Map<Page, Double> pageMap = new HashMap<Page, Double>();
// holds a mapping of the best distance values to page IDs
Map<Integer, Double> distanceMap = new HashMap<Integer, Double>();
Session session = this.__getHibernateSession();
session.beginTransaction();
Iterator results = session.createQuery("select pml.pageID, pml.name from PageMapLine as pml").list().iterator();
while (results.hasNext()) {
Object[] row = (Object[]) results.next();
int pageID = (Integer) row[0];
String pageName = (String) row[1];
// this returns a similarity - if we want to use it, we have to change the semantics the ordering of the results
// double distance = new Levenshtein().getSimilarity(pageName, pPattern);
double distance = new LevenshteinStringDistance().distance(pageName, pattern);
distanceMap.put(pageID, distance);
// if there are more than "pSize" entries in the map remove the last one (it has the biggest distance)
if (distanceMap.size() > pSize) {
Set <Map.Entry<Integer,Double>> valueSortedSet = new TreeSet <Map.Entry<Integer,Double>> (new ValueComparator());
valueSortedSet.addAll(distanceMap.entrySet());
Iterator it = valueSortedSet.iterator();
// remove the first element
if (it.hasNext() ) {
// get the id of this entry and remove it in the distanceMap
Map.Entry entry = (Map.Entry)it.next();
distanceMap.remove(entry.getKey());
}
}
}
session.getTransaction().commit();
for (int pageID : distanceMap.keySet()) {
Page page = null;
try {
page = this.getPage(pageID);
} catch (WikiPageNotFoundException e) {
logger.error("Page with pageID " + pageID + " could not be found. Fatal error. Terminating.");
e.printStackTrace();
System.exit(1);
}
pageMap.put(page, distanceMap.get(pageID));
}
return pageMap;
} |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.MCDRG__RG_LENGTH:
return RG_LENGTH_EDEFAULT == null ? rgLength != null : !RG_LENGTH_EDEFAULT.equals(rgLength);
case AfplibPackage.MCDRG__TRIPLETS:
return triplets != null && !triplets.isEmpty();
}
return super.eIsSet(featureID);
} |
java | int nextSymbol() {
// Move to next group selector if required
if (++groupPosition % HUFFMAN_GROUP_RUN_LENGTH == 0) {
groupIndex++;
if (groupIndex == selectors.length) {
throw new DecompressionException("error decoding block");
}
currentTable = selectors[groupIndex] & 0xff;
}
final Bzip2BitReader reader = this.reader;
final int currentTable = this.currentTable;
final int[] tableLimits = codeLimits[currentTable];
final int[] tableBases = codeBases[currentTable];
final int[] tableSymbols = codeSymbols[currentTable];
int codeLength = minimumLengths[currentTable];
// Starting with the minimum bit length for the table, read additional bits one at a time
// until a complete code is recognised
int codeBits = reader.readBits(codeLength);
for (; codeLength <= HUFFMAN_DECODE_MAX_CODE_LENGTH; codeLength++) {
if (codeBits <= tableLimits[codeLength]) {
// Convert the code to a symbol index and return
return tableSymbols[codeBits - tableBases[codeLength]];
}
codeBits = codeBits << 1 | reader.readBits(1);
}
throw new DecompressionException("a valid code was not recognised");
} |
python | def match_precision(val, ref, *args, **kwargs):
"""
Returns a string version of a value *val* matching the significant digits as given in *ref*.
*val* might also be a numpy array. All remaining *args* and *kwargs* are forwarded to
``Decimal.quantize``. Example:
.. code-block:: python
match_precision(1.234, ".1") # -> "1.2"
match_precision(1.234, "1.") # -> "1"
match_precision(1.234, ".1", decimal.ROUND_UP) # -> "1.3"
a = np.array([1.234, 5.678, -9.101])
match_precision(a, ".1") # -> ["1.2", "5.7", "-9.1"]
"""
val = ensure_nominal(val)
if not is_numpy(val):
ret = _match_precision(val, ref, *args, **kwargs)
else:
# strategy: map into a flat list, create chararray with max itemsize, reshape
strings = [_match_precision(v, r, *args, **kwargs) for v, r in np.nditer([val, ref])]
ret = np.chararray(len(strings), itemsize=max(len(s) for s in strings))
ret[:] = strings
ret = ret.reshape(val.shape)
return ret |
python | def group_files_by_size_fast(fileslist, nbgroups, mode=1): # pragma: no cover
'''Given a files list with sizes, output a list where the files are grouped in nbgroups per cluster.
Pseudo-code for algorithm in O(n log(g)) (thank's to insertion sort or binary search trees)
See for more infos: http://cs.stackexchange.com/questions/44406/fast-algorithm-for-clustering-groups-of-elements-given-their-size-time/44614#44614
For each file:
- If to-fill list is empty or file.size > first-key(to-fill):
* Create cluster c with file in first group g1
* Add to-fill[file.size].append([c, g2], [c, g3], ..., [c, gn])
- Else:
* ksize = first-key(to-fill)
* c, g = to-fill[ksize].popitem(0)
* Add file to cluster c in group g
* nsize = ksize - file.size
* if nsize > 0:
. to-fill[nsize].append([c, g])
. sort to-fill if not an automatic ordering structure
'''
ftofill = SortedList()
ftofill_pointer = {}
fgrouped = [] # [] or {}
ford = sorted(fileslist.iteritems(), key=lambda x: x[1])
last_cid = -1
while ford:
fname, fsize = ford.pop()
#print "----\n"+fname, fsize
#if ftofill: print "beforebranch", fsize, ftofill[-1]
#print ftofill
if not ftofill or fsize > ftofill[-1]:
last_cid += 1
#print "Branch A: create cluster %i" % last_cid
fgrouped.append([])
#fgrouped[last_cid] = []
fgrouped[last_cid].append([fname])
if mode==0:
for g in xrange(nbgroups-1, 0, -1):
fgrouped[last_cid].append([])
if not fsize in ftofill_pointer:
ftofill_pointer[fsize] = []
ftofill_pointer[fsize].append((last_cid, g))
ftofill.add(fsize)
else:
for g in xrange(1, nbgroups):
try:
fgname, fgsize = ford.pop()
#print "Added to group %i: %s %i" % (g, fgname, fgsize)
except IndexError:
break
fgrouped[last_cid].append([fgname])
diff_size = fsize - fgsize
if diff_size > 0:
if not diff_size in ftofill_pointer:
ftofill_pointer[diff_size] = []
ftofill_pointer[diff_size].append((last_cid, g))
ftofill.add(diff_size)
else:
#print "Branch B"
ksize = ftofill.pop()
c, g = ftofill_pointer[ksize].pop()
#print "Assign to cluster %i group %i" % (c, g)
fgrouped[c][g].append(fname)
nsize = ksize - fsize
if nsize > 0:
if not nsize in ftofill_pointer:
ftofill_pointer[nsize] = []
ftofill_pointer[nsize].append((c, g))
ftofill.add(nsize)
return fgrouped |
python | def add_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handler to the global logger."""
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatter = ColoredFormatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')
else:
formatter = logging.Formatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
g_logger.addHandler(handler)
return handler |
python | def htmlReadDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options)
if ret is None:raise treeError('htmlReadDoc() failed')
return xmlDoc(_obj=ret) |
java | public void setRules(java.util.Collection<DataRetrievalRule> rules) {
if (rules == null) {
this.rules = null;
return;
}
this.rules = new java.util.ArrayList<DataRetrievalRule>(rules);
} |
java | private static void adjustCalibrated(FMatrixRMaj rectifyLeft, FMatrixRMaj rectifyRight,
FMatrixRMaj rectifyK,
RectangleLength2D_F32 bound, float scale) {
// translation
float deltaX = -bound.x0*scale;
float deltaY = -bound.y0*scale;
// adjustment matrix
SimpleMatrix A = new SimpleMatrix(3,3,true,new float[]{scale,0,deltaX,0,scale,deltaY,0,0,1});
SimpleMatrix rL = SimpleMatrix.wrap(rectifyLeft);
SimpleMatrix rR = SimpleMatrix.wrap(rectifyRight);
SimpleMatrix K = SimpleMatrix.wrap(rectifyK);
// remove previous calibration matrix
SimpleMatrix K_inv = K.invert();
rL = K_inv.mult(rL);
rR = K_inv.mult(rR);
// compute new calibration matrix and apply it
K = A.mult(K);
rectifyK.set(K.getFDRM());
rectifyLeft.set(K.mult(rL).getFDRM());
rectifyRight.set(K.mult(rR).getFDRM());
} |
java | public AsciiTable setPaddingLeftRight(int paddingLeft, int paddingRight){
for(AT_Row row : this.rows){
if(row.getType()==TableRowType.CONTENT){
row.setPaddingLeftRight(paddingLeft, paddingRight);
}
}
return this;
} |
java | public OvhOrder license_virtuozzo_new_duration_POST(String duration, OvhOrderableVirtuozzoContainerNumberEnum containerNumber, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableVirtuozzoVersionEnum version) throws IOException {
String qPath = "/order/license/virtuozzo/new/{duration}";
StringBuilder sb = path(qPath, duration);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "containerNumber", containerNumber);
addBody(o, "ip", ip);
addBody(o, "serviceType", serviceType);
addBody(o, "version", version);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} |
java | public static String getCurrentDateTime(final String localeLang, final String localeCountry, final String timezone, final String dateFormat) throws Exception {
final DateTimeFormatter formatter = getDateTimeFormatter(localeLang, localeCountry, timezone, dateFormat);
final DateTime datetime = DateTime.now();
if (DateTimeUtils.isUnix(localeLang)) {
Long unixSeconds = (long) Math.round(datetime.getMillis() / Constants.Miscellaneous.THOUSAND_MULTIPLIER);
return unixSeconds.toString();
}
return formatter.print(datetime);
} |
java | public static NameVirtualHostHandler virtualHost(final HttpHandler hostHandler, String... hostnames) {
NameVirtualHostHandler handler = new NameVirtualHostHandler();
for (String host : hostnames) {
handler.addHost(host, hostHandler);
}
return handler;
} |
python | def is_nested_list_like(obj):
"""
Check if the object is list-like, and that all of its elements
are also list-like.
.. versionadded:: 0.20.0
Parameters
----------
obj : The object to check
Returns
-------
is_list_like : bool
Whether `obj` has list-like properties.
Examples
--------
>>> is_nested_list_like([[1, 2, 3]])
True
>>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}])
True
>>> is_nested_list_like(["foo"])
False
>>> is_nested_list_like([])
False
>>> is_nested_list_like([[1, 2, 3], 1])
False
Notes
-----
This won't reliably detect whether a consumable iterator (e. g.
a generator) is a nested-list-like without consuming the iterator.
To avoid consuming it, we always return False if the outer container
doesn't define `__len__`.
See Also
--------
is_list_like
"""
return (is_list_like(obj) and hasattr(obj, '__len__') and
len(obj) > 0 and all(is_list_like(item) for item in obj)) |
python | def _handler_http(self, result):
"""
Handle the result of an http monitor
"""
monitor = result['monitor']
self.thread_debug("process_http", data=monitor, module='handler')
self.stats.http_handled += 1
# splunk will pick this up
logargs = {
'type':"metric",
'endpoint': result['url'],
'pipeline': monitor['pipeline'],
'service': monitor['service'],
'instance': monitor['instance'],
'status': result['status'],
'elapsed-ms': round(result['elapsedms'], 5),
'code': result['code']
}
self.NOTIFY(result['message'], **logargs)
# if our status has changed, also update Reflex Engine
if result['status'] != self.instances[monitor['instance']]['status']:
# do some retry/counter steps on failure?
self.instances[monitor['instance']]['status'] = result['status']
self.rcs.patch('instance',
monitor['instance'],
{'status': result['status']}) |
java | public final void assignmentOperator() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:730:5: ( EQUALS_ASSIGN | PLUS_ASSIGN | MINUS_ASSIGN | MULT_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | MOD_ASSIGN | LESS LESS EQUALS_ASSIGN | ( GREATER GREATER GREATER )=> GREATER GREATER GREATER EQUALS_ASSIGN | ( GREATER GREATER )=> GREATER GREATER EQUALS_ASSIGN )
int alt97=12;
switch ( input.LA(1) ) {
case EQUALS_ASSIGN:
{
alt97=1;
}
break;
case PLUS_ASSIGN:
{
alt97=2;
}
break;
case MINUS_ASSIGN:
{
alt97=3;
}
break;
case MULT_ASSIGN:
{
alt97=4;
}
break;
case DIV_ASSIGN:
{
alt97=5;
}
break;
case AND_ASSIGN:
{
alt97=6;
}
break;
case OR_ASSIGN:
{
alt97=7;
}
break;
case XOR_ASSIGN:
{
alt97=8;
}
break;
case MOD_ASSIGN:
{
alt97=9;
}
break;
case LESS:
{
alt97=10;
}
break;
case GREATER:
{
int LA97_11 = input.LA(2);
if ( (LA97_11==GREATER) ) {
int LA97_12 = input.LA(3);
if ( (LA97_12==GREATER) && (synpred47_DRL6Expressions())) {
alt97=11;
}
else if ( (LA97_12==EQUALS_ASSIGN) && (synpred48_DRL6Expressions())) {
alt97=12;
}
}
else {
if (state.backtracking>0) {state.failed=true; return;}
int nvaeMark = input.mark();
try {
input.consume();
NoViableAltException nvae =
new NoViableAltException("", 97, 11, input);
throw nvae;
} finally {
input.rewind(nvaeMark);
}
}
}
break;
default:
if (state.backtracking>0) {state.failed=true; return;}
NoViableAltException nvae =
new NoViableAltException("", 97, 0, input);
throw nvae;
}
switch (alt97) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:730:9: EQUALS_ASSIGN
{
match(input,EQUALS_ASSIGN,FOLLOW_EQUALS_ASSIGN_in_assignmentOperator4589); if (state.failed) return;
}
break;
case 2 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:731:7: PLUS_ASSIGN
{
match(input,PLUS_ASSIGN,FOLLOW_PLUS_ASSIGN_in_assignmentOperator4597); if (state.failed) return;
}
break;
case 3 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:732:7: MINUS_ASSIGN
{
match(input,MINUS_ASSIGN,FOLLOW_MINUS_ASSIGN_in_assignmentOperator4605); if (state.failed) return;
}
break;
case 4 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:733:7: MULT_ASSIGN
{
match(input,MULT_ASSIGN,FOLLOW_MULT_ASSIGN_in_assignmentOperator4613); if (state.failed) return;
}
break;
case 5 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:734:7: DIV_ASSIGN
{
match(input,DIV_ASSIGN,FOLLOW_DIV_ASSIGN_in_assignmentOperator4621); if (state.failed) return;
}
break;
case 6 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:735:7: AND_ASSIGN
{
match(input,AND_ASSIGN,FOLLOW_AND_ASSIGN_in_assignmentOperator4629); if (state.failed) return;
}
break;
case 7 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:736:7: OR_ASSIGN
{
match(input,OR_ASSIGN,FOLLOW_OR_ASSIGN_in_assignmentOperator4637); if (state.failed) return;
}
break;
case 8 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:737:7: XOR_ASSIGN
{
match(input,XOR_ASSIGN,FOLLOW_XOR_ASSIGN_in_assignmentOperator4645); if (state.failed) return;
}
break;
case 9 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:738:7: MOD_ASSIGN
{
match(input,MOD_ASSIGN,FOLLOW_MOD_ASSIGN_in_assignmentOperator4653); if (state.failed) return;
}
break;
case 10 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:739:7: LESS LESS EQUALS_ASSIGN
{
match(input,LESS,FOLLOW_LESS_in_assignmentOperator4661); if (state.failed) return;
match(input,LESS,FOLLOW_LESS_in_assignmentOperator4663); if (state.failed) return;
match(input,EQUALS_ASSIGN,FOLLOW_EQUALS_ASSIGN_in_assignmentOperator4665); if (state.failed) return;
}
break;
case 11 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:740:7: ( GREATER GREATER GREATER )=> GREATER GREATER GREATER EQUALS_ASSIGN
{
match(input,GREATER,FOLLOW_GREATER_in_assignmentOperator4682); if (state.failed) return;
match(input,GREATER,FOLLOW_GREATER_in_assignmentOperator4684); if (state.failed) return;
match(input,GREATER,FOLLOW_GREATER_in_assignmentOperator4686); if (state.failed) return;
match(input,EQUALS_ASSIGN,FOLLOW_EQUALS_ASSIGN_in_assignmentOperator4688); if (state.failed) return;
}
break;
case 12 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:741:7: ( GREATER GREATER )=> GREATER GREATER EQUALS_ASSIGN
{
match(input,GREATER,FOLLOW_GREATER_in_assignmentOperator4703); if (state.failed) return;
match(input,GREATER,FOLLOW_GREATER_in_assignmentOperator4705); if (state.failed) return;
match(input,EQUALS_ASSIGN,FOLLOW_EQUALS_ASSIGN_in_assignmentOperator4707); if (state.failed) return;
}
break;
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} |
java | @Override
public CPFriendlyURLEntry[] findByUuid_PrevAndNext(
long CPFriendlyURLEntryId, String uuid,
OrderByComparator<CPFriendlyURLEntry> orderByComparator)
throws NoSuchCPFriendlyURLEntryException {
CPFriendlyURLEntry cpFriendlyURLEntry = findByPrimaryKey(CPFriendlyURLEntryId);
Session session = null;
try {
session = openSession();
CPFriendlyURLEntry[] array = new CPFriendlyURLEntryImpl[3];
array[0] = getByUuid_PrevAndNext(session, cpFriendlyURLEntry, uuid,
orderByComparator, true);
array[1] = cpFriendlyURLEntry;
array[2] = getByUuid_PrevAndNext(session, cpFriendlyURLEntry, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
} |
python | def ub_to_str(string):
"""
converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str)
"""
if not isinstance(string, str):
if six.PY2:
return str(string)
else:
return string.decode()
return string |
java | public String encode() throws IOException {
FastStringWriter fsw = new FastStringWriter();
try {
ChartUtils.writeDataValue(fsw, "display", this.display, false);
ChartUtils.writeDataValue(fsw, "position", this.position, true);
ChartUtils.writeDataValue(fsw, "fullWidth", this.fullWidth, true);
ChartUtils.writeDataValue(fsw, "reverse", this.reverse, true);
if (this.labels != null) {
fsw.write(",\"labels\":" + this.labels.encode());
}
}
finally {
fsw.close();
}
return fsw.toString();
} |
python | def _inject_conversion(self, value, conversion):
"""
value: '{x}', conversion: 's' -> '{x!s}'
"""
t = type(value)
return value[:-1] + t(u'!') + conversion + t(u'}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.