language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def collectors(self, recurse=True, flags=0):
"""
Returns a list of the collectors for this instance.
:return {<str> name: <orb.Collector>, ..}
"""
output = {}
if recurse and self.inherits():
schema = orb.system.schema(self.inherits())
if not s... |
java | private static String nodeTargetPattern(ShapeTargetValueShape target) {
return " " + formatNode(target.getNode()) + " " + writePropertyChain(target.pathChain) + " ?this . ";
} |
python | def words_amount_needed(self) -> int:
"""Calculate the needed amount of words to satisfy the entropy number.
This is for the given wordlist.
"""
if (
self.entropy_bits_req is None
or self.amount_n is None
or not self.wordlist
):
... |
python | def ingress_filter(self, response):
""" Flatten a response with meta and data keys into an object. """
data = self.data_getter(response)
if isinstance(data, dict):
data = m_data.DictResponse(data)
elif isinstance(data, list):
data = m_data.ListResponse(data)
... |
java | public SshClient connect(SshTransport transport, String username,
boolean buffered) throws SshException {
return connect(transport, username, buffered, null);
} |
python | def chunked_iter(src, size, **kw):
"""Generates *size*-sized chunks from *src* iterable. Unless the
optional *fill* keyword argument is provided, iterables not even
divisible by *size* will have a final chunk that is smaller than
*size*.
>>> list(chunked_iter(range(10), 3))
[[0, 1, 2], [3, 4, 5... |
python | def deactivate(name):
"""Deactivate plugin.
Parameters
----------
name : str
Plugin name.
"""
if name in plugins:
plugins[name].deactivate()
else:
raise Exception("plugin {} not found".format(name)) |
java | public DataLakeStoreAccountInner beginUpdate(String resourceGroupName, String accountName, UpdateDataLakeStoreAccountParameters parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body();
} |
java | public static int[] trim(LinearSparseVector c, float v) {
int[][] idx = getTop(c, v);
setZero(c, idx[1]);
return idx[0];
} |
python | def keypair_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all keypairs.
Generates a list of keypairs available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a... |
python | def _group_flat_tags(tag, tags):
"""Extract tags sharing the same name as the provided tag. Used to collect
options for radio and checkbox inputs.
:param Tag tag: BeautifulSoup tag
:param list tags: List of tags
:return: List of matching tags
"""
grouped = [tag]
name = tag.get('name', ... |
java | public ResponseLaunchTemplateData withLicenseSpecifications(LaunchTemplateLicenseConfiguration... licenseSpecifications) {
if (this.licenseSpecifications == null) {
setLicenseSpecifications(new com.amazonaws.internal.SdkInternalList<LaunchTemplateLicenseConfiguration>(licenseSpecifications.length));... |
java | public static void addMessage(final HttpServletRequest request, final String message) {
StringBuilder sb = (StringBuilder) request.getAttribute(MESSAGE_KEY);
if (sb == null) {
sb = new StringBuilder();
request.setAttribute(MESSAGE_KEY, sb);
}
sb.append(message);
} |
python | def gt(name, value):
'''
Only succeed if the value in the given register location is greater than
the given value
USAGE:
.. code-block:: yaml
foo:
check.gt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
... |
python | def reduce(x, op='sum'):
"""Reduction function with given operation.
Args:
x (Variable): An input.
op (str): 'sum' or 'mean'.
Note:
This is deprecated. Use ``mean`` or ``sum`` instead.
"""
import warnings
warnings.warn(
"Deprecated API. Use ``sum`` or ``mean`` ... |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Empty, OperationMetadata> deleteInstanceAsync(InstanceName name) {
DeleteInstanceRequest request =
DeleteInstanceRequest.newBuilder().setName(name == null ? null : name.... |
python | def ratio(self, operand):
"""Calculate the ratio of this `Spectrogram` against a reference
Parameters
----------
operand : `str`, `FrequencySeries`, `Quantity`
a `~gwpy.frequencyseries.FrequencySeries` or
`~astropy.units.Quantity` to weight against, or one of
... |
java | public static final boolean isConnected(AminoAcid a, AminoAcid b) {
Atom C = null ;
Atom N = null;
C = a.getC();
N = b.getN();
if ( C == null || N == null)
return false;
// one could also check if the CA atoms are < 4 A...
double distance = getDistance(C,N);
return distance < 2.5;
} |
python | def log_assist_response_without_audio(assist_response):
"""Log AssistResponse fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistResponse()
resp_copy.CopyFrom(assist_response)
has_audio_data = (resp_copy.HasField('au... |
java | protected boolean combineRecursively( List<Privilege> list,
Privilege[] privileges ) {
boolean res = false;
for (Privilege p : privileges) {
if (p.isAggregate()) {
res = combineRecursively(list, p.getAggregatePrivileges());
... |
python | def create(cls, jar):
"""Creates an actual M2Coordinate from the given M2Coordinate-like object (eg a JarDependency).
:API: public
:param JarDependency jar: the input coordinate.
:return: A new M2Coordinate, unless the input is already an M2Coordinate in which case it just
returns the input unch... |
java | public String activate() {
Long[] userIds = getLongIds("user");
String isActivate = get("isActivate");
int successCnt;
User manager = userService.get(SecurityUtils.getUsername());
String msg = "security.info.freeze.success";
if (Strings.isNotEmpty(isActivate) && "false".equals(isActivate)) {
... |
java | boolean canBeSplit( List<Point2D_I32> contour, Element<Corner> e0 , boolean mustSplit ) {
Element<Corner> e1 = next(e0);
// NOTE: The contour is passed in but only the size of the contour matters. This was done to prevent
// changing the signature if the algorithm was changed later on.
int length = Circu... |
python | def close(self):
"Terminate document"
if(self.state==3):
return
if(self.page==0):
self.add_page()
#Page footer
self.in_footer=1
self.footer()
self.in_footer=0
#close page
self._endpage()
#close document
self.... |
python | def text(text, message='', title=''):
"""
This function is suitable for displaying general text, which can be longer
than in :func:`message`
:ref:`screenshots<text>`
:param text: (long) text to be displayed
:param message: (short) message to be displayed.
:param title: window title
:rt... |
java | @Bean
@ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true)
public MonitoringSpringAdvisor monitoringSpringRestControllerAdvisor() {
return new MonitoringSpringAdvisor(new AnnotationMatchingPointcut(RestController.class));
} |
java | @Override
public void search(final Query query) {
getDispatcher().invokeLater(new AsyncTask(SEARCH, listeners) {
@Override
public void invoke(List<TwitterListener> listeners) throws TwitterException {
QueryResult result = twitter.search(query);
for (Tw... |
java | @Override
public @Nonnull Iterable<String> launchMany(final @Nonnull VMLaunchOptions withLaunchOptions, final @Nonnegative int count) throws CloudException, InternalException {
if( count < 1 ) {
throw new InternalException("Invalid attempt to launch less than 1 virtual machine (requested " + cou... |
python | def download_SRA(self, email, directory='series', filterby=None, nproc=1,
**kwargs):
"""Download SRA files for each GSM in series.
.. warning::
Do not use parallel option (nproc > 1) in the interactive shell.
For more details see `this issue <https://stacko... |
python | def strip(value, msg):
"""
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict... |
python | def correspondent(self):
"""
:returns: The username of the user with whom the logged in user is
conversing in this :class:`~.MessageThread`.
"""
try:
return self._correspondent_xpb.one_(self._thread_element).strip()
except IndexError:
rai... |
python | def find_ctx(elt):
"""Get the right ctx related to input elt.
In order to keep safe memory as much as possible, it is important to find
the right context element. For example, instead of putting properties on
a function at the level of an instance, it is important to save such
property on the insta... |
java | private void removeHighlights(Collection<? extends Point> points)
{
Set<Object> highlightsToRemove = new LinkedHashSet<Object>();
for (Point point : points)
{
Object oldHighlight = highlights.remove(point);
if (oldHighlight != null)
{
... |
java | public static Map<String, Object> read(Object object) {
PropertyDescriptor[] descriptors;
Class<?> clazz = object.getClass();
try {
descriptors = getPropertyDescriptors(clazz);
} catch (IntrospectionException e) {
LOG.error("Failed to introspect " + clazz, e);
... |
python | def cuboid(target, throat_diameter='throat.diameter',
throat_length='throat.length'):
r"""
Calculate surface area for a cuboid throat
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated a... |
python | def normalized(self):
"""Return a Rect covering the same area, but with height and width
guaranteed to be positive."""
return Rect(pos=(min(self.left, self.right),
min(self.top, self.bottom)),
size=(abs(self.width), abs(self.height))) |
python | def shutdown(self):
"""
Close all connections. ``Session`` instances should not be used
for any purpose after being shutdown.
"""
with self._lock:
if self.is_shutdown:
return
else:
self.is_shutdown = True
# PYTHON-... |
python | def node_desc(self, atoms):
"""default 9 bits descriptor
7 bits of atomic number (0-127) and 2 bits of pi electrons (0-3)
"""
a1 = self.mol.atom(atoms[0])
a2 = self.mol.atom(atoms[1])
a1t = a1.number << 2 | a1.pi
a2t = a2.number << 2 | a2.pi
pair = sorted(... |
java | protected Pair<Double, ServerHolder> chooseBestServer(
final DataSegment proposalSegment,
final Iterable<ServerHolder> serverHolders,
final boolean includeCurrentServer
)
{
Pair<Double, ServerHolder> bestServer = Pair.of(Double.POSITIVE_INFINITY, null);
List<ListenableFuture<Pair<Double, ... |
java | private void submitReadTask(String action,
String spaceId,
String contentId,
String range) {
AuditTask task = new AuditTask();
task.setAction(action);
task.setUserId(getUserId());
task.setDate... |
java | public Byte getAsByte(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).byteValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Byte.valueOf(value... |
java | private boolean registerSpecifiedPorts(int PortType) {
String val = null;
Properties props = null;
String file_loc = null;
// Old style: properties file must be in JRE folder
String ext_dirs = System.getProperty("java.ext.dirs");
String[] dirArray = ext_dirs.split(System.... |
java | private void setupResource(List resource) throws ParsingException {
mapAttributes(resource, resourceMap);
// make sure there resource-id attribute was included
List<Attribute> resourceId = resourceMap.get(RESOURCE_ID);
if (resourceId == null) {
logger.warn("Resource must co... |
python | def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
... |
java | private long getMax(Object sourceAttribute)
{
int size = primaryKeyAttributes.size();
long maxFromAllTables = Long.MIN_VALUE;
Long maxFromTable;
Attribute primaryKeyAttribute;
for(int i = 0; i < size; i++)
{
primaryKeyAttribute = (Attribute)prima... |
java | public File downloadArtifactsFile(Object projectIdOrPath, Integer jobId, ArtifactsFile artifactsFile, File directory) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(),
"projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", ar... |
python | def initiate_session(config):
"""
Initiate a session globally used in prof :
+ Retrive the cookie
+ Log to prof
Returns an initiated session
"""
global baseurl
baseurl = config['DEFAULT']['baseurl']
if 'session' in config['DEFAULT']:
cookies = {
'PHPSESSID': ... |
python | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([COMMAND_CODE, self.transmit_error_counter,
self.receive_error_counter, self.bus_off_counter]) |
java | @SuppressWarnings("unchecked")
public static boolean load(GLImplementation implementation) {
try {
final Constructor<?> constructor = Class.forName(implementation.getContextName()).getDeclaredConstructor();
constructor.setAccessible(true);
implementations.put(implementati... |
java | public String getAlterUserSQL() {
StringBuffer sb = new StringBuffer();
sb.append(Tokens.T_ALTER).append(' ');
sb.append(Tokens.T_USER).append(' ');
sb.append(getStatementName()).append(' ');
sb.append(Tokens.T_SET).append(' ');
sb.append(Tokens.T_PASSWORD).append(' ');... |
python | def set_plot_theme(theme):
"""Set the plotting parameters to a predefined theme"""
if theme.lower() in ['paraview', 'pv']:
rcParams['background'] = PV_BACKGROUND
rcParams['cmap'] = 'coolwarm'
rcParams['font']['family'] = 'arial'
rcParams['font']['label_size'] = 16
rcParam... |
java | public Config createConfigWithPackingDetails(Config runtime, PackingPlan packing) {
return Config.newBuilder()
.putAll(runtime)
.put(Key.COMPONENT_RAMMAP, packing.getComponentRamDistribution())
.put(Key.NUM_CONTAINERS, 1 + packing.getContainers().size())
.build();
} |
java | public String[] getModules()
{
// module has higher priority if set by expression
if ( module != null )
{
return new String[] { module };
}
if ( modules == null )
{
//Use a Set to avoid duplicate when user set src/main/java as <resource>
... |
java | public KQueueDatagramChannelConfig setReusePort(boolean reusePort) {
try {
((KQueueDatagramChannel) channel).socket.setReusePort(reusePort);
return this;
} catch (IOException e) {
throw new ChannelException(e);
}
} |
java | @Override
public final void setForwardRoutingPath(List<SIDestinationAddress> value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setForwardRoutingPath", value);
/* It is OK to pass in null for the List */
if (value != null) {
... |
java | public List<I_CmsEditableGroupRow> getRows() {
List<I_CmsEditableGroupRow> result = Lists.newArrayList();
for (Component component : m_container) {
if (component instanceof I_CmsEditableGroupRow) {
result.add((I_CmsEditableGroupRow)component);
}
}
... |
python | def underscores_to_camelcase(argument):
''' Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function '''
result = ''
previous_was_underscore = False
for char in argument:
if ... |
python | def simulate(self, n):
"""
Evolve multiple sites during one tree traversal
"""
self.tree._tree.seed_node.states = self.ancestral_states(n)
categories = np.random.randint(self.ncat, size=n).astype(np.intc)
for node in self.tree.preorder(skip_seed=True):
node.s... |
python | def __clean(self, misp_response):
"""
:param misp_response:
:return:
"""
response = []
for event in misp_response.get('response', []):
response.append(self.__clean_event(event['Event']))
return response |
java | public void validate() throws ValidateException
{
if ((this.xaDataSourceClass == null || this.xaDataSourceClass.trim().length() == 0) &&
(this.driver == null || this.driver.trim().length() == 0))
throw new ValidateException(bundle.requiredElementMissing(XML.ELEMENT_XA_DATASOURCE_CLASS,
... |
java | public static void saveCompositeComponentForResolver(FacesContext facesContext, Location location, int ccLevel)
{
UIComponent cc = ccLevel > 0 ? getCompositeComponentBasedOnLocation(facesContext, location, ccLevel)
: getCompositeComponentBasedOnLocation(facesContext, location);
List<... |
java | @Override
public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
for (Evidence e : dependency.getEvidence(EvidenceType.VENDOR)) {
if ("pom".equals(e.getSource())) {
return;
}
}
try {
final List<MavenA... |
java | @Override
public void execute() throws BuildException {
populateSettings();
try (Engine engine = new Engine(Update.class.getClassLoader(), getSettings())) {
try {
engine.doUpdates();
} catch (UpdateException ex) {
if (this.isFailOnError()) {
... |
java | public boolean isStartedBy(final T element) {
if (element == null) {
return false;
}
return lowerEndpoint.isClosed && lowerEndpoint.compareTo(element) == 0;
} |
python | def resolver(self):
"""jsonschema RefResolver object for the base schema."""
if self._resolver is not None:
return self._resolver
if self._schema_path is not None:
# the documentation for ref resolving
# https://github.com/Julian/jsonschema/issues/98
... |
java | @Override
void parseTablesAndParams(VoltXMLElement stmtNode) {
m_tableList.clear();
// Parse parameters first to satisfy a dependency of expression parsing
// which happens during table scan parsing.
parseParameters(stmtNode);
assert(stmtNode.children.size() > 1);
Ab... |
python | def _symlink_or_copy_grabix(in_file, out_file, data):
"""We cannot symlink in CWL, but may be able to use inputs or copy
"""
if cwlutils.is_cwl_run(data):
# Has grabix indexes, we're okay to go
if utils.file_exists(in_file + ".gbi"):
out_file = in_file
else:
u... |
python | def create_bulk(cls, name, interfaces=None, nodes=2, cluster_mode='balancing',
primary_mgt=None, backup_mgt=None, primary_heartbeat=None,
log_server_ref=None, domain_server_address=None, location_ref=None,
default_nat=False, enable_antivirus=False, enable_gti=False, comment=None,
... |
python | def kill_children(self, *args, **kwargs):
'''
Kill all of the children
'''
# first lets reset signal handlers to default one to prevent running this twice
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
# check that this... |
python | def get_can_error_counter(self, channel):
"""
Reads the current value of the error counters within the CAN controller.
:param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:return: Tuple with the TX and RX error counter.
:rtyp... |
java | private boolean add(Map<ClassDoc, SortedSet<ClassDoc>> map, ClassDoc superclass, ClassDoc cd) {
SortedSet<ClassDoc> list = map.get(superclass);
if (list == null) {
list = new TreeSet<>(comparator);
map.put(superclass, list);
}
if (list.contains(cd)) {
... |
java | protected XmlPullParser loadXml(String source) throws UnsupportedEncodingException, XmlPullParserException, IOException {
return loadXml(new ByteArrayInputStream(source.getBytes("UTF-8")));
} |
python | def validate(self, data):
"""
Validate data using sub defined schema/expressions ensuring at least
one value is valid.
:param data: data to be validated by provided schema.
:return: return validated data if not validation
"""
autos, errors = [], []
for s i... |
python | def lock(self, lock_name, timeout=900):
"""
Attempt to use lock and unlock, which will work if the Cache is Redis,
but fall back to a memcached-compliant add/delete approach.
If the Jobtastic Cache isn't Redis or Memcache, or another product
with a compatible lock or add/delete ... |
java | public static long[] label(IAtomContainer container, int[][] g, long[] initial) {
if (initial.length != g.length)
throw new IllegalArgumentException("number of initial != number of atoms");
return new Canon(g, initial, terminalHydrogens(container, g), false).labelling;
} |
python | def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, compute=True, **kwargs):
"""Save the *dataset_id* to file using *writer* (default: geotiff)."""
if writer is None and filename is None:
writer = 'geotiff'
elif writer is None:
writer = self.get_w... |
python | def put(self, obj):
"""Put request into queue.
Args:
obj (cheroot.server.HTTPConnection): HTTP connection
waiting to be processed
"""
self._queue.put(obj, block=True, timeout=self._queue_put_timeout)
if obj is _SHUTDOWNREQUEST:
return |
java | public Optional<SingularityTaskHistory> getHistoryForTask(String taskId) {
final Function<String, String> requestUri = (host) -> String.format(TASK_HISTORY_FORMAT, getApiBase(host), taskId);
return getSingle(requestUri, "task history", taskId, SingularityTaskHistory.class);
} |
python | def make_rfft_factors(axes, resshape, facshape, normshape, norm):
""" make the compression factors and compute the normalization
for irfft and rfft.
"""
N = 1.0
for n in normshape: N = N * n
# inplace modification is fine because we produce a constant
# which doesn't go into autograd.
... |
java | public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
XFactory factory = XFactoryRegistry.instance().currentDefault();
XTrace trace = factory.createTrace();
reader.moveDown();
XAttributeMap attributes = (XAttributeMap) context.convertAnother(
trace, XAttributeMap.class,... |
python | def _load_dataset_area(self, dsid, file_handlers, coords):
"""Get the area for *dsid*."""
try:
return self._load_area_def(dsid, file_handlers)
except NotImplementedError:
if any(x is None for x in coords):
logger.warning(
"Failed to loa... |
python | def parse_star_fusion(infile):
"""
Parses STAR-Fusion format and returns an Expando object with basic features
:param str infile: path to STAR-Fusion prediction file
:return: Fusion prediction attributes
:rtype: bd2k.util.expando.Expando
"""
reader = csv.reader(infile, delimiter='\t')
h... |
java | public DataSource<CloseableReference<CloseableImage>> fetchDecodedImage(
ImageRequest imageRequest,
Object callerContext,
ImageRequest.RequestLevel lowestPermittedRequestLevelOnSubmit,
@Nullable RequestListener requestListener) {
try {
Producer<CloseableReference<CloseableImage>> produ... |
python | def update_sibling_distance(self, sibling_distance, dest, topic):
"""Update the sibling distance for topic and destination broker."""
for source in six.iterkeys(sibling_distance[dest]):
sibling_distance[dest][source][topic] = \
dest.count_partitions(topic) - \
... |
python | def rfecv(model, X, y, ax=None, step=1, groups=None, cv=None,
scoring=None, **kwargs):
"""
Performs recursive feature elimination with cross-validation to determine
an optimal number of features for a model. Visualizes the feature subsets
with respect to the cross-validation score.
This h... |
python | def get_data(self, path, **params):
""" Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure.
"""
xml = self.get_response(path, **params)
try:
return parse(xml)
except Exception as err:
... |
java | public synchronized void obtainAuthorization(Context context, ResponseListener listener, Object... params) {
authorizationProcessManager.startAuthorizationProcess(context, listener);
} |
python | def insert(self, loc, column, value, allow_duplicates=False):
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int... |
python | def files(self, mountPoint):
"""Get an iterator of JFSFile() from the given mountPoint.
"mountPoint" may be either an actual mountPoint element from JFSDevice.mountPoints{} or its .name. """
if isinstance(mountPoint, six.string_types):
# shortcut: pass a mountpoint name
... |
python | def scoreGraph(titlesAlignments, find=None, showTitles=False, figureWidth=5,
figureHeight=5):
"""
NOTE: This function has probably bit rotted (but only a little).
Produce a rectangular panel of graphs, each of which shows sorted scores
for a title. Matches against a certain sequence titl... |
java | public ServiceFuture<OperationStatusResponseInner> deleteInstancesAsync(String resourceGroupName, String vmScaleSetName, List<String> instanceIds, final ServiceCallback<OperationStatusResponseInner> serviceCallback) {
return ServiceFuture.fromResponse(deleteInstancesWithServiceResponseAsync(resourceGroupName, v... |
python | def get_csbi(filehandle=None):
"""
Returns a CONSOLE_SCREEN_BUFFER_INFO structure for the given console or stdout
"""
if filehandle is None:
filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno())
csbi = ConsoleScreenBufferInfo()
KERNEL32.GetConsoleScreenBufferInfo(filehandle, ctype... |
java | public static base_response update(nitro_service client, rnat resource) throws Exception {
rnat updateresource = new rnat();
updateresource.network = resource.network;
updateresource.netmask = resource.netmask;
updateresource.natip = resource.natip;
updateresource.td = resource.td;
updateresource.aclname = ... |
java | public int[] otherOccurrences(Entity entity){
List<Integer> other = new ArrayList<Integer>();
for (int i = 0; i < doc.size(); i++) {
if (i == entity.startPosition) { continue; }
if (matches(entity, i)) {
other.add(Integer.valueOf(i));
}
}
return toArray(other);
} |
java | public void keepAliveSessions(long index, long timestamp) {
log.debug("Resetting session timeouts");
this.currentIndex = index;
this.currentTimestamp = Math.max(currentTimestamp, timestamp);
for (RaftSession session : sessions.getSessions(primitiveId)) {
session.setLastUpdated(timestamp);
}
... |
java | private String convertBlanksToNull(String string) {
if (string != null && string.trim().length() > 0) {
return string;
} else {
return null;
}
} |
python | def tabText(self, tab):
""" allow index or tab widget instance"""
if not isinstance(tab, int):
tab = self.indexOf(tab)
return super(FwTabWidget, self).tabText(tab) |
java | public static float min(final float a, final float b) {
if (a > b) {
return b;
}
if (a < b) {
return a;
}
/* if either arg is NaN, return NaN */
if (a != b) {
return Float.NaN;
}
/* min(+0.0,-0.0) == -0.0 */
/* 0... |
java | @SuppressWarnings({"WeakerAccess", "unused"})
public Picture renderToPicture(RenderOptions renderOptions)
{
Box viewBox = (renderOptions != null && renderOptions.hasViewBox()) ? renderOptions.viewBox
: rootElement.viewBox;
... |
java | private Metadata createMetadata(String tableName) {
Metadata metadata = new Metadata();
if (tableName != null) {
metadata.put(GRPC_RESOURCE_PREFIX_KEY, tableName);
}
return metadata;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.