language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def gps2_raw_send(self, time_usec, fix_type, lat, lon, alt, eph, epv, vel, cog, satellites_visible, dgps_numch, dgps_age, force_mavlink1=False):
'''
Second GPS data. Coordinate frame is right-handed, Z-axis up (GPS
frame).
time_usec : Time... |
java | public static aaa_stats get(nitro_service service) throws Exception{
aaa_stats obj = new aaa_stats();
aaa_stats[] response = (aaa_stats[])obj.stat_resources(service);
return response[0];
} |
python | def add_pool_member(hostname, username, password, name, member):
'''
A function to connect to a bigip device and add a new member to an existing pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
na... |
python | def expose(self, commandObject, exceptionType):
"""
Expose a function for processing a given AMP error.
"""
thunk = super(_AMPErrorExposer, self).expose(
(commandObject.commandName,
commandObject.errors.get(exceptionType)))
def thunkplus(function):
... |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OpenVPNCollector, self).get_default_config()
config.update({
'path': 'openvpn',
'instances': 'file:///var/log/openvpn/status.log',
'timeout': '10... |
python | def update(self, id=None, new_data={}, **kwargs):
"""Update an object on the server.
Args:
id: ID of the object to update (can be None if not required)
new_data: the update data for the object
**kwargs: Extra options to send to the server (e.g. sudo)
Returns... |
java | MutableNode splitKey(final int prefixLength, final byte nextByte) {
final byte[] keyBytes = keySequence.getBytesUnsafe();
final ByteIterable prefixKey;
if (prefixLength == 0) {
prefixKey = ByteIterable.EMPTY;
} else if (prefixLength == 1) {
prefixKey = SingleByteI... |
java | @FFDCIgnore(Exception.class)
public Transaction getTransaction() throws SystemException {
Transaction tx = null;
RRSSynchronizerTransaction rrsTx = null;
try {
tx = tm.getTransaction();
if (tx != null) {
rrsTx = new RRSSynchronizerTransaction(tx);
... |
python | def extend_with(self, rdf_file):
"""Extend the RDF graph of this HierarchyManager with another RDF file.
Parameters
----------
rdf_file : str
An RDF file which is parsed such that the current graph and the
graph described by the file are merged.
"""
... |
java | @SuppressWarnings("unchecked")
public static void registerValidator(Class<? extends IValidator<?>> validator) {
if (validator == null) {
throw new IllegalArgumentException("validator cannot be null");
}
ValidatorFactory.registerValidatorClasses(validator);
} |
java | public ConnectedStreams<IN1, IN2> keyBy(int keyPosition1, int keyPosition2) {
return new ConnectedStreams<>(this.environment, inputStream1.keyBy(keyPosition1),
inputStream2.keyBy(keyPosition2));
} |
python | def get_network_when(tnet, i=None, j=None, t=None, ij=None, logic='and', copy=False, asarray=False):
"""
Returns subset of dataframe that matches index
Parameters
----------
tnet : df or TemporalNetwork
TemporalNetwork object or pandas dataframe edgelist
i : list or int
get node... |
java | @SuppressWarnings("rawtypes")
@Override
public Iterable<Class<?>> getSuites() {
TestsToRun scanned = scanResult.applyFilter(new PowerUnitProviderScannerFilter(parameters), testClassLoader);
return runOrderCalculator.orderTestClasses(scanned);
} |
python | def rouge_l_sentence_level(eval_sentences, ref_sentences):
"""Computes ROUGE-L (sentence level) of two collections of sentences.
Source: https://www.microsoft.com/en-us/research/publication/
rouge-a-package-for-automatic-evaluation-of-summaries/
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)... |
java | @Override
public CommerceSubscriptionEntry fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(CommerceSubscriptionEntryModelImpl.ENTITY_CACHE_ENABLED,
CommerceSubscriptionEntryImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
CommerceS... |
java | @Override
protected void write(LogLevel level, String correlationId, Exception error, String message) {
if (this.getLevel().equals(level))
return;
StringBuilder build = new StringBuilder();
build.append('[');
build.append(correlationId != null ? correlationId : "---");
build.append(':');
build.append(l... |
java | public FutureAPIResponse setItemAsFuture(String iid, Map<String, Object> properties,
DateTime eventTime) throws IOException {
return createEventAsFuture(new Event()
.event("$set")
.entityType("item")
.entityId(iid)
.eventTime(eventTime)
.properties(properties));
} |
python | def vrrpe(self, **kwargs):
"""Enable or Disable Vrrpe.
Args:
ip_version (str): The IP version ('4' or '6') for which vrrpe
should be enabled/disabled. Default: `4`.
enable (bool): If vrrpe should be enabled or disabled. Default:
``True``.
... |
java | public void shutdown() {
synchronized (lock) {
if (isShutdown) {
return;
}
LOG.info("Shutting down the network environment and its components.");
// terminate all network connections
try {
LOG.debug("Shutting down network connection manager");
connectionManager.shutdown();
}
catch (... |
java | @Override
public String[] getResources() {
String resource = getResource();
if (resource == null) {
return null;
}
return resource.split(" ");
} |
python | def cleanup_temporary_directories(self):
"""Delete the build directories and any temporary directories created by pip."""
while self.build_directories:
shutil.rmtree(self.build_directories.pop())
for requirement in self.reported_requirements:
requirement.remove_temporary_... |
python | def exists(name, index=None):
'''
Add the directory to the system PATH at index location
index
Position where the directory should be placed in the PATH. This is
0-indexed, so 0 means to prepend at the very start of the PATH.
.. note::
If the index is not specified, and... |
python | def sourcelines(self):
"""The sourcecode of the file as list of unicode strings."""
# get sourcecode from loader or file
source = None
if self.loader is not None:
try:
if hasattr(self.loader, 'get_source'):
source = self.loader.get_source(s... |
java | public static ByteBuffer[] getWrappedByteBuffers(WsByteBuffer wsbuffers[]) {
// Create the buffer array to return.
ByteBuffer buffers[] = new ByteBuffer[wsbuffers.length];
boolean foundNullBuffer = false;
int i = 0;
// Loop through each buffer of the input array.
for (i =... |
python | def to_affine(aff, dims=None):
'''
to_affine(None) yields None.
to_affine(data) yields an affine transformation matrix equivalent to that given in data. Such a
matrix may be specified either as (matrix, offset_vector), as an (n+1)x(n+1) matrix, or, as an
n x (n+1) matrix.
to_affine(data, dim... |
python | def register_presence_callback(self, type_, from_, cb):
"""
Register a callback to be called when a presence stanza is received.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data:`None` for a wildcard... |
java | PartialMatch newPartialMatch(char[] key, PartialMatch pm) {
if (tc.isEntryEnabled())
tc.entry(this,cclass, "newPartialMatch", "key: "+new String(key)+", pm:"+pm);
PartialMatch ans = new PartialMatch(key, pm, owner);
if (tc.isEntryEnabled())
tc.exit(this,cclass, "newPartialMatch", ans);
retur... |
java | public TrainingSpecification withSupportedHyperParameters(HyperParameterSpecification... supportedHyperParameters) {
if (this.supportedHyperParameters == null) {
setSupportedHyperParameters(new java.util.ArrayList<HyperParameterSpecification>(supportedHyperParameters.length));
}
for ... |
python | def _get_template_list(self):
" Get the hierarchy of templates belonging to the object/box_type given. "
t_list = []
if hasattr(self.obj, 'category_id') and self.obj.category_id:
cat = self.obj.category
base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name... |
java | @Override
public boolean accept(File pathname) {
boolean accept = super.accept(pathname);
if (accept) {
try {
accept &= shouldProcess(pathname);
} catch (AnalysisException ex) {
throw new UnexpectedAnalysisException(ex.getMessage(), ex.getCause... |
python | def _construct(self):
"""
Construct the data dependence graph.
We track the following types of dependence:
- (Intra-IRSB) temporary variable dependencies
- Register dependencies
- Memory dependencies, although it's very limited. See below.
We track the following... |
java | SchemaFuture installHandlers(XMLReader in, SchemaReceiverImpl sr) {
Handler h = new Handler(sr);
in.setContentHandler(h);
return h;
} |
python | def column_count(self, ):
"""Return the number of columns that the children have
If there are no children, return the column count of its own data.
:returns: the column count of the children data
:rtype: int
:raises: None
"""
if self.child_count():
r... |
python | def uninstall_visa_handler(self, session, event_type, handler, user_handle=None):
"""Uninstalls handlers for events.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be u... |
java | private static void addNonBlank(final String string, final List<String> strings) {
if (!StringUtils.isBlank(string) && !"/".equals(string))
strings.add(string);
} |
java | public static String intersectingConcatenate(String a, String b) {
// find length of maximum possible match
int lenOfA = a.length();
int lenOfB = b.length();
int minIntersectionLen = min(lenOfB, lenOfA);
// search down from maximum match size, to get longest possible intersection
for (int size... |
python | def help_center_incremental_articles_list(self, start_time=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path = "/api/v2/help_center/incremental/articles.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update... |
python | def lon_bounds(self):
"""Longitude of grid interfaces (degrees)
:getter: Returns the bounds of axis ``'lon'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lon'`` axis can be found.
"""
... |
python | def map_function(func_str, fw_action_addtion=None,bw_action_addtion=None, alias_func=None):
''' Sample usage:
print map_function('set',alias_func = "ini_items");# -> ini_items
print map_function('set',fw_action_addtion="action_steps_",bw_action_addtion="_for_upd",alias_func = "ini_items"); # -> a... |
python | def current_iteration(self):
"""Get the index of the current iteration.
Returns
-------
cur_iter : int
The index of the current iteration.
"""
out_cur_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetCurrentIteration(
self.handle,
... |
python | def idle_task(self):
'''handle GUI elements'''
if not self.menu_needs_refreshing:
return
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu)
#(re)create the menu
if mp... |
java | public final void lazyEvalReplicationMethod(
final Map<String, Object> pAddParam) throws Exception {
Long replicationMethodId;
try {
replicationMethodId = Long.parseLong(pAddParam
.get("replicationMethodId").toString());
} catch (Exception e) {
throw new ExceptionWithCode(ExceptionWi... |
python | def get_data():
"""Retrieve static data from the game."""
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
m = maps.get("Sequencer") # Arbitrary ladder map.
create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap(
map_path=m.path, map_data=m.data(run_config))... |
java | public void printSurvivor(PrintStream tty, List<ClassStats> list, boolean orderByName, long minSize, int age,
int minAge) {
if (orderByName) {
Collections.sort(list, ClassStats.NAME_COMPARATOR);
} else {
Collections.sort(list, ClassStats.SUR_SIZE_COMPARATOR);
}
tty.println("\nSurvivor Object Histogram... |
java | protected static boolean checkDiagram(String fileName, String modelFileName, String[] diagramSuffixes, String[] modelSuffixes) {
for (String modelSuffix : modelSuffixes) {
if (modelFileName.endsWith(modelSuffix)) {
String caseFilePrefix = modelFileName.substring(0, modelFileName.length() - modelSuffix... |
java | public static Email emlToEmail(@Nonnull final String eml) {
final MimeMessage mimeMessage = emlToMimeMessage(checkNonEmptyArgument(eml, "eml"), createDummySession());
return mimeMessageToEmail(mimeMessage);
} |
python | def get_values(self):
"""Correctly set the ``owner_type`` attribute."""
attrs = super(Host, self).get_values()
if '_owner_type' in attrs and attrs['_owner_type'] is not None:
attrs['owner_type'] = attrs.pop('_owner_type')
else:
attrs.pop('_owner_type')
ret... |
python | def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
... |
java | @Override
public Collection<PointOfInterest> findInRect(BoundingBox bb, PoiCategoryFilter filter,
List<Tag> patterns, int limit) {
// Clear previous results
this.ret.clear();
// Query
Cursor cursor = null;
try {
i... |
python | def check_permissions(self, request):
"""Permission checking for DRF."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... |
java | public ArrayList<String> credit_balance_GET(OvhType type) throws IOException {
String qPath = "/me/credit/balance";
StringBuilder sb = path(qPath);
query(sb, "type", type);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} |
python | def list_broadcasts():
"""
List all registered broadcasts as a list of objects with
keys "cast" and "onto".
"""
casts = [{'cast': b[0], 'onto': b[1]} for b in orca.list_broadcasts()]
return jsonify(broadcasts=casts) |
java | public static <T> Consumer<T> ignore(Runnable runnable, Class<T> ignored) {
dbc.precondition(runnable != null, "cannot ignore parameter of a null runnable");
return first -> runnable.run();
} |
python | def read(self, size=1024):
"""Read and return at most ``size`` characters from the pty.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
data = self.fileobj.recv(size)
if not data:
self.flag_eof = True
... |
python | def _get_content(self, context):
"""
Add the csrf_token_value because the mixin use render_to_string
and not render.
"""
self._valid_template()
context.update({
"csrf_token_value": get_token(self.request)
})
return render_to_str... |
python | def read_custom_resource_definition_status(self, name, **kwargs):
"""
read status of the specified CustomResourceDefinition
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_custom_resou... |
java | private int synchroizeTaskIDToHierarchy(Task parentTask, int currentID)
{
for (Task task : parentTask.getChildTasks())
{
task.setID(Integer.valueOf(currentID++));
add(task);
currentID = synchroizeTaskIDToHierarchy(task, currentID);
}
return currentID;
} |
python | def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(m... |
java | public static String encode(List<XMLEvent> theEvents) {
try {
StringWriter w = new StringWriter();
XMLEventWriter ew = XmlUtil.createXmlFragmentWriter(w);
for (XMLEvent next : theEvents) {
if (next.isCharacters()) {
ew.add(next);
} else {
ew.add(next);
}
}
ew.close();
return w... |
python | def update_vehicle_menu(self):
'''update menu for new vehicles'''
self.vehicle_menu.items = []
for s in sorted(self.vehicle_list):
clist = self.module('param').get_component_id_list(s)
if len(clist) == 1:
name = 'SysID %u: %s' % (s, self.vehicle_name_by_sy... |
python | def resolve_domain(self, pipeline):
"""Resolve a concrete domain for ``pipeline``.
"""
domain = pipeline.domain(default=self._default_domain)
if domain is GENERIC:
raise ValueError(
"Unable to determine domain for Pipeline.\n"
"Pass domain=<des... |
python | def calc_arguments(args):
'''
calc_arguments is a calculator that parses the command-line arguments for the registration
command and produces the subject, the model, the log function, and the additional options.
'''
(args, opts) = _retinotopy_parser(args)
# We do some of the options right here..... |
java | private int binarySearch(int fromIndex, int toIndex, Composite name, Comparator<Composite> comparator)
{
int low = fromIndex;
int mid = toIndex;
int high = mid - 1;
int result = -1;
while (low <= high)
{
mid = (low + high) >> 1;
if ((result = c... |
python | def create_stream(stream_name, num_shards, region=None, key=None, keyid=None, profile=None):
'''
Create a stream with name stream_name and initial number of shards num_shards.
CLI example::
salt myminion boto_kinesis.create_stream my_stream N region=us-east-1
'''
conn = _get_conn(region=re... |
java | public void encrypt(final String userName, final byte[] password, final MessageEncryption msgEncryption) {
setUserName(null);
setPassword(null);
setNonce(null);
setCreated(null);
byte[] nonce = null;
switch (msgEncryption) {
case NONE: {
... |
python | def _shannon_radii_from_cn(species_list, cn_roman, radius_to_compare=0):
"""
Utility func to get Shannon radii for a particular coordination number.
As the Shannon radii depends on charge state and coordination number,
species without an entry for a particular coordination number will
be skipped.
... |
java | public void beginUpdateGatewaySettings(String resourceGroupName, String clusterName, UpdateGatewaySettingsParameters parameters) {
beginUpdateGatewaySettingsWithServiceResponseAsync(resourceGroupName, clusterName, parameters).toBlocking().single().body();
} |
java | public static ns_detail_vlan add(nitro_service client, ns_detail_vlan resource) throws Exception
{
resource.validate("add");
return ((ns_detail_vlan[]) resource.perform_operation(client, "add"))[0];
} |
java | @javax.annotation.Nonnull
public java.util.Optional<net.morimekta.providence.model.FilePos> optionalEndPos() {
return java.util.Optional.ofNullable(mEndPos);
} |
java | public Object value(int i, String key) {
Object data = getData();
if (data instanceof List) {
List list = (List) data;
if (list.size() > 0) {
Map map = (Map) list.get(i);
return map.get(key);
}
} else if (data instanceof Map) {
... |
java | public GrRelation createRelation(String type, GrNode startNode, GrNode endNode) {
return this.resultHandler.getLocalElements().createRelation(type, startNode, endNode);
} |
python | def eni_present(
name,
subnet_id=None,
subnet_name=None,
private_ip_address=None,
description=None,
groups=None,
source_dest_check=True,
allocate_eip=None,
arecords=None,
region=None,
key=None,
keyid=None,
profile=No... |
java | public void storeIfNew(final DbArtifact fromClient) {
final DbArtifact existing = repositoryHandler.getArtifact(fromClient.getGavc());
if(existing != null){
existing.setLicenses(fromClient.getLicenses());
store(existing);
}
if(existing == null){
store(f... |
java | protected static int postorder_dfs( int j , int k , int []w, int[] post, int N ) {
final int next = N;
final int stack = 2*N;
int top = 0; // top of the stack
w[stack+top] = j;
while( top >= 0 ) {
int p = w[stack+top]; // next index in the stack to process
... |
java | protected LocPathIterator createDTMIterator(
Compiler compiler, int opPos) throws javax.xml.transform.TransformerException
{
LocPathIterator lpi = (LocPathIterator)WalkerFactory.newDTMIterator(compiler, opPos,
(compiler.getLocationPathDepth() <= 0));
return lpi... |
python | def rsdl_r(self, AX, Y):
"""Compute primal residual vector.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
# Avoid calling cnst_c() more than once in case it is expensive
... |
java | public FacesConfigBehaviorType<WebFacesConfigDescriptor> getOrCreateBehavior()
{
List<Node> nodeList = model.get("behavior");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigBehaviorTypeImpl<WebFacesConfigDescriptor>(this, "behavior", model, nodeList.get(0));
}
... |
java | @Override
public void onLoaderReset(Loader<SortedList<Metadata>> loader) {
progressBar.setVisibility(View.INVISIBLE);
recyclerView.setVisibility(View.VISIBLE);
super.onLoaderReset(loader);
} |
python | def fix_e714(self, result):
"""Fix object identity should be 'is not' case."""
(line_index, offset, target) = get_index_offset_contents(result,
self.source)
# to convert once 'is not' -> 'is'
before_target = target[:offset... |
python | async def _set_whitelist(self):
"""
Whitelist domains for the messenger extensions
"""
page = self.settings()
if 'whitelist' in page:
await self._send_to_messenger_profile(page, {
'whitelisted_domains': page['whitelist'],
})
... |
java | public static boolean set(String value) {
if (StringUtil.isEmpty(value)) {
throw new IllegalArgumentException("Can not set an empty msgId. If you want to clear msgId of current context, use clear() instead.");
}
if (Objects.equals(value, MsgIdHolder.get())) {
//no need ma... |
java | public static void copyDirectories(File[] directories, String storageFolder) throws IOException {
storageFolder = checkFolder(storageFolder) + ValueConsts.SEPARATOR;
for (File directory : directories) {
copyDirectory(directory, new File(storageFolder + directory.getName()));
}
} |
python | def numpy_to_texture(image):
"""Convert a NumPy image array to a vtk.vtkTexture"""
if not isinstance(image, np.ndarray):
raise TypeError('Unknown input type ({})'.format(type(image)))
if image.ndim != 3 or image.shape[2] != 3:
raise AssertionError('Input image must be nn by nm by RGB')
g... |
java | public void updateExceptions() {
m_exceptionsList.setDates(m_model.getExceptions());
if (m_model.getExceptions().size() > 0) {
m_exceptionsPanel.setVisible(true);
} else {
m_exceptionsPanel.setVisible(false);
}
} |
python | def config(filename):
"""
Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list
"""
Config = collections.namedtuple('Config', [
'git',
'lock_file',
'version',
'name',
'src',
'dst',
... |
python | async def SetHostMachineNetworkConfig(self, config, tag):
'''
config : typing.Sequence[~NetworkConfig]
tag : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Provisioner',
request='SetHostMachineNetw... |
python | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, ... |
java | public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
File tempWriteDir = (File) servletContext
.getAttribute("javax.servlet.context.tempdir");
servletContext.setAttribute("audioFilePath", FILE_PROTOCOL + tempWriteDi... |
java | public static ComputationGraph restoreComputationGraph(@NonNull InputStream is, boolean loadUpdater)
throws IOException {
checkInputStream(is);
File tmpFile = null;
try{
tmpFile = tempFileFromStream(is);
return restoreComputationGraph(tmpFile, loadUpdater);
... |
java | @NotNull
public T queryNN() throws SQLException {
T res = null;
try (ResultSet r = statement.executeQuery()) {
if (r.next()) {
res = resultMapper.map(r);
}
Objects.requireNonNull(res);
return res;
}
} |
java | public static double solve(Matrix A, Preconditioner Ap, double[] b, double[] x, double tol, int itol) {
return solve(A, Ap, b, x, tol, itol, 2 * Math.max(A.nrows(), A.ncols()));
} |
java | private static Map<String, Set<BioPAXElement>> collectEntityRefs(Collection<SIFInteraction> inters)
{
Map<String, Set<BioPAXElement>> map = new HashMap<String, Set<BioPAXElement>>();
for (SIFInteraction inter : inters)
{
if (!map.containsKey(inter.sourceID))
map.put(inter.sourceID, new HashSet<BioPAXElem... |
python | def data(self):
"""
TODO: What is the right way to do this?
"""
if not self.body:
return self.body
elif self.body is EMPTY:
return EMPTY
elif self.content_type and self.content_type.startswith('application/json'):
try:
i... |
python | def _metadata_fixed(self):
"""
Define the most important tab parametersfor a fixed-type tab file
"""
# Number of fluids and index of all the phisical properties
fluids = {}
props_idx = {}
with open(self.abspath) as fobj:
contents = fobj.readlin... |
java | public static <KeyIn, ValueIn, ValueOut> Supplier<KeyIn, ValueIn, ValueOut> all() {
return new AcceptAllSupplier(null);
} |
python | def complete(self, stream):
"""Complete the pending stream.
Any connections made to :py:attr:`stream` are connected to `stream` once
this method returns.
Args:
stream(Stream): Stream that completes the connection.
"""
assert not s... |
python | def represented_args(args, separator=" "):
"""
Args:
args (list | tuple | None): Arguments to represent
separator (str | unicode): Separator to use
Returns:
(str): Quoted as needed textual representation
"""
result = []
if args:
for text in args:
resu... |
java | private static synchronized void startup() {
try {
if (CONFIG == null) {
CONFIG = ApiConfigurations.fromProperties();
}
ObjectMapper objectMapper = new ObjectMapper();
AppIdentityService appIdentityService = new AppIdentityService(CONFIG, objectMapper, true);
MetricMonitorService monito... |
python | def is_paths(maybe_paths, marker='*'):
"""
Does given object 'maybe_paths' consist of path or path pattern strings?
"""
return ((is_path(maybe_paths) and marker in maybe_paths) or # Path str
(is_path_obj(maybe_paths) and marker in maybe_paths.as_posix()) or
(is_iterable(maybe_pa... |
java | public static <T> List<T> page(int pageNo, int pageSize, List<T> list) {
if (isEmpty(list)) {
return new ArrayList<>(0);
}
int resultSize = list.size();
// 每页条目数大于总数直接返回所有
if (resultSize <= pageSize) {
if (pageNo <= 1) {
return Collections.unmodifiableList(list);
} else {
// 越界直接返... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.