language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | static <T> Single<T> wrap(
SingleSource<T> source, Collection<ReactiveInstrumenter> instrumentations) {
if (source instanceof Callable) {
return new RxInstrumentedCallableSingle<>(source, instrumentations);
}
return new RxInstrumentedSingle<>(source, instrumentations);
... |
python | def generate_lines(self, infile):
""" Split file into lines
return dict with line=input, depth=n
"""
pound = '#'
for line in infile:
heading = self.hash_count(line)
indent = self.hash_count(line, pound=' ')
yield dict(line=line.str... |
python | def create_project(project_name, skel="basic"):
"""
Create the project
"""
project_dir = get_project_dir_path(project_name)
app_tpl = pkg_resources.resource_string(__name__, '%s/app.py' % (SKELETON_DIR))
propel_tpl = pkg_resources.resource_string(__name__, '%s/propel.yml' % (SKELETON_DIR))
c... |
python | def draw(instance):
"""Generic draw function"""
# Draw Wavefront instance
if isinstance(instance, Wavefront):
draw_materials(instance.materials)
# Draw single material
elif isinstance(instance, Material):
draw_material(instance)
# Draw dict of materials
elif isinstance(instan... |
java | @Override
public Double getProductCoefficient(IAtomContainer product) {
logger.debug("Setting product coefficient: ", product, "" + super.getProductCoefficient(product));
return super.getProductCoefficient(product);
} |
python | def download_url(url, destination=None, progress_bar=True):
"""Download a URL to a local file.
Parameters
----------
url : str
The URL to download.
destination : str, None
The destination of the file. If None is given the file is saved to a temporary directory.
progress_bar : bo... |
java | public void checkWritePermission(TimedDirContext ctx) throws OperationNotSupportedException {
if (!iWriteToSecondary) {
String providerURL = getProviderURL(ctx);
if (!getPrimaryURL().equalsIgnoreCase(providerURL)) {
String msg = Tr.formatMessage(tc, WIMMessageKey.WRITE_TO... |
java | @When("^I send a message '(.+?)' to the kafka topic named '(.+?)'")
public void sendAMessage(String message, String topic_name) throws Exception {
commonspec.getKafkaUtils().sendMessage(message, topic_name);
} |
python | def download_file(self, file_path, store_directory=None):
"""
Download a file from betfair historical and store in given directory or current directory.
:param file_path: the file path as given by get_file_list method.
:param store_directory: directory path to store data files i... |
python | def get_child_by_qualifier(self, parent_qualifier):
"""
:param parent_qualifier: time_qualifier of the parent process
:return: <HierarchyEntry> child entry to the HierarchyEntry associated with the parent_qualifier
or None if the given parent_qualifier is not registered in this h... |
python | def send_custom_hsm(self, whatsapp_id, template_name, language, variables):
"""
Sends an HSM with more customizable fields than the send_hsm function
"""
data = {
"to": whatsapp_id,
"type": "hsm",
"hsm": {
"namespace": self.hsm_namespac... |
java | @Override
protected void afterPaint(final RenderContext renderContext) {
super.afterPaint(renderContext);
if (profileBtn.isPressed()) {
// UIC serialization stats
UicStats stats = new UicStats(UIContextHolder.getCurrent());
WComponent currentComp = this.getCurrentComponent();
if (currentComp != null... |
python | def get_info(self, full=False):
" Return printable information about current site. "
if full:
context = self.as_dict()
return "".join("{0:<25} = {1}\n".format(
key, context[key]) for key in sorted(context.iterkeys()))
return "%s [%s]" % (self.g... |
python | def FixedOffset(offset, _tzinfos = {}):
"""return a fixed-offset timezone based off a number of minutes.
>>> one = FixedOffset(-330)
>>> one
pytz.FixedOffset(-330)
>>> one.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 66600)
>>> one.dst(datetime.datetime.... |
python | def remove_users(self, users=None):
"""
Remove users (specified by email address) from this user group.
In case of ambiguity (two users with same email address), the non-AdobeID user is preferred.
:param users: list of emails for users to remove from the group.
:return: the Group... |
java | public static Pattern wellFormedToPattern(String value) {
StringBuilder sb = new StringBuilder(value.length() + 4);
for (int x = 0; x < value.length(); x++) {
if (value.charAt(x) == '*') {
sb.append(".*");
} else if (value.charAt(x) == '?') {
sb.ap... |
python | def fetch(self):
"""
Fetch a FormInstance
:returns: Fetched FormInstance
:rtype: twilio.rest.authy.v1.form.FormInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
... |
java | public KeyBundle createKey(String vaultBaseUrl, String keyName, JsonWebKeyType kty, Integer keySize, List<JsonWebKeyOperation> keyOps, KeyAttributes keyAttributes, Map<String, String> tags) {
return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty, keySize, keyOps, keyAttributes, tags).toBlocking().... |
java | protected String gitFindLastTag() throws MojoFailureException, CommandLineException {
String tag = executeGitCommandReturn("for-each-ref", "--sort=-*authordate", "--count=1",
"--format=\"%(refname:short)\"", "refs/tags/");
// https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3
... |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Empty, Empty> runAssetDiscoveryAsync(OrganizationName parent) {
RunAssetDiscoveryRequest request =
RunAssetDiscoveryRequest.newBuilder()
.setParent(parent ==... |
python | def filter_keep_phenotype_entry_ids(self, entry):
'''
doubt this should be kept
'''
omim_id = str(entry['mimNumber'])
otype = self.globaltt['obsolete']
if omim_id in self.omim_type:
otype = self.omim_type[omim_id]
if otype == self.globaltt['obs... |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.CFC__CFIRG_LEN:
setCFIRGLen(CFIRG_LEN_EDEFAULT);
return;
case AfplibPackage.CFC__RETIRED1:
setRetired1(RETIRED1_EDEFAULT);
return;
case AfplibPackage.CFC__TRIPLETS:
getTriplets().clear();
return;
... |
java | protected void refresh()
{
if (log.isDebugEnabled())
log.debug("Refresh this transaction for reuse: " + this);
try
{
// we reuse ObjectEnvelopeTable instance
objectEnvelopeTable.refresh();
}
catch (Exception e)
{
... |
python | def in_project_scope(self, filename):
'''
Note: in general this method should not be used (apply_files_filter should be used
in most cases as it also handles the project scope check).
'''
try:
return self._in_project_scope_cache[filename]
except KeyError:
... |
java | public OvhPayment withdrawal_withdrawalId_payment_GET(String withdrawalId) throws IOException {
String qPath = "/me/withdrawal/{withdrawalId}/payment";
StringBuilder sb = path(qPath, withdrawalId);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPayment.class);
} |
python | def get_essential_properties(self):
"""Constructs the dictionary of essential properties
Constructs the dictionary of essential properties, named
cpu, cpu_arch, local_gb, memory_mb. The MACs are also returned
as part of this method.
"""
sushy_system = self._get_sushy_sys... |
java | public void debug(String format, Object param1, Object param2) {
formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
} |
java | public static LinkedHashMap<String, String> extractTags(String s) {
LinkedHashMap<String, String> map = Maps.newLinkedHashMap();
int c = s.lastIndexOf(CHECKSUM_DELIMITER);
if (c == -1) {
return map;
}
s = s.substring(0, c);
String[] items = s.split(PARAMETER_D... |
python | def get_contents_dir(node):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
for n in sorted(node.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (n.get_csig(), n.name))
return ''.join(content... |
python | def OnTableChanged(self, event):
"""Table changed event handler"""
if hasattr(event, 'updated_cell'):
# Event posted by cell edit widget. Even more up to date
# than the current cell's contents
self.ignore_changes = True
try:
self.SetVal... |
python | def setShowTypeButton(self, state):
"""
Sets whether or not the type button is visible.
:param state | <bool>
"""
self._showTypeButton = state
if not state:
self.uiTypeBTN.hide()
else:
self.uiTypeBTN.show() |
python | def get_memory_usage(user=None):
"""
Returns a three-tupel with memory usage for the given user.
The result contains::
(total memory, largest process' memory, largest process name)
:param user: String representing the user. If `None`, the total size of
all processes for all users will b... |
python | def _get_encoder_method(stream_type):
"""A function to get the python type to device cloud type converter function.
:param stream_type: The streams data type
:return: A function that when called with the python object will return the serializable
type for sending to the cloud. If there is no function f... |
python | def get_osdb_hash(self):
"""
Get the hash of this local videofile
:return: hash as string
"""
if self._osdb_hash is None:
self._osdb_hash = self._calculate_osdb_hash()
return self._osdb_hash |
python | def secho(text, file=None, nl=True, err=False, color=None, **styles):
"""This function combines :func:`echo` and :func:`style` into one
call. As such the following two calls are the same::
click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))
All keyw... |
java | public void deleteGroup(Integer groupId) throws IOException {
String tailUrl = GitlabGroup.URL + "/" + groupId;
retrieve().method(DELETE).to(tailUrl, Void.class);
} |
java | public List<Node> pathQuery(String pathQuery) throws XmlModelException {
// validations
if(pathQuery == null || pathQuery.trim().length() == 0) {
return new ArrayList<Node>();
}
pathQuery = pathQuery.trim();
if(! reQueryFormat.matcher(pathQuery).matches()) {
... |
java | public void read() {
if (isTransient) {
AVIMMessage lastMessage = getLastMessage();
Map<String, Object> params = new HashMap<String, Object>();
if (null != lastMessage) {
params.put(Conversation.PARAM_MESSAGE_QUERY_MSGID, lastMessage.getMessageId());
params.put(Conversation.PARAM_M... |
java | private void clinkstep8(DBIDRef id, DBIDArrayIter it, int n, WritableDBIDDataStore pi, WritableDoubleDataStore lambda, WritableDoubleDataStore m) {
DBIDVar p_i = DBIDUtil.newVar(), pp_i = DBIDUtil.newVar();
for(it.seek(0); it.getOffset() < n; it.advance()) {
p_i.from(pi, it); // p_i = pi[i]
pp_i.fro... |
python | def getset(self, key, value, *, encoding=_NOTSET):
"""Set the string value of a key and return its old value."""
return self.execute(b'GETSET', key, value, encoding=encoding) |
python | def dataverse_search_doi(doi):
"""
Fetches metadata pertaining to a Digital Object Identifier (DOI) in the
Harvard Dataverse.
Args:
doi (str): The Digital Object Identifier (DOI) of the entry in the
Dataverse.
Raises:
requests.exceptions.HTTPError: The given DOI does no... |
python | def parent(self):
"""Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined
"""
try:
return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)
... |
java | public static <A, B> Choice2<A, B> b(B b) {
return new _B<>(b);
} |
python | def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueErro... |
python | def pertibate_to_obj(cls, columns, pertibate_values,
generated_columns=None, filter_func=None,
max_size=None, deliminator=None, tab=None):
"""
This will create and add rows to the table by pertibating the
parameters for the provided colum... |
python | def namedb_get_namespace_ready( cur, namespace_id, include_history=True ):
"""
Get a ready namespace, and optionally its history.
Only return a namespace if it is ready.
"""
select_query = "SELECT * FROM namespaces WHERE namespace_id = ? AND op = ?;"
namespace_rows = namedb_query_execute( cur, ... |
python | def detect_infinitive_phrase(sentence):
"""Given a string, return true if it is an infinitive phrase fragment"""
# eliminate sentences without to
if not 'to' in sentence.lower():
return False
doc = nlp(sentence)
prev_word = None
for w in doc:
# if statement will execute exactly... |
java | public void addHeaders(HttpServletRequest reqSource, HttpRequestBase httpTarget)
{
Enumeration<?> headerNames = reqSource.getHeaderNames();
while (headerNames.hasMoreElements())
{
String key = headerNames.nextElement().toString();
if (CONTENT_LENGTH.equalsIgnoreCase(key))
continue;... |
java | public void saveTaskUpdateForRetry(SingularityTaskHistoryUpdate taskHistoryUpdate) {
String parentPath = ZKPaths.makePath(SNS_TASK_RETRY_ROOT, taskHistoryUpdate.getTaskId().getRequestId());
if (!isChildNodeCountSafe(parentPath)) {
LOG.warn("Too many queued webhooks for path {}, dropping", parentPath);
... |
python | def add_result(self, source, found, runtime):
"""
Adds a new record to the statistics 'database'. This function is
intended to be called after a website has been scraped. The arguments
indicate the function that was called, the time taken to scrap the
website and a boolean indica... |
python | def grid_track(lat,lon,sla,remove_edges=None,backbone=None,interp_over_continents=True):
"""
# GRID_TRACK
# @summary: This function allow detecting gaps in a set of altimetry data and rebin this data regularly, with informations on gaps.
# @param lat {type:numeric} : latitude
# @param lon {type... |
python | def load_shapefile(self, feature_type, base_path):
"""Load downloaded shape file to QGIS Main Window.
TODO: This is cut & paste from OSM - refactor to have one method
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads... |
java | private void net( WritableRandomIter hacksIter, WritableRandomIter netIter ) {
// calculates the max order of basin (max hackstream value)
pm.beginTask("Extraction of rivers of chosen order...", nRows);
for( int r = 0; r < nRows; r++ ) {
for( int c = 0; c < nCols; c++ ) {
... |
java | @Deprecated
public String readLine() throws IOException, IllegalStateException {
LOG.trace("enter HttpConnection.readLine()");
assertOpen();
return HttpParser.readLine(inputStream);
} |
python | def cmd_http_methods(self):
"""Reports a breakdown of how many requests have been made per HTTP
method (GET, POST...).
"""
methods = defaultdict(int)
for line in self._valid_lines:
methods[line.http_request_method] += 1
return methods |
java | public void marshall(Snapshot snapshot, ProtocolMarshaller protocolMarshaller) {
if (snapshot == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(snapshot.getDirectoryId(), DIRECTORYID_BINDING);
... |
java | private static void invokeCallbackMethod(Method callbackMethod, Object listener, Object entity) {
try {
callbackMethod.invoke(listener, entity);
} catch (Exception exp) {
String message = String.format("Failed to execute callback method %s of class %s",
callbackMethod.getName(), callbackMe... |
java | private void formatFile(File file, ResultCollector rc, Properties hashCache, String basedirPath)
throws MojoFailureException, MojoExecutionException {
try {
doFormatFile(file, rc, hashCache, basedirPath, false);
} catch (IOException | MalformedTreeException | BadLocationException... |
java | public String getLabelText() {
String value = (String) getStateHelper().eval(PropertyKeys.labelText);
return value;
} |
python | def firmware_version(self):
"""Return the firmware version."""
if (self._firmware_version is None) or \
(datetime.now() - timedelta(hours=24) > self._fw_last_read):
self._fw_last_read = datetime.now()
with self._bt_interface.connect(self._mac) as connection:
... |
python | def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value) |
python | def generate_DJ_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VD junction.
Sets the attributes Tdj, Sdj, Ddj, rTdj, and rDdj.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tdj
Tdj = {}
for aa... |
java | public void remove (Object object) {
if (!idToObject.containsValue(object, true)) return;
int objectID = idToObject.findKey(object, true, -1);
idToObject.remove(objectID);
objectToID.remove(object, 0);
if (TRACE) trace("kryonet", "Object " + objectID + " removed from ObjectSpace: " + object);
} |
python | def delete_source_map(srcmap_file, names, logger=None):
"""Delete a map from a binned analysis source map file if it exists.
Parameters
----------
srcmap_file : str
Path to the source map file.
names : list
List of HDU keys of source maps to be deleted.
"""
with fits.open(sr... |
java | public String getDateTime(Date date, int format) {
return CmsDateUtil.getDateTime(date, format, m_locale);
} |
java | public void batchCommitted()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "batchCommitted");
synchronized(flushedStreamSets)
{
Iterator<StreamSet> itr = flushedStreamSets.iterator();
while(itr.hasNext())
{
StreamSet streamSet = itr.nex... |
java | void checkForSetter(Map<Integer, Instruction> pcMap) throws ClassParseException {
final String methodName = getMethod().getName();
if (methodName.startsWith("set")) {
final String rawVarNameCandidate = methodName.substring(3);
final String firstLetter = rawVarNameCandidate.substring(0, 1).... |
python | def get_profile(self, profile_count=50):
"""
Get profile of query execution time.
:param int profile_count:
Number of profiles to retrieve,
counted from the top query in descending order by
the cumulative execution time.
:return: Profile information f... |
java | public void readConnections(ConfigParams connections) {
synchronized (_lock) {
_items.clear();
for (Map.Entry<String, String> entry : connections.entrySet()) {
DiscoveryItem item = new DiscoveryItem();
item.key = entry.getKey();
item.connection = ConnectionParams.fromString(entry.getValue());
_i... |
java | public ScoreNode nextScoreNode() throws IOException {
if (nodes.hasNext()) {
NodeImpl n = (NodeImpl) nodes.next();
return new ScoreNode(n.getData().getIdentifier(), 1.0f);
} else {
return null;
}
} |
java | @Override
public BigIntegerMapper build(String field) {
return new BigIntegerMapper(field, column, validated, digits);
} |
python | def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundErr... |
python | def parse_kegg_entries(f, context=None):
"""Iterate over entries in KEGG file."""
section_id = None
entry_line = None
properties = {}
for lineno, line in enumerate(f):
if line.strip() == '///':
# End of entry
mark = FileMark(context, entry_line, 0)
yield ... |
java | public LibraryService getLibraryService() {
if (_libraryService == null) {
synchronized (CCApi2.class) {
if (_libraryService == null) {
_libraryService = _retrofit.create(LibraryService.class);
}
}
}
return _libraryServ... |
java | public void write()
throws IOException
{
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( m_outputStream ) );
for( String line : m_content )
{
writer.write( line );
writer.newLine();
}
writer.flush();
writer.close();
... |
java | public static HTTPResponse put(URL url, String username, String password, long timeout, boolean redirect, String mimetype, String charset, String useragent, ProxyData proxy,
lucee.commons.net.http.Header[] headers, Object body) throws IOException {
HttpPut put = new HttpPut(url.toExternalForm());
setBody(put, bo... |
java | @Override
protected VoltTable.ColumnInfo getColumnInfo(String columnTypeName, String colName) {
return super.getColumnInfo(getVoltColumnTypeName(columnTypeName), colName);
} |
java | @Override
public Namespace convert(BELNamespaceDefinition bnd) {
if (bnd == null) {
return null;
}
return new Namespace(bnd.getPrefix(), bnd.getResourceLocation());
} |
python | def main():
'''main routine'''
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit('Error: Expecting azurermconfig.json in current folder')
tenant_id = config_data['tenantI... |
java | public State get() {
InternalState internalState = currentInternalState.get();
while (!internalState.isRead) {
// Slow path, the state is first time read. Change the state only if no other changes
// happened between the moment initialState is read and this moment. This ensures that this
// me... |
python | def quat2Yaw(qw, qx, qy, qz):
'''
Translates from Quaternion to Yaw.
@param qw,qx,qy,qz: Quaternion values
@type qw,qx,qy,qz: float
@return Yaw value translated from Quaternion
'''
rotateZa0=2.0*(qx*qy + qw*qz)
rotateZa1=qw*qw + qx*qx - qy*qy - qz*qz
rotateZ=0.0
if(rotateZa0... |
java | @Override
public List<Inspection> getInspectionsForHitNumber(int hitNumber) {
ResponsePayload payload = (ResponsePayload) payloads.values().toArray()[hitNumber];
return payload.getInspections();
} |
java | public void checkZipCode(String zipcode) throws CmsIllegalArgumentException {
if (!CmsStringUtil.validateRegex(zipcode, ZIPCODE_REGEX, true)) {
throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_ZIPCODE_VALIDATION_1, zipcode));
}
} |
python | def wait_event(self, filter: Callable[[T_Event], bool] = None) -> Awaitable[T_Event]:
"""Shortcut for calling :func:`wait_event` with this signal in the first argument."""
return wait_event([self], filter) |
python | def __format_occurence(self, occurence):
"""
Formats the given occurence and returns the matching rich html text.
:param occurence: Occurence to format.
:type occurence: Occurence
:return: Rich text.
:rtype: unicode
"""
color = "rgb({0}, {1}, {2})"
... |
java | public void removeIncompleteUpload(String bucketName, String objectName)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException {
for (R... |
java | public void marshall(BatchGetTriggersRequest batchGetTriggersRequest, ProtocolMarshaller protocolMarshaller) {
if (batchGetTriggersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchGetTr... |
python | def _GetCompressedStreamTypes(self, mediator, path_spec):
"""Determines if a data stream contains a compressed stream such as: gzip.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpe... |
python | def create_writer(self, name, *args, **kwargs):
"""Create a new writer instance for a given format."""
self._check_format(name)
return self._formats[name]['writer'](*args, **kwargs) |
java | public static <T extends DajlabModelInterface> DajlabModel loadModel(final File file) {
Gson fxGson = FxGson.fullBuilder().create();
DajlabModel model = new DajlabModel();
try {
JsonParser jsonParser = new JsonParser();
JsonReader jsonReader = new JsonReader(new FileReader(file));
jsonReader.begi... |
java | public TerminalSize max(TerminalSize other) {
return withColumns(Math.max(columns, other.columns))
.withRows(Math.max(rows, other.rows));
} |
java | public <E extends Exception> boolean setRightIf(final R newRight, Try.BiPredicate<? super Triple<L, M, R>, ? super R, E> predicate) throws E {
if (predicate.test(this, newRight)) {
this.right = newRight;
return true;
}
return false;
} |
java | public final Tuple7<T5, T6, T7, T8, T9, T10, T11> skip4() {
return new Tuple7<>(v5, v6, v7, v8, v9, v10, v11);
} |
python | def OSLibpath(self):
"""
Microsoft Windows SDK Libraries Paths
"""
ref = os.path.join(self.si.WindowsSdkDir, 'References')
libpath = []
if self.vc_ver <= 9.0:
libpath += self.OSLibraries
if self.vc_ver >= 11.0:
libpath += [os.path.join(re... |
python | def build_byte_align_buff(bits):
"""Pad the left side of a bitarray with 0s to align its length with byte boundaries.
Args:
bits: A bitarray to be padded and aligned.
Returns:
A newly aligned bitarray.
"""
bitmod = len(bits)%8
if bitmod == 0:
rdiff = bitarray()
else... |
python | def is_installed(self, name: str) -> bool:
"""
Indicates a given Docker image is installed on this server.
Parameters:
name: the name of the Docker image.
Returns:
`True` if installed; `False` if not.
"""
assert name is not None
try:
... |
java | private static boolean migrate(TaskListener listener, String target) throws IOException, InterruptedException {
PrintStream out = listener.getLogger();
File home = Jenkins.getInstance().getRootDir();
// do the migration
LibZFS zfs = new LibZFS();
ZFSFileSystem existing = zfs.get... |
python | def geocode(address, required_precision_km=1.):
""" Identifies the coordinates of an address
:param address:
the address to be geocoded
:type value:
String
:param required_precision_km:
the maximum permissible geographic uncertainty for the geocoding
:type required_precision... |
python | def _copy_body_to_tempfile(cls, environ):
"""
Copy wsgi.input to a tempfile so it can be reused.
"""
try:
length = int(environ.get('CONTENT_LENGTH', 0))
except ValueError:
length = 0
try:
fileobj = tempfile.SpooledTemporaryFile(1024*10... |
java | private int parseOffsetDefaultLocalizedGMT(String text, int start, int[] parsedLen) {
int idx = start;
int offset = 0;
int parsed = 0;
do {
// check global default GMT alternatives
int gmtLen = 0;
for (String gmt : ALT_GMT_STRINGS) {
in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.