language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_names_in_namespace_page(namespace_id, offset, count, proxy=None, hostport=None):
"""
Get a page of names in a namespace
Returns the list of names on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connec... |
python | def write(
self,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Streams batches of document updates and deletes, in order.
EXPERIMENTAL: This method interface might chang... |
python | def get_healthcheck(self, service_id, version_number, name):
"""Get the healthcheck for a particular service and version."""
content = self._fetch("/service/%s/version/%d/healthcheck/%s" % (service_id, version_number, name))
return FastlyHealthCheck(self, content) |
java | @Override
public Server build() {
if (!CheckGcpEnvironment.isOnGcp()) {
if (enableUntrustedAlts) {
logger.log(
Level.WARNING,
"Untrusted ALTS mode is enabled and we cannot guarantee the trustworthiness of the "
+ "ALTS handshaker service");
} else {
... |
java | protected boolean read(ByteBuffer buffer) throws IOException{
while(buffer.hasRemaining()){
int read = in.read(buffer);
if(read==0){
in.addReadInterest();
return false;
}else if(read==-1)
return true;
}
return tr... |
python | def get(self, name, request=None, timeout=5.0, throw=True):
"""Fetch current value of some number of PVs.
:param name: A single name string or list of name strings
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param float timeout: ... |
java | public static MergeEngine newInstance(final DatabaseType databaseType, final ShardingRule shardingRule,
final SQLRouteResult routeResult, final ShardingTableMetaData shardingTableMetaData, final List<QueryResult> queryResults) throws SQLException {
if (routeResult.getSq... |
python | def iplot(self, c_poly='default', c_holes='c', ret=False, ax=None):
"""
Improved plot that allows to plot polygons and holes in
different colors.
:param c_poly: Polygons color.
:type c_poly: matplotlib color, 'default' or 't' (transparent)
:param c_holes: ... |
java | public Observable<Page<RegistryInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<RegistryInner>>, Page<RegistryInner>>() {
@Override
public Page<RegistryInner> call(ServiceRespo... |
java | public ResourceHandle findUpwards(String basePath, Pattern namePattern, String childType) {
ResourceHandle current = this;
while (current != null && current.isValid()) {
ResourceHandle base = ResourceHandle.use(current.getChild(basePath));
if (base.isValid()) {
fo... |
python | def replace(self, record_id, fields, typecast=False):
"""
Replaces a record by its record id.
All Fields are updated to match the new ``fields`` provided.
If a field is not included in ``fields``, value will bet set to null.
To update only selected fields, use :any:`update`.... |
java | private void calculateMinimapAreaBounds() {
if (minimapBounds == null) {
return;
}
if (zoom == 1f) {
miniMapRequired = false;
} else {
// Calculates the bounds of the current displayed area
float x = (-currentXOffset - toCurrentSc... |
java | public static int getPid()
throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException,
InvocationTargetException {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
VMManagement mgmt... |
java | @Override
public Void call(final Void input) throws Exception {
System.out.println("Hello, Vortex!");
return null;
} |
python | def get_subscriptions(self):
"""Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
"""
# Example: {'subscriptions': ['subscr... |
python | def _generate_range(start, end, periods, offset):
"""Generate a regular range of cftime.datetime objects with a
given time offset.
Adapted from pandas.tseries.offsets.generate_range.
Parameters
----------
start : cftime.datetime, or None
Start of range
end : cftime.datetime, or Non... |
python | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
... |
java | public String getScreenURL()
{
String strCommand = super.getScreenURL();
strCommand = Utility.addURLParam(strCommand, DBParams.RECORD, this.getProperty(DBParams.RECORD));
strCommand = Utility.addURLParam(strCommand, "package", this.getProperty("package"));
return strCommand;
} |
java | protected void applyRegularization(Regularization.ApplyStep step, Trainable layer, String paramName, INDArray gradientView, INDArray paramsView, int iter, int epoch, double lr) {
//TODO: do this for multiple contiguous params/layers (fewer, larger ops)
List<Regularization> l = layer.getConfig().getRegu... |
python | def resizeToContents(self):
"""
Resizes this toolbar based on the contents of its text.
"""
if self._toolbar.isVisible():
doc = self.document()
h = doc.documentLayout().documentSize().height()
offset = 34
... |
python | def cycle_class(self):
"""
Return the subclass of ScfCycle associated to the task or
None if no SCF algorithm if associated to the task.
"""
if isinstance(self, RelaxTask):
return abiinspect.Relaxation
elif isinstance(self, GsTask):
return abiinspe... |
python | def closeEvent( self, event ):
"""
Overloads the close event for this widget to make sure that the data \
is properly saved before exiting.
:param event | <QCloseEvent>
"""
if ( not (self.saveOnClose() and self.checkForSave()) ):
event.ignore()
... |
java | public static void shuffle(int[] arr, Random rand) {
int size = arr.length;
for (int i = size; i > 1; i--) {
int tmp = arr[i-1];
int r = rand.nextInt(i);
arr[i-1] = arr[r];
arr[r] = tmp;
}
} |
java | @Override
protected void coreLoadCatalog(long timestamp, final byte[] catalogBytes) throws EEException {
LOG.trace("Loading Application Catalog...");
int errorCode = 0;
errorCode = nativeLoadCatalog(pointer, timestamp, catalogBytes);
checkErrorCode(errorCode);
//LOG.info("Loa... |
java | public void handleTouchEvent(MotionEvent ev){
if(ev.getAction() == MotionEvent.ACTION_MOVE){
// A finger is dragging about
if(mTexHeight != 0 && mTexWidth != 0){
mSummedTouchPosition[0] += (2 * (ev.getX() - mLastTouchPosition[0])) / mTexWidth;
mSummedTouch... |
java | public int createTextureObject() {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
GlUtil.checkGlError("glGenTextures");
int texId = textures[0];
GLES20.glBindTexture(mTextureTarget, texId);
GlUtil.checkGlError("glBindTexture " + texId);
GLES2... |
java | public static base_response delete(nitro_service client, dnstxtrec resource) throws Exception {
dnstxtrec deleteresource = new dnstxtrec();
deleteresource.domain = resource.domain;
deleteresource.String = resource.String;
deleteresource.recordid = resource.recordid;
return deleteresource.delete_resource(clien... |
python | def umi_consensus(data):
"""Convert UMI grouped reads into fastq pair for re-alignment.
"""
align_bam = dd.get_work_bam(data)
umi_method, umi_tag = _check_umi_type(align_bam)
f1_out = "%s-cumi-1.fq.gz" % utils.splitext_plus(align_bam)[0]
f2_out = "%s-cumi-2.fq.gz" % utils.splitext_plus(align_bam... |
java | public synchronized byte[] readLog(String moduleName) throws IOException {
File logFile = getLogFile(moduleName);
if (logFile.exists()) {
return CmsFileUtil.readFile(logFile);
} else {
return new byte[] {};
}
} |
python | def start(self):
"""Start listener in a background thread
Returns:
address of the Server as a tuple of (host, port)
"""
server_sock = self.start_listening_socket()
# hostname may not be resolvable but IP address probably will be
host = self.get_server_ip()
port = server_sock.getsockn... |
java | public Deferred<ByteMap<Long>> getLastWriteTimes() {
class ResolutionCB implements Callback<Deferred<ByteMap<Long>>, Object> {
@Override
public Deferred<ByteMap<Long>> call(Object arg0) throws Exception {
final Scanner scanner = getScanner();
scanner.setQualifier(TSMeta.COUNTER_QUALIFIER... |
python | def _assert_command_dict(self, struct, name, path=None, extra_info=None):
"""Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair."""
self._assert_dict(struct, name, path, extra_info)
if len(struct) != 1:
err = [self._format_error_path(path + [name])]
... |
python | def functions(self):
"""
A list of functions declared or defined in this module.
"""
return [v for v in self.globals.values()
if isinstance(v, values.Function)] |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
public static String setPropertyAsNeeded(final String propName, final String propValue) {
String previousPropValue = (String) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
@Override
public String run... |
java | public final ObjectName registerMBean(Object pMBean,String ... pOptionalName)
throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException {
synchronized (mBeanHandles) {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {... |
python | def wns_send_bulk_message(
uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs
):
"""
WNS doesn't support bulk notification, so we loop through each uri.
:param uri_list: list: A list of uris the notification will be sent to.
:param message: str: The notification data to be sent.
... |
java | protected JsonWriter writeObject(Object object) throws IOException {
if (object == null) {
nullValue();
} else if (object instanceof JsonSerializable) {
JsonSerializable structuredSerializable = Cast.as(object);
if (object instanceof JsonArraySerializable) {
beginArray... |
python | def dependents(self, task, params={}, **options):
"""Returns the compact representations of all of the dependents of a task.
Parameters
----------
task : {Id} The task to get dependents on.
[params] : {Object} Parameters for the request
"""
path = "/tasks/%s/dep... |
python | def get_local_filter_directives(ast, current_schema_type, inner_vertex_fields):
"""Get all filter directives that apply to the current field.
This helper abstracts away the fact that some vertex field filtering operators apply on the
inner scope (the scope of the inner vertex field on which they are applie... |
python | def absence_count(request):
"""Add the absence count to the context for students."""
if request.user and request.user.is_authenticated and request.user.is_student:
absence_info = request.user.absence_info()
num_absences = absence_info.count()
show_notif = False
if num_absences >... |
python | def _soup_strings(soup):
"""Return text strings in soup."""
paragraph_tags = set([
"caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td",
"div", "span"
])
skip_children = None
for descendant in soup.descendants:
# If we've treated a tag as a contiguous paragraph, don't re-... |
java | @Override
public Set<SingularAttribute<? super X, ?>> getIdClassAttributes()
{
if (isIdClass)
{
return idClassAttributes;
}
else if (getSuperClazzType() != null
/*
* && getSuperClazzType().getJavaType().isAssignableFrom(
* AbstractIdentifiabl... |
java | byte[] getFirstKey(TableKelp table)
{
int keyOffset = table.getKeyOffset();
int keyLength = table.getKeyLength();
int offset = _rowHead + keyOffset;
byte []key = new byte[keyLength];
byte []buffer = getBuffer();
System.arraycopy(buffer, offset, key, 0, keyLength);
retur... |
python | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... |
python | def leave_command_mode(self, append_to_history=False):
"""
Leave the command/prompt mode.
"""
client_state = self.get_client_state()
client_state.command_buffer.reset(append_to_history=append_to_history)
client_state.prompt_buffer.reset(append_to_history=True)
c... |
java | protected Set<Tag> getAllTags(Area area)
{
Set<Tag> ret = new HashSet<Tag>(area.getTags().keySet());
for (int i = 0; i < area.getChildCount(); i++)
ret.addAll(area.getChildAt(i).getTags().keySet());
return ret;
} |
java | private static Provider getDefaultProvider() {
// approach 1
try {
String providerClass = System.getProperty("org.joda.time.DateTimeZone.Provider");
if (providerClass != null) {
try {
// do not initialize the class until the type has been check... |
python | def _get_action(self, action):
"""
Retrieve a descriptor for the named action. Caches
descriptors for efficiency.
"""
# If we don't have an action named that, bail out
if action not in self.wsgi_actions:
return None
# Generate an ActionDescriptor if... |
java | public static @CheckForNull
TypeQualifierAnnotation combineReturnTypeAnnotations(TypeQualifierAnnotation a, TypeQualifierAnnotation b) {
return combineAnnotations(a, b, combineReturnValueMatrix);
} |
python | def get_event_access_codes(self, id, **data):
"""
GET /events/:id/access_codes/
Returns a :ref:`paginated <pagination>` response with a key of ``access_codes``, containing a list of :format:`access_codes <access_code>` available on this event.
"""
return self.get("/event... |
java | public static PrivateKey getSignCertPrivateKeyByStoreMap(String certPath,
String certPwd) {
if (!keyStoreMap.containsKey(certPath)) {
loadSignCert(certPath, certPwd);
}
try {
Enumeration<String> aliasenum = keyStoreMap.get(certPath)
.aliases();
String keyAlias = null;
if (aliasenum.hasMoreElem... |
python | def from_elan(cls: Type[CorpusT], org_dir: Path, tgt_dir: Path,
feat_type: str = "fbank", label_type: str = "phonemes",
utterance_filter: Callable[[Utterance], bool] = None,
label_segmenter: Optional[LabelSegmenter] = None,
speakers: List[str] = No... |
java | public boolean insertGroup(String name)
{
if (isGroupExist(name))
{
throw new SystemException(String.format("Group '%s' already exist.", name));
}
return allGroups.add(name);
} |
java | public static Config load(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
return loadDefaultConfig(loader, parseOptions, resolveOptions);
} |
java | public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case HOST:
return is_set_host();
case SUPERVISOR_ID:
return is_set_supervisorId();
case UPTIME_SECS:
return is_set_uptimeSecs();
case NUM_WORKERS:
... |
java | public boolean isConsistent() throws IOException {
byte[] b = new byte[elementSize];
long offset = 0;
byte[] oldKey = null;
int i = 0;
while (offset < this.getFilledUpFromContentStart()) {
this.read(offset, ByteBuffer.wrap(b));
byte[] key = Arrays.copyOfRa... |
python | def acceptEdit(self):
"""
Accepts the current edit for this label.
"""
if not self._lineEdit:
return
self.setText(self._lineEdit.text())
self._lineEdit.hide()
if not self.signalsBlocked():
self.editingFinished.e... |
python | def run_mutation_aggregator(job, mutation_results, univ_options):
"""
Aggregate all the called mutations.
:param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome
format
:param dict univ_options: Dict of universal options used by almost all tools
:r... |
python | def _set_access_group(self, v, load=False):
"""
Setter method for access_group, mapped from YANG variable /interface/ethernet/ipv6/access_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_access_group is considered as a private
method. Backends looking to ... |
python | def get_output_key(self, args, kwargs):
"""Return the key that the output should be cached with, given
arguments, keyword arguments, and a list of arguments to ignore.
"""
# Get a dictionary mapping argument names to argument values where
# ignored arguments are omitted.
... |
java | protected void openPublishDailog(CmsProject project, List<CmsResource> directPublishResources) {
CmsPublishData publishData = getPublishData(project, directPublishResources);
String data = getSerializedPublishData(publishData);
getRpcProxy(I_CmsGwtDialogClientRpc.class).openPublishDialog(data);... |
java | public void bindFilterPredicate(ObjectProperty<TreeItemPredicate<Category>> predicateProperty) {
predicateProperty.bind(Bindings.createObjectBinding(() -> {
if (searchText.get() == null || searchText.get().isEmpty()) {
return null;
}
return TreeItemPredicate.create(filterPredicate);
},... |
java | public CompletionStage<Void> put(final Resource resource, final Instant time) {
return runAsync(() -> {
final File resourceDir = FileUtils.getResourceDirectory(directory, resource.getIdentifier());
if (!resourceDir.exists()) {
resourceDir.mkdirs();
}
... |
python | def snapshot_absent(name, force=False, recursive=False, recursive_all=False):
'''
ensure snapshot is absent on the system
name : string
name of snapshot
force : boolean
try harder to destroy the dataset (zfs destroy -f)
recursive : boolean
also destroy all the child datasets... |
python | def _GenerateApiFileDetails(path_infos):
"""Generate file details based on path infos history."""
type_attrs = []
hash_attrs = []
size_attrs = []
stat_attrs = []
pathspec_attrs = []
def _Value(age, value):
"""Generate ApiAff4ObjectAttributeValue from an age and a value."""
v = ApiAff4ObjectAttr... |
python | def directory_compare_from_hash(from_directory, to_directory):
"""
:param from_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:param to_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:re... |
java | public String selectOne(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
//修改返回值类型为实体类型
setResultType(ms, entityClass);
StringBuilder sql = new StringBuilder();
sql.append(SqlHelper.selectAllColumns(entityClass));
sql.append(SqlHelper.fromTable(entityClass... |
python | def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned version of tf.image.crop_and_resize, following our definition of floating point boxes.
Args:
image: NCHW
boxes: nx4, x1y1x2y2
box_ind: (n,)
crop_size (int):
Returns:
n,C,size,size... |
python | def copy_file_upload(self, targetdir):
'''
Copies the currently valid file upload into the given directory.
If possible, the content is un-archived in the target directory.
'''
assert(self.file_upload)
# unpack student data to temporary directory
# os.chro... |
python | def stream(self, actor_sid=values.unset, event_type=values.unset,
resource_sid=values.unset, source_ip_address=values.unset,
start_date=values.unset, end_date=values.unset, limit=None,
page_size=None):
"""
Streams EventInstance records from the API as a gener... |
python | def decrypt(self, esp, key, icv_size=None):
"""
Decrypt an ESP packet
@param esp: an encrypted ESP packet
@param key: the secret key used for encryption
@param icv_size: the length of the icv used for integrity check
@return: a valid ESP packet encryp... |
java | public static String[] replaceDataReferencesInArray(final String[] args, final Map<String, Map<String, String>> data) {
return replaceDataReferencesInArray(args, data, null, false);
} |
python | def connectSelection( self, cls = None ):
"""
Creates a connection between the currently selected \
nodes, provided there are only 2 nodes selected. If \
the cls parameter is supplied then that will be the \
class instance used when creating the connection. \
Otherwise, ... |
java | public void get(URI uri, Header[] additionalRequestHeaders,
Credentials credentials) {
ra.getExecutorService().execute(
new AsyncGetHandler(ra, handle, uri, additionalRequestHeaders,
credentials));
} |
python | def get_stacktrace(limit=None):
"""
Get a full stacktrace for the current state of execution.
Include the current state of the stack, minus this function.
If there is an active exception, include the stacktrace information from
the exception as well.
:param int limit:
Optionally limit ... |
python | def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={},
ret_center=False, ret_pha_offset=False, ret_qpi=False):
"""Determine refractive index and radius of a spherical object
Parameters
----------
qpi: qpimage.QPImage
Quantitative phase image data
r0: floa... |
java | public synchronized boolean addDriveListener(final IUSBDriveListener listener) {
if (listeners.contains(listener)) {
return false;
}
listeners.add(listener);
start();
return true;
} |
python | def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(len(environment.comment_start_string), 'comment',
e(environment.comment_start_string)),
(len(environment.block_start_string), 'block',
e(environm... |
python | def _detail_participant(
self,
channel_identifier: ChannelID,
participant: Address,
partner: Address,
block_identifier: BlockSpecification,
) -> ParticipantDetails:
""" Returns a dictionary with the channel participant information. """
dat... |
java | public void marshall(UpdateShardCountRequest updateShardCountRequest, ProtocolMarshaller protocolMarshaller) {
if (updateShardCountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateShar... |
java | Expression XreadExplicitRowValueConstructorOrNull() {
Expression e;
switch (token.tokenType) {
case Tokens.OPENBRACKET : {
read();
int position = getPosition();
int brackets = readOpenBrackets();
switch (token.tokenType) {
... |
python | def curlrequests(curl_string, **kwargs):
"""Use tPool to request for curl string.
If kwargs contains the req which hasattr request method, like req=requests.
:param curl_string: standard curl string.
:type curl_string: str
:param kwargs: valid kwargs for tPool.
:type curl_string: dict
Basi... |
python | def display(self, content = None, **settings):
"""
Perform widget rendering and output the result.
"""
sys.stdout.write("\r")
sys.stdout.write(self.render(content, **settings))
sys.stdout.flush() |
python | def fit(self, X, y, **kwargs):
"""
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
An array or series of target values
kwargs: keyword arguments passed to Sci... |
java | public Component getComponentByName(String strName, Container parent)
{
for (int i = 0; i < parent.getComponentCount(); i++)
{
Component component = parent.getComponent(i);
if (strName.equals(component.getName()))
return component;
if (component in... |
java | public AnnotationVisitor visitLocalVariableAnnotation(int typeRef,
TypePath typePath, Label[] start, Label[] end, int[] index,
String desc, boolean visible) {
if (mv != null) {
return mv.visitLocalVariableAnnotation(typeRef, typePath, start,
end, index, de... |
python | def count(self):
"Return how many nodes this contains, including self."
if self._nodes is None:
return 1
return sum(i.count() for i in self._nodes) |
python | def transform_to_mods_periodical(marc_xml, uuid, url):
"""
Convert `marc_xml` to periodical MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url (str): URL of... |
java | public void init (Injector injector)
throws Exception
{
// output general system information
SystemInfo si = new SystemInfo();
log.info("Starting up", "server", getClass().getSimpleName(), "os", si.osToString(),
"jvm", si.jvmToString());
registerSignalHandlers(in... |
java | protected String changeCase(String originalString, String mode) {
String targetString = originalString;
// mode is case insensitive, allow upper for example
CaseFormatMode changeCaseMode = CaseFormatMode.get(mode.toUpperCase());
if (changeCaseMode != null) {
switch (changeCaseMode) {
case LOWER_CAMEL_CASE... |
java | public String[] getNamespacePrefixes() throws RepositoryException
{
Collection<String> allPrefixes = new LinkedList<String>();
allPrefixes.addAll(namespaces.keySet());
String[] permanentPrefixes = workspace.getNamespaceRegistry().getPrefixes();
for (int i = 0; i < permanentPrefixes.length; ... |
python | def prepare(
self,
config_path=None,
user=None,
password=None,
exe_path=None,
comm_password=None,
**kwargs
):
"""
登陆客户端
:param config_path: 登陆配置文件,跟参数登陆方式二选一
:param user: 账号
:param password: 明文密码
:param exe_path:... |
python | def _maybe_read_file(filename):
"""Read the given file, if it exists.
Args:
filename: A path to a file.
Returns:
A string containing the file contents, or `None` if the file does
not exist.
"""
try:
with open(filename) as infile:
return infile.read()
except IOError as e:
if e.err... |
java | public String getHeapMemoryUsage() {
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
return JsonUtils.marshalToString(memoryUsage);
} |
java | @BetaApi
public final Operation setNamedPortsRegionInstanceGroup(
ProjectRegionInstanceGroupName instanceGroup,
RegionInstanceGroupsSetNamedPortsRequest regionInstanceGroupsSetNamedPortsRequestResource) {
SetNamedPortsRegionInstanceGroupHttpRequest request =
SetNamedPortsRegionInstanceGroupHt... |
java | public static Response post(String url, String body) throws HttpException {
return post(url, body, null, null, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT);
} |
java | private static RDFNode toNode(Object value) {
if (value == null) {
return null;
} else if (value instanceof RDFNode) {
return (RDFNode) value;
} else if (value instanceof IRI) {
return new NamedNodeImpl(URI.create(((IRI)value).iri.toString()));
} else if (value instanceof PlainLiteral)... |
java | @Override
protected String getIdentifier(final String internalId)
{
if (internalId == null)
{
return null;
}
return internalId.substring(this.containerConfig.containerName.length());
} |
java | public void setContentHighlightingVisible(boolean visible) {
if (visible) {
if (m_highlighting == null) {
m_highlighting = new CmsHighlightingBorder(
CmsPositionBean.getBoundingClientRect(m_referenceElement),
CmsHighlightingBorder.BorderColor.... |
java | protected boolean isMissingParameter(Map<String, String[]> requestParams, String endpoint) {
if (TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN.equals(endpoint)) {
// Must have oauth_token and oauth_verifier parameters in order to send request to oauth/access_token endpoint
if (!requestP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.