language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
protected boolean doHandleRequest(final Request request) {
boolean selected = getRequestValue(request);
boolean current = getValue();
boolean changed = current != selected;
if (changed) {
setData(selected);
}
return changed;
} |
java | @Override
public byte[] getValueAsbyteArray()
{
final byte[] result = new byte[size()];
for (int r = 0; r < size(); r++)
result[r] = getValue(r).byteValue();
return result;
}
/** {@inheritDoc} */
@Override
public Byte[] getValueAsByteArray()
{
f... |
java | protected void actionGoingToResources()
{
if (checker.canExtract())
{
for (final ExtractorListener listener : listeners)
{
listener.notifyStartExtraction(resourceType, resourceLocation);
}
state = ExtractorState.EXTRACTING;
}
... |
java | public static <E1,E2> Collection<E2> mapColl2(Iterable<E1> coll, Function<E1,E2> func, Collection<E2> newColl) {
for(E1 elem : coll) {
E2 img = func.f(elem);
if(img != null)
newColl.add(img);
}
return newColl;
} |
java | public static void deleteValue(Object target, String dPath) {
if (target instanceof JsonNode) {
deleteValue((JsonNode) target, dPath);
return;
}
String[] paths = splitDpath(dPath);
Object cursor = target;
// "seek"to the correct position
for (int i... |
python | def unpack_srec(record):
"""Unpack given Motorola S-Record record into variables.
"""
# Minimum STSSCC, where T is type, SS is size and CC is crc.
if len(record) < 6:
raise Error("record '{}' too short".format(record))
if record[0] != 'S':
raise Error(
"record '{}' not... |
python | def multiply(self, other, out=None):
"""Return ``out = self * other``.
If ``out`` is provided, the result is written to it.
See Also
--------
LinearSpace.multiply
"""
return self.space.multiply(self, other, out=out) |
java | public synchronized long read(long offset, final ByteBuffer buf) {
if (!validState) {
throw new InvalidStateException();
}
try {
int readed;
while (true) {
if (offset >= offsetOutputCommited) {
if (bufOutput.position() > 0) {
log.warn("WARN: autoflush forced");
flushBuffer();
}
... |
python | def getPackages(plist):
"""
Cleans up input from the command line tool and returns a list of package
names
"""
nlist = plist.split('\n')
pkgs = []
for i in nlist:
if i.find('===') > 0: continue
pkg = i.split()[0]
if pkg == 'Warning:': continue
elif pkg == 'Could': continue
elif pkg == 'Some': continu... |
python | def probably_prime(n, k=10):
"""
Miller-Rabin primality test
Input: n > 3
k: accuracy of test
Output: True if n is "probably prime", False if it is composite
From psuedocode at https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n == 2:
return True... |
python | def _label_select_column(self, select, column,
populate_result_map,
asfrom, column_clause_args,
name=None,
within_columns_clause=True):
"""produce labeled columns present in a select()."""
... |
python | def parse_home_face_offs(self):
"""
Parse only the home faceoffs
:returns: ``self`` on success, ``None`` otherwise
"""
self.__set_team_docs()
self.face_offs['home'] = FaceOffRep.__read_team_doc(self.__home_doc)
return self |
java | public PrintStream createStatusPrintStream() {
return new PrintStream(new OutputStream() {
StringBuffer sb = new StringBuffer();
@Override
public void write(int b) throws IOException {
if (b == '\n') {
String str = sb.toString();
sb.delete(0, sb.length());
writeLine(str);
} else {
... |
java | public static String createFaceHtml(String text, String imageClass, HorizontalAlignmentConstant align) {
StringBuffer sb = new StringBuffer();
if (align == HasHorizontalAlignment.ALIGN_LEFT) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(text)) {
sb.append(text.trim());
... |
python | def load_backends(self):
"""
Loads all the backends setup in settings.py.
"""
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
... |
python | def uniformVectorRDD(sc, numRows, numCols, numPartitions=None, seed=None):
"""
Generates an RDD comprised of vectors containing i.i.d. samples drawn
from the uniform distribution U(0.0, 1.0).
:param sc: SparkContext used to create the RDD.
:param numRows: Number of Vectors in th... |
python | def _datetime(self):
"""Conversion of the Date object into a :py:class:`datetime.datetime`.
The resulting object is a timezone-naive instance in the REF_SCALE time-scale
"""
if 'dt' not in self._cache.keys():
self._cache['dt'] = self.MJD_T0 + timedelta(days=self._d, seconds=... |
java | public void write(File file) throws IOException {
Assert.state(this.pid != null, "No PID available");
createParentFolder(file);
if (file.exists()) {
assertCanOverwrite(file);
}
try (FileWriter writer = new FileWriter(file)) {
writer.append(this.pid);
}
} |
python | def _remove_remote_data_bags():
"""Remove remote data bags, so it won't leak any sensitive information"""
data_bags_path = os.path.join(env.node_work_path, 'data_bags')
if exists(data_bags_path):
sudo("rm -rf {0}".format(data_bags_path)) |
python | def crypto_pwhash_scryptsalsa208sha256_str(
passwd, opslimit=SCRYPT_OPSLIMIT_INTERACTIVE,
memlimit=SCRYPT_MEMLIMIT_INTERACTIVE):
"""
Derive a cryptographic key using the ``passwd`` and ``salt``
given as input, returning a string representation which includes
the salt and the tuning param... |
java | static private double lock(double value) {
if (value <= -1.633123935319537E16d) return Double.NEGATIVE_INFINITY; // lock onto -infinity
if (value >= 1.633123935319537E16d) return Double.POSITIVE_INFINITY; // lock onto infinity
if (value > -Math.PI - EPSILON && value < -Math.PI + EPSILON) ret... |
java | @Override
public ResourceReference parse(String rawReference)
{
ResourceReference parsedResourceReference = null;
// Step 1: Find the type parser matching the specified prefix type (if any).
int pos = rawReference.indexOf(TYPE_SEPARATOR);
if (pos > -1) {
String typeP... |
java | @Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.MEDIA_EJECT_CONTROL__RESERVED:
setReserved((Integer)newValue);
return;
case AfplibPackage.MEDIA_EJECT_CONTROL__EJ_CTRL:
setEjCtrl((Integer)newValue);
return;
}
super.eSet(featureID, newValue... |
python | def loads(s):
"""Read a .glyphs file from a (unicode) str object, or from
a UTF-8 encoded bytes object.
Return a GSFont object.
"""
p = Parser(current_type=glyphsLib.classes.GSFont)
logger.info("Parsing .glyphs file")
data = p.parse(s)
return data |
python | def from_buffer(string, serverEndpoint=ServerEndpoint, xmlContent=False, headers=None, config_path=None):
'''
Parses the content from buffer
:param string: Buffer value
:param serverEndpoint: Server endpoint. This is optional
:param xmlContent: Whether or not XML content be requested.
... |
java | @Override
public Builder claimFrom(String jsonOrJwt) throws InvalidTokenException {
isValidToken(jsonOrJwt);
String decoded = jsonOrJwt;
if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
}
boolean isJson = JwtUtils.is... |
python | def _check_copy_for(self):
"""Check the value of copy_for and make appropriate copies."""
if not self._bundle:
return
# read the following at your own risk - I just wrote it and it still
# confuses me and baffles me that it works
for param in self.to_list():
... |
java | public static Character toCharacter(Object o) throws PageException {
if (o instanceof Character) return (Character) o;
return new Character(toCharValue(o));
} |
python | def _api_views(self, plugin):
"""Glances API RESTful implementation.
Return the JSON views of a given plugin
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
if plugin n... |
java | public void reset(SessionConfig config) {
if (mState != STATE.UNINITIALIZED)
throw new IllegalArgumentException("reset called in invalid state");
mState = STATE.INITIALIZING;
mHandler.sendMessage(mHandler.obtainMessage(MSG_RESET, config));
} |
python | def format_choicefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.conf... |
python | def _check_triple(self, triple):
"""compare triple to ontology, return error or None"""
subj, pred, obj = triple
if self._should_ignore_predicate(pred):
log.info("Ignoring triple with predicate '{}'"
.format(self._field_name_from_uri(pred)))
return
... |
python | def bin_open(fname: str):
"""
Returns a file descriptor for a plain text or gzipped file, binary read mode
for subprocess interaction.
:param fname: The filename to open.
:return: File descriptor in binary read mode.
"""
if fname.endswith(".gz"):
return gzip.open(fname, "rb")
re... |
python | def is_text_extractor_available(extension: str) -> bool:
"""
Is a text extractor available for the specified extension?
"""
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
... |
java | public static void main(String[] args)
{
try {
// read the command line options and run the client
final Map options = new HashMap();
if (parseOptions(args, options))
new PropClient().run(options);
}
catch (final Throwable t) {
if (t.getMessage() != null)
System.out.println(t.getMes... |
java | public static boolean equalsIgnoreCase(String str1, String... strs) {
if (strs != null) {
for (String element : strs) {
if ((str1 != null && str1.equalsIgnoreCase(element)) || (str1 == null && element == null)) {
return true; // found
}
... |
python | def add_rr_ce_entry(self, length):
# type: (int) -> Tuple[bool, rockridge.RockRidgeContinuationBlock, int]
'''
Add a new Rock Ridge Continuation Entry to this PVD; see
track_rr_ce_entry() above for why we track these in the PVD. This
method is used to add a new Continuation Entr... |
python | def rx_int_extra(rxmatch):
"""
We didn't just match an int but the int is what we need.
"""
rxmatch = re.search("\d+", rxmatch.group(0))
return int(rxmatch.group(0)) |
python | def exponential_terms(order, variables, data):
"""
Compute exponential expansions.
Parameters
----------
order: range or list(int)
A list of exponential terms to include. For instance, [1, 2]
indicates that the first and second exponential terms should be added.
To retain th... |
python | def prepare_input_data(self, X):
"""
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask.
"""
X = check_array(X, force_all_finite=False)
if X.dtype != "f" and X.dtype != "d":
X = X.astype(float)
... |
python | def _set_raw_params(self, sep):
"""Set the output raw parameters section
:param sep: the separator of current style
"""
raw = '\n'
if self.dst.style['out'] == 'numpydoc':
spaces = ' ' * 4
with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spa... |
java | public void handleNewCandlestick(final BitfinexCandlestickSymbol currencyPair, final BitfinexCandle tick) {
updateChannelHeartbeat(currencyPair);
candleCallbacks.handleEvent(currencyPair, tick);
} |
python | def from_xmrs(cls, xmrs, **kwargs):
"""
Facilitate conversion among subclasses.
Args:
xmrs (:class:`Xmrs`): instance to convert from; possibly
an instance of a subclass, such as :class:`Mrs` or
:class:`Dmrs`
**kwargs: additional keyword ar... |
python | def prioritized_mux(selects, vals):
"""
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
... |
python | def set_fft_params(func):
"""Decorate a method to automatically convert quantities to samples
"""
@wraps(func)
def wrapped_func(series, method_func, *args, **kwargs):
"""Wrap function to normalize FFT params before execution
"""
if isinstance(series, tuple):
data = se... |
python | def kent_mean(dec=None, inc=None, di_block=None):
"""
Calculates the Kent mean and associated statistical parameters from either a list of
declination values and a separate list of inclination values or from a
di_block (a nested list a nested list of [dec,inc,1.0]). Returns a
dictionary with the Ken... |
python | def boundary_polygon(self, time):
"""
Get coordinates of object boundary in counter-clockwise order
"""
ti = np.where(time == self.times)[0][0]
com_x, com_y = self.center_of_mass(time)
# If at least one point along perimeter of the mask rectangle is unmasked, find_boundar... |
python | def tile(self, z, x, y):
"""
Download the specified tile from `tiles_url`
"""
logger.debug(_("Download tile %s") % ((z, x, y),))
# Render each keyword in URL ({s}, {x}, {y}, {z}, {size} ... )
size = self.tilesize
s = self.tiles_subdomains[(x + y) % len(self.tiles_... |
python | def websocket_safe_read(self):
"""Returns data if available, otherwise ''. Newlines indicate multiple messages """
data = ''
while True:
try:
data += '{0}\n'.format(self.websocket.recv())
except WebSocketException as e:
if isinstance(e, Web... |
java | public ApiResponse<List<CorporationShareholdersResponse>> getCorporationsCorporationIdShareholdersWithHttpInfo(
Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token)
throws ApiException {
com.squareup.okhttp.Call call = getCorporationsCorporationIdShar... |
python | def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case SimpleAntlrPackage.PREDICATED__PREDICATE:
return getPredicate();
case SimpleAntlrPackage.PREDICATED__ELEMENT:
return getElement();
}
return super.eGet(featureID, res... |
java | public PropertyDefinitionDataBuilder newPropertyDefinitionDataBuilder()
{
PropertyDefinitionDataBuilder property = new PropertyDefinitionDataBuilder(this.name);
this.propertyDefinitionDataBuilders.add(property);
return property;
} |
java | public static Config loadConfig(ConfigParseOptions parseOptions,
ConfigResolveOptions resolveOptions, Reader configReader) {
return ConfigFactory.parseReader(configReader, parseOptions).resolve(resolveOptions);
} |
python | def precheck():
"""
Verify project runtime dependencies
"""
cfg_path = local_config['PROJECT']['CONFIG_PATH']
# enable or disable logging based on config/ defaults
logging = set_logging(local_config)
if os.path.exists(cfg_path):
logger.info('%s: config_path parameter: %s' % (inspect... |
python | def getPeersByClassName(self, className):
'''
getPeersByClassName - Gets peers (elements on same level) with a given class name
@param className - classname must contain this name
@return - None if no parent element (error condition), otherwise a TagCollection of peers that... |
java | public static int compareVersions(String v1, String v2) {
// Remove the SNAPSHOT version.
//final String fixedv1 = v1.replaceFirst("-SNAPSHOT$", ""); //$NON-NLS-1$ //$NON-NLS-2$
//final String fixedv2 = v2.replaceFirst("-SNAPSHOT$", ""); //$NON-NLS-1$ //$NON-NLS-2$
//final Version vobject1 = Version.parseVersio... |
python | def to_mongo(self):
"""Translate projection to MongoDB query form.
:return: Dictionary to put into a MongoDB JSON query
:rtype: dict
"""
d = copy.copy(self._fields)
for k, v in self._slices.items():
d[k] = {'$slice': v}
return d |
java | public static EnumMap<FacebookParam, CharSequence> extractFacebookParams(Map<CharSequence, CharSequence> reqParams) {
if (null == reqParams)
return null;
EnumMap<FacebookParam, CharSequence> result =
new EnumMap<FacebookParam, CharSequence>(FacebookParam.class);
for (Map.Entry<CharSequence, Cha... |
python | def _ranging_attributes(attributes, param_class):
"""
Checks if there is a continuous range
"""
next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes}
in_first = attributes.difference(next_attributes)
in_second = next_attributes.difference(attributes)
if l... |
python | def resolve(self, sourcepath, paths, library_paths=None):
"""
Resolve given paths from given base paths
Return resolved path list.
Note:
Resolving strategy is made like libsass do, meaning paths in
import rules are resolved from the source file where the import
... |
python | def delete(self, main_type, sub_type, unique_id, owner=None):
"""
Deletes the Indicator/Group/Victim or Security Label
Args:
main_type:
sub_type:
unique_id:
owner:
"""
params = {'owner': owner} if owner else {}
if not sub_ty... |
java | public Icon getIcon (String iconSet, int index)
{
try {
// see if the tileset is already loaded
TileSet set = _icons.get(iconSet);
// load it up if not
if (set == null) {
String path = _config.getProperty(iconSet + PATH_SUFFIX);
... |
python | def query_item(name, query_string, order='Rank'):
'''
Query a type of record for one or more items. Requires a valid query string.
See https://rally1.rallydev.com/slm/doc/webservice/introduction.jsp for
information on query syntax.
CLI Example:
.. code-block:: bash
salt myminion rally... |
java | protected void generalHelp(IsInfoSetFT info){
//collect all commands belonging to a particular category
String defKey = "__standard";
Map<String, TreeMap<String, SkbShellCommand>> cat2Cmd = new TreeMap<>();
for(CommandInterpreter ci : this.skbShell.getCommandMap().values()){
for(SkbShellCommand ssc : ci.getC... |
python | def interval_timed(interval):
'''Interval timer decorator.
Taken from: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds/12435256
'''
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
stopped = Event()
def... |
python | def _process_ufunc_inputs(self, input_args, outputs):
'''
Helper function for __array_ufunc__ that deals with the input/output checks and determines
if this should be relegated to numpy's implementation or not.
@input_args: args to __array_ufunc__
@outputs: specified outputs.
... |
java | public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) {
if (Build.VERSION.SDK_INT >= 11) {
final boolean hasTransformer = transformer != null;
final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
mPageTransfo... |
python | def find_1den_files(self):
"""
Abinit adds the idir-ipert index at the end of the 1DEN file and this breaks the extension
e.g. out_DEN1. This method scans the files in the directories and returns a list of namedtuple
Each named tuple gives the `path` of the 1DEN file and the `pertcase` i... |
python | def did_composer_install(dir):
'''
Test to see if the vendor directory exists in this directory
dir
Directory location of the composer.json file
CLI Example:
.. code-block:: bash
salt '*' composer.did_composer_install /var/www/application
'''
lockFile = "{0}/vendor".forma... |
python | def initialize_unordered_bulk_op(self, bypass_document_validation=False):
"""**DEPRECATED** - Initialize an unordered batch of write operations.
Operations will be performed on the server in arbitrary order,
possibly in parallel. All operations will be attempted.
:Parameters:
... |
java | public InlineResponse2002 subscribe(StatisticsSubscribeData statisticsSubscribeData) throws ApiException {
ApiResponse<InlineResponse2002> resp = subscribeWithHttpInfo(statisticsSubscribeData);
return resp.getData();
} |
java | private Triple convertToInternalReference(final Triple t,
final IdentifierConverter<Resource, FedoraResource> idTranslator,
final IdentifierConverter<Resource, FedoraResource> internalIdTranslator) {
if (t.getObject().isURI()) {
final Resource object = createResource(t.getObj... |
python | def set_coordsys(self):
"""
Mapping to astropy's coordinate system name
# TODO: needs expert attention (Most reference systems are not mapped)
"""
if self.coordsys.lower() in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[self.coordsys.lower()] |
python | def insert(self, instance):
""" inserts a unit of work into MongoDB.
:raises DuplicateKeyError: if such record already exist """
assert isinstance(instance, UnitOfWork)
collection = self.ds.connection(COLLECTION_UNIT_OF_WORK)
try:
return collection.insert_one(instance... |
java | private boolean verifyFingreprint() {
try {
PackageInfo info = context
.getPackageManager()
.getPackageInfo(NOKIA_INSTALLER, PackageManager.GET_SIGNATURES);
if (info.signatures.length == 1) {
byte[] cert = info.signatures[0].toByt... |
python | def _refresh(self, _):
"""Refresh self.access_token.
Args:
_: (ignored) A function matching httplib2.Http.request's signature.
"""
# pylint: disable=import-error
from google.appengine.api import app_identity
try:
token, _ = app_identity.get_access_t... |
python | def _transform_list_args(self, args):
# type: (dict) -> None
"""Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments.
"""
if '_limit' in args:
args['limit'] = int(args['_limit'])
del args['_limit']
... |
python | def new_from_list(cls, content, fill_title=True, **kwargs):
"""Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title... |
java | @Override
public int getIndex(String qName)
{
int cix = qName.indexOf(':');
int acount = mContext.getAttributeCount();
if (cix < 0) { // no prefix
for (int i = 0; i < acount; ++i) {
if (qName.equals(mContext.getAttributeLocalName(i))) {
Str... |
python | def _deserialize(self):
"""Try and deserialize a response body based upon the specified
content type.
:rtype: mixed
"""
if not self._responses or not self._responses[-1].body:
return None
if 'Content-Type' not in self._responses[-1].headers:
retu... |
python | def write_cfg(path, value) -> None:
"""
:param path: example: "/.rwmeta/developer_settings.json"
:param value: dict
"""
full_path = __build_path(path)
with open(full_path, 'w') as myfile:
myfile.write(json.dumps(value)) |
python | def require_fresh_games(self, number_fresh):
"""Require a given number of fresh games to be played.
Args:
number_fresh: integer, number of new fresh games needed
Increments the cell `table_state=metadata:wait_for_game_number`
by the given number of games. This will cause
... |
java | public final static void writeInt(BytesRef dst, int i) {
dst.bytes[dst.offset] = ((byte) (i >> 24));
dst.bytes[dst.offset + 1] = ((byte) (i >> 16));
dst.bytes[dst.offset + 2] = ((byte) (i >> 8));
dst.bytes[dst.offset + 3] = ((byte) i);
dst.offset += 4;
} |
python | def get_pk_attrnames(obj) -> List[str]:
"""
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns
"""
return [attrname
for attrname, column in gen_columns(obj)
... |
java | protected void recycleChildren(RecyclerView.Recycler recycler, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return;
}
if (DEBUG) {
Log.d(TAG, "Recycling " + Math.abs(startIndex - endIndex) + " items");
}
if (endIndex > startIndex) {
... |
python | def weather_at_places_in_bbox(self, lon_left, lat_bottom, lon_right, lat_top,
zoom=10, cluster=False):
"""
Queries the OWM Weather API for the weather currently observed by
meteostations inside the bounding box of latitude/longitude coords.
:param lat_t... |
python | def cover_update(self, photo, **kwds):
"""
Endpoint: /album/<album_id>/cover/<photo_id>/update.json
Update the cover photo of this album.
"""
result = self._client.album.cover_update(self, photo, **kwds)
self._replace_fields(result.get_fields())
self._update_fiel... |
java | protected void submit() {
if (m_userinfoNoEditGroup.getRows().size() != m_addInfoReadOnly.size()) {
List<String> currentKeys = getKeyListFromGroup(m_userinfoNoEditGroup);
for (String key : m_addInfoReadOnly.keySet()) {
if (!currentKeys.contains(key)) {
... |
python | def p_generate_if(self, p):
'generate_if : IF LPAREN cond RPAREN gif_true_item ELSE gif_false_item'
p[0] = IfStatement(p[3], p[5], p[7], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
java | private static void deleteBackups(final List<File> files, final int count) {
if (count >= 0) {
for (int i = files.size() - Math.max(0, files.size() - count); i < files.size(); ++i) {
if (!files.get(i).delete()) {
InternalLogger.log(Level.WARN, "Failed to delete log file '" + files.get(i).getAbsolutePath()... |
java | public CreateJobRequest withInputs(JobInput... inputs) {
if (this.inputs == null) {
setInputs(new com.amazonaws.internal.SdkInternalList<JobInput>(inputs.length));
}
for (JobInput ele : inputs) {
this.inputs.add(ele);
}
return this;
} |
java | public static <T> T load(String path, Class<T> type) {
return load(path, type, null, false);
} |
python | def rpc_connect(self):
"""Connect to a coin daemon's JSON RPC interface.
Returns:
bool: True if successfully connected, False otherwise.
"""
if self.coin in COINS:
rpc_url = COINS[self.coin]["rpc-url"] + ":"
if self.testnet:
rpc_url += ... |
java | public static void ensureNotError(ObjectMapper mapper, JsonNode resourceNode) {
if (resourceNode != null && resourceNode.hasNonNull(JSONAPISpecConstants.ERRORS)) {
try {
throw new ResourceParseException(ErrorUtils.parseError(mapper, resourceNode, Errors.class));
} catch (JsonProcessingException e) {
thr... |
java | public static String overlayString(String text, String overlay, int start, int end) {
return new StringBuffer(start + overlay.length() + text.length() - end + 1)
.append(text.substring(0, start))
.append(overlay)
.append(text.substring(end))
.toString();
} |
java | public void setValueEntity(I_CmsEntityRenderer renderer, CmsEntity value) {
if (m_hasValue) {
throw new RuntimeException("Value has already been set");
}
m_hasValue = true;
m_isSimpleValue = false;
FlowPanel entityPanel = new FlowPanel();
m_widgetHold... |
python | def execute_command(self, req, **kwargs):
"""
Execute command and return CliResponse
:param req: String, command to be executed in DUT, or CliRequest, command class which
contains all configurations like timeout.
:param kwargs: Configurations (wait, timeout) which will be used w... |
java | public ServiceRequestContext build() {
// Determine the client address; use remote address unless overridden.
final InetAddress clientAddress;
if (this.clientAddress != null) {
clientAddress = this.clientAddress;
} else {
clientAddress = remoteAddress().getAddress... |
python | def LabelValueTable(self, keys=None):
"""Return LabelValue with FSM derived keys."""
keys = keys or self.superkey
# pylint: disable=E1002
return super(CliTable, self).LabelValueTable(keys) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.