language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def addChild(self, cur):
"""Add a new node to @parent, at the end of the child (or
property) list merging adjacent TEXT nodes (in which case
@cur is freed) If the new node is ATTRIBUTE, it is added
into properties instead of children. If there is an
attribute with equal ... |
java | public final void cmov(CONDITION cc, Register dst, Register src)
{
emitX86(conditionToCMovCC(cc), dst, src);
} |
java | public static Map<String, String> nodeData(final INodeEntry nodeentry) {
final HashMap<String, String> data = new HashMap<String, String>();
if(null!=nodeentry) {
HashSet<String> skipProps = new HashSet<String>();
skipProps.addAll(Arrays.asList("nodename", "osName", "osVersion", ... |
python | def smooth_hanning(x, size=11):
"""smooth a 1D array using a hanning window with requested size."""
if x.ndim != 1:
raise ValueError, "smooth_hanning only accepts 1-D arrays."
if x.size < size:
raise ValueError, "Input vector needs to be bigger than window size."
if size < 3:
re... |
python | def main():
""" Run the simulation """
parser = argparse.ArgumentParser(prog='opentrons_simulate',
description=__doc__)
parser.add_argument(
'protocol', metavar='PROTOCOL_FILE',
type=argparse.FileType('r'),
help='The protocol file to simulate (spe... |
python | def one(self, command, params=None):
"""
Возвращает первую строку ответа, полученного через query
> db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: dict
"""
... |
python | def Record(self, value):
"""Records given value."""
self.sum += value
self.count += 1
pos = bisect.bisect(self.bins, value) - 1
if pos < 0:
pos = 0
elif pos == len(self.bins):
pos = len(self.bins) - 1
self.heights[pos] += 1 |
java | private synchronized boolean canLaunchJobCleanupTask() {
// check if the job is running
if (status.getRunState() != JobStatus.RUNNING &&
status.getRunState() != JobStatus.PREP) {
return false;
}
// check if cleanup task has been launched already or if setup isn't
// launched already. T... |
java | public com.google.api.ads.admanager.axis.v201902.Technology[] getExcludedMobileDeviceSubmodels() {
return excludedMobileDeviceSubmodels;
} |
java | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
... |
python | def compile_and_process(self, in_path):
"""compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path]
if not self.embed:
pdebug("[%s::%s] %s -> %s" % (
self.compiler_name,
self.name,
os.p... |
python | def get_list(self, ids: List[str]) -> List[Account]:
""" Loads accounts by the ids passed as an argument """
query = (
self.query
.filter(Account.guid.in_(ids))
)
return query.all() |
python | def filter_active(self, *args, **kwargs):
"""
Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defa... |
java | @Override
public NodeStepResult executeScriptFile(
StepExecutionContext context,
INodeEntry node,
String scriptString,
String serverScriptFilePath,
InputStream scriptAsStream,
String fileExtension,
String[] args,
String ... |
python | def service_restart(service_name):
"""
Wrapper around host.service_restart to prevent spurious "unknown service"
messages in the logs.
"""
if host.service_available(service_name):
if host.service_running(service_name):
host.service_restart(service_name)
else:
... |
python | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['closed_channels'] = self.closed
json_dict['opened_channels'] = self.opened
json_dict['closed_long_channels'] = self.closed_long
return json.dumps(json_dict) |
java | public void setTargetedLocations(com.google.api.ads.admanager.axis.v201811.Location[] targetedLocations) {
this.targetedLocations = targetedLocations;
} |
python | def create_shield_layer(shield, hashcode):
"""Creates the layer for shields."""
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + shield + '.pgn', hashcode, sym=False, invert=False) |
java | public SDVariable assign(SDVariable in, Number value) {
return assign(null, in, value);
} |
python | def get_identities(self, item):
""" Return the identities from an item """
identities = []
if 'data' not in item:
return identities
if 'revisions' not in item['data']:
return identities
revisions = item['data']['revisions']
for revision in revis... |
python | def restrict(self, point):
"""Apply the ``restrict`` method to all functions.
Returns a new farray.
"""
items = [f.restrict(point) for f in self._items]
return self.__class__(items, self.shape, self.ftype) |
java | public static int cudnnSoftmaxBackward(
cudnnHandle handle,
int algo,
int mode,
Pointer alpha,
cudnnTensorDescriptor yDesc,
Pointer y,
cudnnTensorDescriptor dyDesc,
Pointer dy,
Pointer beta,
cudnnTensorDescriptor dxDesc,
P... |
python | def get_encoder(ndarray_mode='b64'):
"""
Returns a JSON encoder that can handle:
* :obj:`numpy.ndarray`
* :obj:`numpy.floating` (converted to :obj:`float`)
* :obj:`numpy.integer` (converted to :obj:`int`)
* :obj:`numpy.dtype`
* :obj:`astropy.units.Quantity`
* :obj... |
java | public RefundQuery refundQueryByRefundNumber(String refundNumber) {
RefundQueryRequestWrapper refundQueryRequestWrapper = new RefundQueryRequestWrapper();
refundQueryRequestWrapper.setRefundNumber(refundNumber);
return refundQuery(refundQueryRequestWrapper);
} |
java | public void setRow(int row, double[] vals) {
if (vals.length != cols)
throw new IllegalArgumentException(
"The number of values does not match the number of columns");
for (int i = 0; i < vals.length; ++i)
set(row, i, vals[i]);
} |
python | def installed_packages(self):
""" :return: list of installed packages """
packages = []
CMDLINE = [sys.executable, "-mpip", "freeze"]
try:
for package in subprocess.check_output(CMDLINE) \
.decode('utf-8'). \
splitlines():
... |
python | def getstate(self):
"""
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
state = "RUNNING"
exit_code = -1
exitcode_file = os.path.join(self.workdir, "exit_code")
pid_file = os.path.join(self.workdir, "pid"... |
java | private static void moveAllFollowing(
Node start, Node srcParent, Node destParent) {
for (Node n = start.getNext(); n != null; n = start.getNext()) {
boolean isFunctionDeclaration = NodeUtil.isFunctionDeclaration(n);
srcParent.removeChild(n);
if (isFunctionDeclaration) {
destParent.a... |
java | public static syslog_ui_cmd[] get_filtered(nitro_service service, String filter) throws Exception
{
syslog_ui_cmd obj = new syslog_ui_cmd();
options option = new options();
option.set_filter(filter);
syslog_ui_cmd[] response = (syslog_ui_cmd[]) obj.getfiltered(service, option);
return response;
} |
java | boolean seekTab(FontFileReader in, String name,
long offset) throws IOException {
TTFDirTabEntry dt = (TTFDirTabEntry)dirTabs.get(name);
if (dt == null) {
log.error("Dirtab " + name + " not found.");
return false;
} else {
in.seekSet(dt.getOf... |
java | public ApiResponse<List<CorporationContactsLabelsResponse>> getCorporationsCorporationIdContactsLabelsWithHttpInfo(
Integer corporationId, String datasource, String ifNoneMatch, String token) throws ApiException {
com.squareup.okhttp.Call call = getCorporationsCorporationIdContactsLabelsValidateBefo... |
python | def step(self, action):
"""Forward action to the wrapped environment.
Args:
action: Action to apply to the environment.
Raises:
ValueError: Invalid action.
Returns:
Converted observation, converted reward, done flag, and info object.
"""
observ, reward, done, info = self._en... |
python | def extra(self, **params):
"""
Set extra query parameters (eg. filter expressions/attributes that don't validate).
Appends to any previous extras set.
:rtype: Query
"""
q = self._clone()
for key, value in params.items():
q._extra[key].append(value)
... |
python | def reset(self, config=None, train_mode=True, custom_reset_parameters=None) -> AllBrainInfo:
"""
Sends a signal to reset the unity environment.
:return: AllBrainInfo : A data structure corresponding to the initial reset state of the environment.
"""
if config is None:
... |
java | @Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T a[]) {
Object[] elements = getArray();
int len = elements.length;
if (a.length < len)
return (T[]) Arrays.copyOf(elements, len, a.getClass());
else {
System.arraycopy(elements, 0, a, 0, len)... |
python | def Reorder(x, params, output=None, **kwargs):
"""Reorder a tuple into another tuple.
For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y).
The output argument specifies how to re-order, using integers that refer
to indices in the input tuple. For example, if
input = (x, y, z)
then
... |
python | def qt4_menu_nib_dir():
"""Return path to Qt resource dir qt_menu.nib."""
menu_dir = ''
# Detect MacPorts prefix (usually /opt/local).
# Suppose that PyInstaller is using python from macports.
macports_prefix = sys.executable.split('/Library')[0]
# list of directories where to look for qt_menu.n... |
java | @Override
public void setTaskStatus(final JobId jobId, final TaskStatus status)
throws InterruptedException {
log.debug("setting task status: {}", status);
taskStatuses.put(jobId.toString(), status.toJsonBytes());
if (historyWriter != null) {
try {
historyWriter.saveHistoryItem(status)... |
java | public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException {
final Set<String> keys = request.keys();
if (keys.size() == 2) { // no props
return null;
}
ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPO... |
java | @Override
public void onNDArrayMessage(NDArrayMessage message) {
try (AeronNDArrayPublisher publisher = AeronNDArrayPublisher.builder().streamId(streamId).ctx(aeronContext)
.channel(masterUrl).build()) {
publisher.publish(message);
log.debug("NDArray Publishin... |
python | def get_max_waypoint_items_metadata(self):
"""get the metadata for max waypoint items"""
metadata = dict(self._max_waypoint_items_metadata)
metadata.update({'existing_cardinal_values': self.my_osid_object_form._my_map['maxWaypointItems']})
return Metadata(**metadata) |
python | def dump(self, backend, node):
'''High-level function to call a `backend' on a `node' to generate
code for module `module_name'.'''
assert issubclass(backend, Backend)
b = backend()
b.attach(self)
return b.run(node) |
python | def lower_coerce_type_blocks(ir_blocks):
"""Lower CoerceType blocks into Filter blocks with a type-check predicate."""
new_ir_blocks = []
for block in ir_blocks:
new_block = block
if isinstance(block, CoerceType):
predicate = BinaryComposition(
u'contains', Liter... |
python | def add(self, model):
"""raises an exception if the model cannot be added"""
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
# checks if already existing
self.foreach(foo)
self.appen... |
java | private void populateInitialAuthorizationTable() {
clearAuthorizationTable();
Map<String, Set<String>> userToRoleName = new HashMap<String, Set<String>>();
Map<String, Set<String>> groupToRoleName = new HashMap<String, Set<String>>();
Iterator<ManagementRole> itr = managementRoles.getSe... |
java | protected void setGalleriesVisible(boolean visible) {
if (visible) {
m_noGalleriesLabel.getElement().getStyle().clearDisplay();
m_galleryTree.getElement().getStyle().clearDisplay();
} else {
m_galleryTree.getElement().getStyle().setDisplay(Display.NONE);
... |
python | def _value_list_to_sciobj_dict(
sciobj_value_list, lookup_list, lookup_dict, generate_dict
):
"""Create a dict where the keys are the requested field names, from the values
returned by Django."""
sciobj_dict = {}
# for sciobj_value, lookup_str in zip(sciobj_value_list, lookup_list):
lookup_to_... |
python | def gauss_noise(dur=None, mu=0., sigma=1.):
"""
Gaussian (normal) noise stream generator.
Parameters
----------
dur :
Duration, in number of samples; endless if not given (or None).
mu :
Distribution mean. Defaults to zero.
sigma :
Distribution standard deviation. Defaults to one.
Returns
... |
python | def add_user(self, username, email, **kwargs):
"""Create a new user with provided details.
Add user example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# Add user
user = {
"username": "test_user",
... |
java | public static <T> Set<T> createSet(T... args) {
HashSet<T> newSet = new HashSet<T>();
Collections.addAll(newSet, args);
return newSet;
} |
python | def _clear_namespace():
""" Clear names that are not part of the strict ES API
"""
ok_names = set(default_backend.__dict__)
ok_names.update(['gl2', 'glplus']) # don't remove the module
NS = globals()
for name in list(NS.keys()):
if name.lower().startswith('gl'):
if name not ... |
python | def register_all(self, callback, user_data=None):
"""Register a callback for all sensors."""
self._callback = callback
self._callback_data = user_data |
python | def get_ir(cfg_func):
"""
Converts the given CFG function into IR entities
"""
ir_func = ir.Function()
ir_var_list = []
cfg_var_list = []
ir_bb_label_list = []
for cfg_var in cfg_func.variable_list:
ir_var = ir.Variable(cfg_var.name)
ir_var_list.append(ir_var)
cfg... |
java | public ServiceFuture<ProductionOrStagingEndpointInfo> publishAsync(UUID appId, ApplicationPublishObject applicationPublishObject, final ServiceCallback<ProductionOrStagingEndpointInfo> serviceCallback) {
return ServiceFuture.fromResponse(publishWithServiceResponseAsync(appId, applicationPublishObject), serviceC... |
java | @Bind(aggregate = true, optional = true)
public synchronized void bindController(Controller controller) {
LOGGER.info("Adding routes from " + controller);
List<Route> newRoutes = new ArrayList<>();
try {
List<Route> annotatedNewRoutes = RouteUtils.collectRouteFromControllerAnno... |
java | public static FileUtils.FileCopyResult unzip(InputStream in, File outDir) throws IOException
{
try (final ZipInputStream zipIn = new ZipInputStream(in)) {
final FileUtils.FileCopyResult result = new FileUtils.FileCopyResult();
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
... |
python | def generate(env):
"""Add Builders and construction variables for LaTeX to an Environment."""
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import dvi
dvi.generate(env)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxA... |
python | def convert_node(self, node):
"""
Convert the given rupture node into a hazardlib rupture, depending
on the node tag.
:param node: a node representing a rupture
"""
convert = getattr(self, 'convert_' + striptag(node.tag))
return convert(node) |
java | protected String determineRootDir(String location) {
int prefixEnd = location.indexOf(":") + 1;
int rootDirEnd = location.length();
while (rootDirEnd > prefixEnd && getPathMatcher().isPattern(location.substring(prefixEnd, rootDirEnd))) {
rootDirEnd = location.lastIndexOf('/', rootDir... |
python | def read(self, identifier, path=None):
""" Read a text object given an identifier and a path
:param identifier: Identifier of the text
:param path: Path of the text files
:return: Text
"""
if self.CACHE_FULL_TEI is True:
o = self.cache.get(_cache_key(self.tex... |
java | public static String getStatusLabelDetailsInString(final String value, final String style, final String id) {
final StringBuilder val = new StringBuilder();
if (!StringUtils.isEmpty(value)) {
val.append("value:").append(value).append(",");
}
if (!StringUtils.isEmpty(style)) {... |
java | public static boolean isValidXmlNameStartChar(char ch, boolean colonEnabled)
{
if (ch == ':') {
return colonEnabled;
}
return (ch >= 'A' && ch <= 'Z')
|| ch == '_'
|| (ch >= 'a' && ch <= 'z')
|| (ch >= 0xC0 && ch <= 0xD6)
|| (ch >= ... |
python | def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
r... |
java | @Override
public INDArray valueArrayOf(long rows, long columns, double value) {
INDArray create = createUninitialized(new long[] {rows, columns}, Nd4j.order());
create.assign(value);
return create;
} |
java | public final <R> Stream<R> transform(final Function<? super T, ? extends R> function,
final int parallelism) {
synchronized (this.state) {
checkState();
return new TransformElementStream<T, R>(this, parallelism, function);
}
} |
java | public MDecimal getHz() {
MDecimal result = new MDecimal(currentUnit.getConverterTo(HERTZ)
.convert(doubleValue()));
logger.trace(MMarker.GETTER, "Converting from {} to Hertz : {}",
currentUnit, result);
return result;
} |
java | public static long[] setI(long[] v, int off) {
final int wordindex = off >>> LONG_LOG2_SIZE;
v[wordindex] |= (1L << off);
return v;
} |
java | private Map<String, Object> readHeaderElements(AdManagerSession adManagerSession) {
// The order here must match the order of the SoapRequestHeader elements in the WSDL.
Map<String, Object> mapToFill = Maps.newLinkedHashMap();
mapToFill.put("networkCode", adManagerSession.getNetworkCode());
mapToFill.pu... |
java | protected MCWrapper getFreeConnection(ManagedConnectionFactory managedConnectionFactory, Subject subject, ConnectionRequestInfo cri,
int hashCode) throws ResourceAllocationException {
final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();
if (i... |
java | @Override
public MessageToClient createMessageToClient(MessageFromClient message, HttpSession session) {
boolean monitor = isMonitored(session);
logger.debug("Monitor is enabled : {}", monitor);
long t0 = getT0(monitor);
MessageToClient mtc = messageToClientService.createMessageToClient(message, session);... |
java | @OverrideOnDemand
protected void logInvalidRequestSetup (@Nonnull final String sMsg, @Nonnull final HttpServletRequest aHttpRequest)
{
log (sMsg + ":\n" + RequestLogger.getRequestDebugString (aHttpRequest).toString ());
} |
java | public static synchronized void init(final boolean useDb, final String adminDeviceName) throws DevFailed {
// Modified properties fo ORB usage.
final Properties props = System.getProperties();
props.put("org.omg.CORBA.ORBClass", "org.jacorb.orb.ORB");
props.put("org.omg.CORBA.ORBSingleto... |
python | def log(cls, q):
"""Quaternion Logarithm.
Find the logarithm of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing log(q) := (log(|q|), v/|v|acos(w/|q|)).
Note:
... |
python | def _get_info_pv(info):
"""
Helper function for _bestmove_get_info.
Extracts "pv" field from bestmove's info and returns move sequence in UCI notation.
"""
search = re.search(pattern=PV_REGEX, string=info)
return {"pv": search.group("move_list")} |
python | def exists(self, primary_key):
'''
a method to determine if record exists
:param primary_key: string with primary key of record
:return: boolean to indicate existence of record
'''
select_statement = self.table.select(self.table).where(... |
java | public static int[] range(int includedStart, int excludedEnd, int step) {
if (includedStart > excludedEnd) {
int tmp = includedStart;
includedStart = excludedEnd;
excludedEnd = tmp;
}
if (step <= 0) {
step = 1;
}
int deviation = excludedEnd - includedStart;
int length = deviation /... |
java | public <T> HttpClientRequest.Builder<T> get(final URI uri, final HttpClientResponseHandler<T> httpHandler)
{
return new HttpClientRequest.Builder<T>(httpClientFactory, HttpClientMethod.GET, uri, httpHandler);
} |
java | static Set<String> getTypeVariableNames(TypeMirror type) {
Set<String> names = new HashSet<>();
type.accept(TypeVariableNameVisitor.INSTANCE, names);
return names;
} |
python | def push_call_history_item(self, state, call_type, state_for_scoped_data, input_data=None):
"""Adds a new call-history-item to the history item list
A call history items stores information about the point in time where a method (entry, execute,
exit) of certain state was called.
:param... |
java | public BucketTaggingConfiguration withTagSets( TagSet... tagSets ) {
this.tagSets.clear();
for ( int index = 0; index < tagSets.length; index++ ) {
this.tagSets.add( tagSets[ index ] );
}
return this;
} |
java | private void serverFinished(Finished mesg) throws IOException {
if (debug != null && Debug.isOn("handshake")) {
mesg.print(System.out);
}
boolean verified = mesg.verify(handshakeHash, Finished.SERVER,
session.getMasterSecret());
if (!verified) {
fata... |
java | public void setKnotBlend(int n, int type) {
knotTypes[n] = (byte)((knotTypes[n] & ~BLEND_MASK) | type);
rebuildGradient();
} |
python | def delete(self, loc):
"""
Make new index with passed location deleted
Returns
-------
new_index : MultiIndex
"""
new_codes = [np.delete(level_codes, loc) for level_codes in self.codes]
return MultiIndex(levels=self.levels, codes=new_codes,
... |
java | public final <K, V, M extends Multimap<K, V>> M toMultimap(
final Function<? super T, ? extends K> keyFunction,
final Function<? super T, ? extends V> valueFunction, final M multimap) {
Preconditions.checkNotNull(keyFunction);
Preconditions.checkNotNull(valueFunction);
Pr... |
python | def resolve_compound_variable_fields(dbg, thread_id, frame_id, scope, attrs):
"""
Resolve compound variable in debugger scopes by its name and attributes
:param thread_id: id of the variable's thread
:param frame_id: id of the variable's frame
:param scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, ... |
python | def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_va... |
java | public com.sun.javadoc.Type containingType() {
if (type.getEnclosingType().hasTag(CLASS)) {
// This is the type of an inner class.
return TypeMaker.getType(env, type.getEnclosingType());
}
ClassSymbol enclosing = type.tsym.owner.enclClass();
if (enclosing != null)... |
python | def json2value(json_string, params=Null, flexible=False, leaves=False):
"""
:param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value
"""
if not is_text(json_string):
L... |
java | public void setPerson(Person person) {
log.debug("Adding person: " + person);
if (person.getId() == -1) {
person.setId(getNextId());
}
people.remove(person);
people.add(person);
} |
python | def GetUnreachableInstances(instances, ssh_key):
""" Returns list of instances unreachable via ssh. """
hostnames = [i.private_ip for i in instances]
ssh_status = AreHostsReachable(hostnames, ssh_key)
assert(len(hostnames) == len(ssh_status))
nonresponsive_instances = [instance for (instance, ssh_ok) in
... |
python | def create_network(self, action, n_name, **kwargs):
"""
Creates a configured network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name.
:type n_name: unicode | str
:param kwargs: Additional keyword a... |
java | public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} |
python | def try_collect(self, timeframe):
"""
Run the plugin's collect() method, and if an exception was caught,
store the traceback before re-raising, in order that it doesn't
get lost when concurrent.futures.Future.result() is invoked.
"""
try:
result = self.collect... |
python | def toc(self):
""" Smart getter for Table of Content list.
"""
toc = []
stack = [toc]
for entry in self.__toc:
entry['sub'] = []
while entry['level'] < len(stack):
stack.pop()
while entry['level'] > len(stack):
s... |
java | public static boolean isZip(String fileName) {
if (fileName == null) {
return false;
}
String tl = fileName.toLowerCase();
for (String element : ZIP_EXTENSIONS) {
if (tl.endsWith(element)) {
return true;
}
}
return false;
} |
python | def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
glo... |
java | private void emitCodeLines(final StringBuilder out, final Line lines, final String meta, final boolean removeIndent)
{
Line line = lines;
if (this.config.codeBlockEmitter != null)
{
final ArrayList<String> list = new ArrayList<String>();
while (line != null)
... |
java | public Implementation.SpecialMethodInvocation invokeSuper(MethodDescription.SignatureToken token) {
MethodRebaseResolver.Resolution resolution = rebaseableMethods.get(token);
return resolution == null
? invokeSuper(methodGraph.getSuperClassGraph().locate(token))
: invokeS... |
python | def figure_grid(figures_grid,
row_heights=None,
column_widths=None,
row_spacing=0.15,
column_spacing=0.15,
share_xaxis=False,
share_yaxis=False):
"""
Construct a figure from a 2D grid of sub-figures
Parameters
... |
java | synchronized void stateChanged(Date date, ChannelState state)
{
final ChannelStateHistoryEntry historyEntry;
final ChannelState oldState = this.state;
if (oldState == state)
{
return;
}
// System.err.println(id + " state change: " + oldState + " => " + s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.