language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def to_shell_manager(self, mpi_procs=1):
"""
Returns a new `TaskManager` with the same parameters as self but replace the :class:`QueueAdapter`
with a :class:`ShellAdapter` with mpi_procs so that we can submit the job without passing through the queue.
"""
my_kwargs = copy.deepco... |
java | public static MozuUrl getExtendedPropertiesUrl(Boolean draft, String orderId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/extendedproperties?draft={draft}");
formatter.formatUrl("draft", draft);
formatter.formatUrl("orderId", orderId);
return new MozuUrl(formatter.getResour... |
java | public static boolean hasFinishedCopying(File file) {
FileInputStream fis = null;
FileLock lock = null;
try {
fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
lock = fc.tryLock(0L, Long.MAX_VALUE, true);
} catch (IOException ioe) {
return false;
} finally {
IOUtils.close(fis... |
python | def start_agent(self, cfgin=True):
"""
CLI interface to start 12-factor service
"""
default_conf = {
"threads": {
"result": {
"number": 0,
"function": None
},
"worker": {
... |
python | def interpret_script(shell_script):
"""Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer:
shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE)
with open(shell_script) as handle:
for line in handle:
sys.stdout.writ... |
java | @SuppressWarnings("unchecked")
private BaseDescr lhsPatternBind(PatternContainerDescrBuilder<?, ?> ce,
final boolean allowOr) throws RecognitionException {
PatternDescrBuilder<?> pattern = null;
CEDescrBuilder<?, OrDescr> or = null;
BaseDescr result = null;
Token first =... |
python | def param_labels(self):
"""The param_names vector is a list each parameter's analysis_path, and is used for *GetDist* visualization.
The parameter names are determined from the class instance names of the model_mapper. Latex tags are
properties of each model class."""
paramnames_labels... |
java | public String convertIfcReflectanceMethodEnumToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
java | @Override
public RandomVariableDifferentiable mult(RandomVariable randomVariable) {
return new RandomVariableDifferentiableAADPathwise(
getValues().mult(randomVariable),
Arrays.asList(this, randomVariable),
OperatorType.MULT);
} |
java | public static Fraction getFraction(final int whole, final int numerator, final int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
throw new ArithmeticException("The denominator must not be... |
python | def _l_cv_weight_factor(self):
"""
Return multiplier for L-CV weightings in case of enhanced single site analysis.
Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b
"""
b = 0.0047 * sqrt(0) + 0.0023 / 2
c = 0.02609 / (self.catchment.record_length - 1)
... |
python | def get_all_descendants(parent):
"""Get all the descendants of a parent class, recursively."""
children = parent.__subclasses__()
descendants = children[:]
for child in children:
descendants += get_all_descendants(child)
return descendants |
python | def on_press(callback, suppress=False):
"""
Invokes `callback` for every KEY_DOWN event. For details see `hook`.
"""
return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress) |
java | public static ContextInfo toContextInfo(final ContextBase context, final ExceptionInfo error) {
final ContextInfo.Builder builder = ContextInfo.newBuilder()
.setContextId(context.getId())
.setEvaluatorId(context.getEvaluatorId())
.setParentId(context.getParentId().orElse(""))
.setEva... |
python | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in... |
python | def is_correct(self):
"""Check if this object configuration is correct ::
* Check if dateranges of timeperiod are valid
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False if at least one daterange
is not correct
:rt... |
java | public static FailHandler createFailHandlerFromString(final String failHandler) {
// determine fail handler implementation from string value
if (failHandler.equalsIgnoreCase(ReliableFailHandler.IDENTIFIER)) {
return new ReliableFailHandler();
}
else if (failHandler.equalsIgno... |
python | def set_image(self):
"""Parses image element and set values"""
temp_soup = self.full_soup
for item in temp_soup.findAll('item'):
item.decompose()
image = temp_soup.find('image')
try:
self.image_title = image.find('title').string
except AttributeErr... |
python | def initialize(self, params, repetition):
"""
Initialize experiment parameters and default values from configuration file.
Called by reset() at the beginning of each experiment and each repetition.
"""
self.name = params["name"]
self.dataDir = params.get("datadir", "data")
self.seed = params... |
python | def time_delta(self, end_datetime=None):
"""
Get a timedelta object
"""
start_datetime = self._parse_start_datetime('now')
end_datetime = self._parse_end_datetime(end_datetime)
seconds = end_datetime - start_datetime
ts = self.generator.random.randint(*sorted([0,... |
java | static private void append(StringBuilder tgt, String pfx, int dgt, long val) {
tgt.append(pfx);
if (dgt > 1) {
int pad = (dgt - 1);
for (long xa = val; xa > 9 && pad > 0; xa /= 10) {
pad--;
}
for (int xa = 0; xa < pad; xa++) {
tgt.append('0');
}
}
tgt.append(val);
} |
java | private File generateJsonFromIndividualESAs(Path jsonDirectory, Map<String, String> shortNameMap) throws IOException, RepositoryException, InstallException {
String dir = jsonDirectory.toString();
List<File> esas = (List<File>) data.get(INDIVIDUAL_ESAS);
File singleJson = new File(dir + "/Single... |
python | def imm_copy(imm, **kwargs):
'''
imm_copy(imm, a=b, c=d...) yields a persisent copy of the immutable object imm that differs from
imm only in that the parameters a, c, etc. have been changed to have the values b, d, etc.
If the object imm is persistent and no changes are made, imm is returned. If imm is... |
python | def group_values(self, group_name):
"""Return all distinct group values for given group."""
group_index = self.groups.index(group_name)
values = []
for key in self.data_keys:
if key[group_index] not in values:
values.append(key[group_index])
return val... |
java | @SuppressWarnings("unchecked")
public void addBeanContextServicesListener(BeanContextServicesListener listener)
{
if (listener == null)
{
throw new NullPointerException();
}
synchronized (bcsListeners)
{
bcsListeners.add(listener);
}
} |
python | def guesstype(timestr):
"""Tries to guess whether a string represents a time or a time delta and
returns the appropriate object.
:param timestr (required)
The string to be analyzed
"""
timestr_full = " {} ".format(timestr)
if timestr_full.find(" in ") != -1 or timestr_full.find(" ago ")... |
python | def _sign(self, data):
"""
Compute a signature string according to the CloudStack
signature method (hmac/sha1).
"""
# Python2/3 urlencode aren't good enough for this task.
params = "&".join(
"=".join((key, cs_encode(value)))
for key, value in sort... |
java | public void sendUnreadMessagesAck(ArrayList<AVIMMessage> messages, String conversationId) {
if (AVIMOptions.getGlobalOptions().isOnlyPushCount() && null != messages && messages.size() > 0) {
Long largestTimeStamp = 0L;
for (AVIMMessage message : messages) {
if (largestTimeStamp < message.getTime... |
java | public WasInformedBy newWasInformedBy(QualifiedName id, QualifiedName a2, QualifiedName a1, Collection<Attribute> attributes) {
WasInformedBy res=newWasInformedBy(id,a2,a1);
setAttributes(res, attributes);
return res;
} |
java | public void marshall(DeleteApiKeyRequest deleteApiKeyRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteApiKeyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteApiKeyRequest.ge... |
python | def conv_stack(name, x, mid_channels, output_channels, dilations=None,
activation="relu", dropout=0.0):
"""3-layer convolutional stack.
Args:
name: variable scope.
x: 5-D Tensor.
mid_channels: Number of output channels of the first layer.
output_channels: Number of output channels.
... |
java | @Override
public void commitJob(JobContext context) throws IOException {
super.commitJob(context);
// Get the destination configuration information.
Configuration conf = context.getConfiguration();
TableReference destTable = BigQueryOutputConfiguration.getTableReference(conf);
String destProjectI... |
python | def options(self, parser, env):
"""
Add options to command line.
"""
super(LeakDetectorPlugin, self).options(parser, env)
parser.add_option("--leak-detector-level", action="store",
default=env.get('NOSE_LEAK_DETECTOR_LEVEL'),
de... |
python | def invoice_items(self, **params):
"""Return a deferred."""
params['customer'] = self.id
return InvoiceItem.all(self.api_key, **params) |
java | public <T> T parse(JsonObject obj, Class<T> clazz) {
return gson.fromJson(obj, clazz);
} |
python | def _get_dependencies_from_json(ireq, sources):
"""Retrieves dependencies for the install requirement from the JSON API.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequireme... |
python | def filter_step(G, covY, pred, yt):
"""Filtering step of Kalman filter.
Parameters
----------
G: (dy, dx) numpy array
mean of Y_t | X_t is G * X_t
covX: (dx, dx) numpy array
covariance of Y_t | X_t
pred: MeanAndCov object
predictive distribution at time t
Returns
... |
java | @Override
public void destroy(Exception e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "destroy entry");
}
H2StreamProcessor stream;
for (Integer i : streamTable.keySet()) {
stream = streamTable.get(i);
// not... |
java | private void fvswap(int[] fmap, int yyp1, int yyp2, int yyn) {
while (yyn > 0) {
fswap(fmap, yyp1, yyp2);
yyp1++; yyp2++; yyn--;
}
} |
python | def _remote_download(self, url):
"""To download the remote plugin package,
there are four methods of setting filename according to priority,
each of which stops setting when a qualified filename is obtained,
and an exception is triggered when a qualified valid filename is ultimately ... |
python | def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
i... |
python | def file_observer(population, num_generations, num_evaluations, args):
"""Print the output of the evolutionary computation to a file.
This function saves the results of the evolutionary computation
to two files. The first file, which by default is named
'inspyred-statistics-file-<timestamp>.csv', ... |
java | void getBlockCrc(DataInputStream in, VersionAndOpcode versionAndOpcode)
throws IOException {
// header
BlockChecksumHeader blockChecksumHeader =
new BlockChecksumHeader(versionAndOpcode);
blockChecksumHeader.readFields(in);
final int namespaceId = blockChecksumHeader.getNamespaceId();
... |
python | def _load_plugins(self):
""" Attempts to load plugin modules according to the order of available
plugin directories.
"""
# import base plugin modules
try:
__import__('focus.plugin.modules')
#import focus.plugin.modules
except ImportError a... |
java | public static boolean isPresentAll(Optional<?>... optionals) {
for (Optional<?> optional : optionals)
if (!optional.isPresent())
return false;
return true;
} |
java | protected final List<T> findSortedByQuery(String query, String sort, Integer skip, Integer limit, Object... params) {
return this.dataAccess.findSortedByQuery(query, sort, skip, limit, params);
} |
java | @Nullable
public <T> Provider<T> getFactory(Class<T> classDefinition) {
//noinspection unchecked
return factories.getRootValue().get(classDefinition);
} |
java | public static List<Subunit> extractSubunits(Structure structure,
int absMinLen, double fraction, int minLen) {
// The extracted subunit container
List<Subunit> subunits = new ArrayList<Subunit>();
for (Chain c : structure.getPolyChains()) {
// Only take protein chains
if (c.isProtein()) {
Atom[] ca... |
python | def write(self, arg, **kwargs):
"""Write instance to file."""
if hasattr(arg, 'seek'):
self._tofile(arg, **kwargs)
else:
with open(arg, 'wb') as fid:
self._tofile(fid, **kwargs) |
java | public static <T> T query(Connection conn, String sql, RsHandler<T> rsh, Map<String, Object> paramMap) throws SQLException {
final NamedSql namedSql = new NamedSql(sql, paramMap);
return query(conn, namedSql.getSql(), rsh, namedSql.getParams());
} |
python | def on_message(self, unused_channel, basic_deliver, properties, body):
"""Called on receipt of a message from a queue.
Processes the message using the self._process method or function and positively
acknowledges the queue if successful. If processing is not succesful,
the message can ei... |
java | @Override
public void play(SourceFactory sourceFactory, Sink<Event> sink) {
LOG.info("Actions will be played using one source.");
Source source = null;
try {
source = sourceFactory.create();
} catch (InitializationFailedException e) {
LOG.error("Source initialization failed. Can not procee... |
python | def _handle_invalid_tag_start(self):
"""Handle the (possible) start of an implicitly closing single tag."""
reset = self._head + 1
self._head += 2
try:
if not is_single_only(self.tag_splitter.split(self._read())[0]):
raise BadRoute()
tag = self._re... |
python | def _handle_ctrl_c(self, *args):
"""Handle the keyboard interrupts."""
if self.anybar: self.anybar.change("exclamation")
if self._stop:
print("\nForced shutdown...")
raise SystemExit
if not self._stop:
hline = 42 * '='
print(
... |
python | def get_instance(self, payload):
"""
Build an instance of OutgoingCallerIdInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.Out... |
java | public int getRandomInt() {
Integer newInt = null;
do {
newInt = randomGenerator.nextInt();
} while(this.previousRandomInts.contains(newInt));
this.previousRandomInts.add(newInt);
return newInt.intValue();
} |
python | def nla_put_string(msg, attrtype, value):
"""Add string attribute to Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L674
Positional arguments:
msg -- Netlink message (nl_msg class instance).
attrtype -- attribute type (integer).
value -- bytes() or bytearray() va... |
python | def get_objective(self):
"""Gets the related objective.
return: (osid.learning.Objective) - the related objective
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.le... |
java | public synchronized void setString(String parameterName,
String x) throws SQLException {
setString(findParameterIndex(parameterName), x);
} |
java | public static Process runProcess(String... cmdParts) throws IOException {
return new ProcessBuilder(buildCommandline(cmdParts))
.inheritIO()
.start();
} |
python | def layer_sort(hmap):
"""
Find a global ordering for layers in a HoloMap of CompositeOverlay
types.
"""
orderings = {}
for o in hmap:
okeys = [get_overlay_spec(o, k, v) for k, v in o.data.items()]
if len(okeys) == 1 and not okeys[0] in orderings:
orderings[okeys[0]] = []
els... |
java | public List<String> getOrphansList() throws DuplicateBundlePathException {
// Create a mapping for every resource available
JoinableResourceBundleImpl tempBundle = new JoinableResourceOrphanBundleImpl("orphansTemp", "orphansTemp",
this.resourceExtension, new InclusionPattern(), Collections.singletonList(this.b... |
python | def get_gtf_db(gtf, in_memory=False):
"""
create a gffutils DB, in memory if we don't have write permissions
"""
db_file = gtf + ".db"
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
if not os.access(os.path.dirname(db_file), os.W_OK | os.X_OK):
in_memory = True
d... |
java | @Override
public BaseType extendGenericType()
{
BaseType []oldParams = getParameters();
BaseType []newParams = new BaseType[oldParams.length];
boolean isExtend = false;
for (int i = 0; i < newParams.length; i++) {
BaseType param = oldParams[i];
if (param instanceof ClassT... |
java | @Nonnull
public static <I> CompactDFA<I> randomICDFA(Random rand,
@Nonnegative int numStates,
Alphabet<I> inputs,
boolean minimize) {
CompactDFA<I> dfa = new Random... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'classifier_id') and self.classifier_id is not None:
_dict['classifier_id'] = self... |
python | def dump_in_memory_result(self, result, output_path):
"""Recursively dumps the result of our processing into files within the
given output path.
Args:
result: The in-memory result of our processing.
output_path: Full path to the folder into which to dump the files.
... |
java | public void comment(char ch[], int start, int length)
throws SAXException {
append(m_doc.createComment(new String(ch, start, length)));
} |
python | def read_raid_configuration(self, raid_config=None):
"""Read the logical drives from the system
:param raid_config: None in case of post-delete read or in case of
post-create a dictionary containing target raid
configuration data. This data stuctu... |
java | public Long count(Criteria<T, T> criteria) {
SingularAttribute<? super T, PK> id = getEntityManager().getMetamodel().entity(entityClass).getId(entityKey);
return criteria.select(Long.class, countDistinct(id))
.getSingleResult();
} |
java | public static PropertiesBuilder builder(KnowledgeComponentImplementationModel implementationModel) {
PropertiesModel propertiesModel = null;
if (implementationModel != null) {
propertiesModel = implementationModel.getProperties();
}
return new PropertiesBuilder(propertiesMode... |
java | private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length, for compatibility with 1.5 version
s.writeInt(Math.max(2, size + 1));
// Write out all... |
java | public DescribeConfigurationRecorderStatusResult withConfigurationRecordersStatus(ConfigurationRecorderStatus... configurationRecordersStatus) {
if (this.configurationRecordersStatus == null) {
setConfigurationRecordersStatus(new com.amazonaws.internal.SdkInternalList<ConfigurationRecorderStatus>(co... |
java | private void writeLengthToStream(int length, OutputStream out) throws IOException {
sharedByteBuffer.clear();
sharedByteBuffer.order(ByteOrder.BIG_ENDIAN).putInt(length);
sharedByteBuffer.flip();
out.write(sharedByteBuffer.array(), 0, Ints.BYTES);
sharedByteBuffer.order(byteOrder);
} |
python | def confirm_push(self, coord, version):
"""Ask the user if a push should be done for a particular version of a
particular coordinate. Return True if the push should be done"""
if not self.get_options().prompt:
return True
try:
isatty = os.isatty(sys.stdin.fileno())
except ValueError... |
java | private float clampMag(float value, float absMin, float absMax) {
final float absValue = Math.abs(value);
if (absValue < absMin) return 0;
if (absValue > absMax) return value > 0 ? absMax : -absMax;
return value;
} |
java | public void emptyElement (String uri, String localName)
throws SAXException
{
emptyElement(uri, localName, "", EMPTY_ATTS);
} |
python | def fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, xi, theta,
file_name=None):
r"""Return a fast function that returns a Hamiltonian as an array.
INPUT:
- ``Ep`` - A list with the electric field amplitudes (real or complex).
- ``epsilonp`` - A list of the polariz... |
java | @Override
public CommerceNotificationQueueEntry findByCommerceNotificationTemplateId_Last(
long commerceNotificationTemplateId,
OrderByComparator<CommerceNotificationQueueEntry> orderByComparator)
throws NoSuchNotificationQueueEntryException {
CommerceNotificationQueueEntry commerceNotificationQueueEntry = fet... |
java | void reportError(String msg, Element e) {
messager.printMessage(Diagnostic.Kind.ERROR, msg, e);
errorCount++;
} |
java | public CloseableReference<Bitmap> createBitmap(
Bitmap source,
int x,
int y,
int width,
int height,
@Nullable Matrix matrix,
boolean filter,
@Nullable Object callerContext) {
Preconditions.checkNotNull(source, "Source bitmap cannot be null");
checkXYSign(x, y);
... |
java | public static Optional<GeneratorSet> reduce( SystemInputDef inputDef, GeneratorSet genDef, SystemTestDef baseDef, ReducerOptions options)
{
// Create a new set of generators to be updated.
GeneratorSet genDefNew = genDef.cloneOf();
// Identify functions to reduce.
String function = options.getFunct... |
python | def namespace_splitter(self, value):
"""
Setter for **self.__namespace_splitter** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... |
python | def query_form_data(self):
"""
Get the formdata stored in the database for existing slice.
params: slice_id: integer
"""
form_data = {}
slice_id = request.args.get('slice_id')
if slice_id:
slc = db.session.query(models.Slice).filter_by(id=slice_id).one... |
java | public DeleteInvitationsResult withUnprocessedAccounts(Result... unprocessedAccounts) {
if (this.unprocessedAccounts == null) {
setUnprocessedAccounts(new java.util.ArrayList<Result>(unprocessedAccounts.length));
}
for (Result ele : unprocessedAccounts) {
this.unprocessed... |
java | public static void setExpirationTimes(long operationTTLMillis, long operationMaxIdleMillis, Record record,
MapConfig mapConfig, boolean consultMapConfig) {
long ttlMillis = pickTTLMillis(operationTTLMillis, record.getTtl(), mapConfig, consultMapConfig);
long max... |
java | public org.inferred.freebuilder.processor.property.Property.Builder addAccessorAnnotations(
Excerpt element) {
if (accessorAnnotations instanceof ImmutableList) {
accessorAnnotations = new ArrayList<>(accessorAnnotations);
}
accessorAnnotations.add(Objects.requireNonNull(element));
return (o... |
java | private boolean notAllowedEnd(String endTag) {
errorState = errorState && endElements.containsKey(endTag)
&& forbiddenIdEndElements.containsKey(endTag);
return errorState;
} |
java | @Override
public TopicConnection createTopicConnection() throws JMSException
{
String username = getStringProperty(Context.SECURITY_PRINCIPAL,null);
String password = getStringProperty(Context.SECURITY_CREDENTIALS,null);
return createTopicConnection(username,password);
} |
java | public ExtendedSwidProcessor setExtendedInformation(final JAXBElement<Object>... extendedInformationList) {
ExtendedInformationComplexType eict = new ExtendedInformationComplexType();
if (extendedInformationList.length > 0) {
for (JAXBElement<Object> extendedInformation : extendedInformation... |
java | @SuppressWarnings("unchecked")
public Paging<PlaylistSimplified> execute() throws
IOException,
SpotifyWebApiException {
return new PlaylistSimplified.JsonUtil().createModelObjectPaging(getJson(), "playlists");
} |
python | def run(self):
"""Run GapFill command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Calculate penalty if penalty file exists
... |
java | private void readAssignments(Project project)
{
Project.Assignments assignments = project.getAssignments();
if (assignments != null)
{
SplitTaskFactory splitFactory = new SplitTaskFactory();
TimephasedWorkNormaliser normaliser = new MSPDITimephasedWorkNormaliser();
for (P... |
python | def insert_multiple(self, documents):
"""
Insert multiple documents into the table.
:param documents: a list of documents to insert
:returns: a list containing the inserted documents' IDs
"""
doc_ids = []
data = self._read()
for doc in documents:
... |
python | def fetch_all_first_values(session: Session,
select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
... |
python | def parse_command(self, string):
"""Parse out any possible valid command from an input string."""
possible_command, _, rest = string.partition(" ")
# Commands are case-insensitive, stored as lowercase
possible_command = possible_command.lower()
if possible_command not in self.com... |
java | private boolean
findProperty() {
String prop;
List lserver = new ArrayList(0);
List lsearch = new ArrayList(0);
StringTokenizer st;
prop = System.getProperty("dns.server");
if (prop != null) {
st = new StringTokenizer(prop, ",");
while (st.hasMoreTokens())
addServer(st.nextToken(), lserver);
}
prop = S... |
python | def set_note(self, name='C', octave=4, dynamics={}):
"""Set the note to name in octave with dynamics.
Return the objects if it succeeded, raise an NoteFormatError
otherwise.
"""
dash_index = name.split('-')
if len(dash_index) == 1:
if notes.is_valid_note(name... |
java | public ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size) throws ValueOutOfRangeException, IllegalStateException {
return channelClient.incrementPayment(size, null, null);
} |
java | private List<HBaseDataWrapper> scanResults(final String tableName, List<HBaseDataWrapper> results)
throws IOException
{
if (fetchSize == null)
{
for (Result result : scanner)
{
HBaseDataWrapper data = new HBaseDataWrapper(tableName, result.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.