language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public void scheduleWork(Address address, DistributableWork work) throws WorkException
{
if (trace)
log.tracef("SCHEDULE_WORK(%s, %s)", address, work);
ClassBundle cb = ClassBundleFactory.createClassBundle(work);
T addr = nodes.get(address);
sendMessage(addr, Request.S... |
java | public static Map mapValues(Mapper mapper, Map map) {
return mapValues(mapper, map, false);
} |
python | def add(self, **kwargs):
'''
in infor.
'''
post_data = {}
for key in self.request.arguments:
post_data[key] = self.get_arguments(key)[0]
MLog.add(post_data)
kwargs.pop('uid', None) # delete `uid` if exists in kwargs
self.redirect('/log/') |
java | protected boolean rule(List<ValidationMessage> errors, IssueType type, String path, boolean thePass, String msg) {
if (!thePass) {
errors.add(new ValidationMessage(source, type, -1, -1, path, msg, IssueSeverity.ERROR));
}
return thePass;
} |
java | public static String requireNotEmpty(String obj, String errorText) {
if (isBlank(obj)) {
throw new IllegalArgumentException(errorText);
}
return obj;
} |
java | private static String getHeaderParam( final String value, final String paramName ) {
if( value == null || value.length() == 0 )
return null;
final int length = value.length();
int start = value.indexOf(';') + 1;
if( start == 0 || start == length )
return null;
... |
java | @Override
protected void shutdown() {
if (isSmEnabled()) {
try {
// Try to send a last SM Acknowledgement. Most servers won't find this information helpful, as the SM
// state is dropped after a clean disconnect anyways. OTOH it doesn't hurt much either.
... |
python | def move_user(self, user_id, group_id):
"""
移动用户分组
详情请参考
http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html
:param user_id: 用户 ID, 可以是单个或者列表,为列表时为批量移动用户分组
:param group_id: 分组 ID
:return: 返回的 JSON 数据包
使用示例::
from wechatpy i... |
java | public static <K1, V1, K2, V2> MutableMap<K2, V2> collect(
Map<K1, V1> map,
Function<? super K1, ? extends K2> keyFunction,
Function<? super V1, ? extends V2> valueFunction)
{
return MapIterate.collect(map, keyFunction, valueFunction, UnifiedMap.<K2, V2>newMap());
} |
python | def _add_results(self, results, trial_id):
"""Add a list of results into db.
Args:
results (list): A list of json results.
trial_id (str): Id of the trial.
"""
for result in results:
self.logger.debug("Appending result: %s" % result)
resul... |
java | public void addInlineDeprecatedComment(Doc doc, Tag tag, Content htmltree) {
addCommentTags(doc, tag.inlineTags(), true, false, htmltree);
} |
java | @Override
public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor());
Method[] methodList = jclass.getMethods();
Method result = null;
... |
java | @Override
public MonetaryAmount apply(MonetaryAmount amount) {
if (termCurrency.equals(Objects.requireNonNull(amount).getCurrency())) {
return amount;
}
ExchangeRate rate = getExchangeRate(amount);
if (Objects.isNull(rate) || !amount.getCurrency().equals(rate.getBaseCurre... |
python | def handler(self, path='/app', ctx='all'):
"""
Handler that prints the project build log into the STDOUT (using the ``project`` package).
:param path(str): the project source code path, default is '/app'.
:param ctx(str): build log context file to be used, available options: validate, prepare, build or... |
java | private boolean persistSet(@Nullable final Set<String> set) {
if (set != null && shouldPersist()) {
if (set.equals(getPersistedSet(null))) {
return true;
}
Editor editor = getPreferenceManager().getSharedPreferences().edit();
editor.putStringSet(g... |
java | public void setTagList(java.util.Collection<Tag> tagList) {
if (tagList == null) {
this.tagList = null;
return;
}
this.tagList = new com.amazonaws.internal.SdkInternalList<Tag>(tagList);
} |
python | def validate(text, file, schema_type):
"""Validate JSON input using dependencies-schema"""
content = None
if text:
print('Validating text input...')
content = text
if file:
print('Validating file input...')
content = file.read()
if content is None:
click.se... |
java | public static <T1, T2, T3, R> TriFunction<T1, T2, T3, R> intercept(TriFunction<T1, T2, T3, R> innermost, TernaryInterceptor<T1, T2, T3>... interceptors) {
return new TernaryInterceptorChain<T1, T2, T3, R>(innermost, new ArrayIterator<TernaryInterceptor<T1, T2, T3>>(interceptors));
} |
python | def __process_equalities(self, equalities, momentequalities):
"""Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints
"""
monomial_sets = []
n_rows = 0
le = 0
if equal... |
python | def find_tokens(sentence, pattern):
"""Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence)
:param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement
:param pattern: pattern to which senten... |
python | def make_static_request(method, *args, **kwargs):
"""Creates a request from a static method function call."""
if args and not use_signature:
raise NotImplementedError("Only keyword arguments allowed in Python2")
if use_signature:
new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items... |
python | def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="Just a Fibonnaci demonstration")
pa... |
python | def _fill_text(self, text, width=None, indent=None):
""" Reflow text width while maintaining certain formatting
characteristics like double newlines and indented statements. """
assert isinstance(text, str)
if indent is None:
indent = NBSP * self._current_indent
asser... |
java | public static String getHashMD5(String str) {
try {
return getHash(str, "MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
} |
java | private void parseLimitFieldSize(Map<Object, Object> props) {
Object value = props.get(HttpConfigConstants.PROPNAME_LIMIT_FIELDSIZE);
if (null != value) {
try {
this.limitFieldSize = rangeLimit(convertInteger(value), HttpConfigConstants.MIN_LIMIT_FIELDSIZE, HttpConfigConstant... |
python | def response(data={}, status=200, message='OK'):
"""
Wraps the arguments in a dictionary and returns a HttpResponse object with
the HTTP status set to ``status``. The body of the response is JSON data
on the format::
{
"status": 400,
"message": "OK",
"data": ... |
python | def _from_dict(cls, _dict):
"""Initialize a ClassificationCollection object from a json dictionary."""
args = {}
if 'classifier_id' in _dict:
args['classifier_id'] = _dict.get('classifier_id')
if 'url' in _dict:
args['url'] = _dict.get('url')
if 'collectio... |
python | def _get_logger(self, handler):
''' Initialize a PCAP stream for logging data '''
log_file = self._get_log_file(handler)
if not os.path.isdir(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
handler['log_rot_time'] = time.gmtime()
return pcap.open(... |
java | private String makeDescription(Object value) {
String answer; // Not initialized, so the compiler tells if we miss a
// case
if (value == null) {
answer = "null";
} else if (value instanceof String) {
answer = "\"" + value + "\"";
} else {
... |
python | def rename_script(rename=None): # noqa: E501
"""Rename a script
Rename a script # noqa: E501
:param rename: The data needed to save this script
:type rename: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
rename = Rename.from_dict(connexion.request.get_json()) #... |
python | def AddNewSignature(self, pattern, offset=None):
"""Adds a signature.
Args:
pattern (bytes): pattern of the signature.
offset (int): offset of the signature. None is used to indicate
the signature has no offset. A positive offset is relative from
the start of the data a negative... |
python | def genes_with_peak(self, peaks, transform_func=None, split=False,
intersect_kwargs=None, id_attribute='ID', *args,
**kwargs):
"""
Returns a boolean index of genes that have a peak nearby.
Parameters
----------
peaks : string or py... |
java | private void placeBridgedRing(IRing ring, IAtomContainer sharedAtoms, Point2d sharedAtomsCenter, Vector2d ringCenterVector, double bondLength) {
IAtom[] bridgeAtoms = getBridgeAtoms(sharedAtoms);
IAtom bondAtom1 = bridgeAtoms[0];
IAtom bondAtom2 = bridgeAtoms[1];
List<IAtom> otherAtoms ... |
java | public BaseDataJsonFieldBo removeDataAttr(String dPath) {
Lock lock = lockForWrite();
try {
JacksonUtils.deleteValue(dataJson, dPath);
return (BaseDataJsonFieldBo) setAttribute(ATTR_DATA,
SerializationUtils.toJsonString(dataJson), false);
} finally {
... |
python | def hash_filesystem(filesystem, hashtype='sha1'):
"""Utility function for running the files iterator at once.
Returns a dictionary.
{'/path/on/filesystem': 'file_hash'}
"""
try:
return dict(filesystem.checksums('/'))
except RuntimeError:
results = {}
logging.warni... |
java | @Override
public byte getParityErrorChar() throws UnsupportedCommOperationException {
byte ret;
logger.fine("getParityErrorChar()");
ret = nativeGetParityErrorChar();
logger.fine("getParityErrorChar() returns "
+ ret);
return (ret);
} |
java | static byte[] marshallIDL5(final AttributeImpl attribute) throws DevFailed {
XLOGGER.entry();
final AttributeValue_5 attributeValue = TangoIDLAttributeUtil.toAttributeValue5(attribute,
attribute.getReadValue(), attribute.getWriteValue());
return marshallIDL5(attributeValue);
... |
python | def ldap_server_host_use_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(ldap_server, "host")
hostname_key = ET.SubElement(host,... |
java | public String determineAddresses() {
if (CollectionUtils.isEmpty(this.parsedAddresses)) {
return this.host + ":" + this.port;
}
List<String> addressStrings = new ArrayList<>();
for (Address parsedAddress : this.parsedAddresses) {
addressStrings.add(parsedAddress.host + ":" + parsedAddress.port);
}
ret... |
python | def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for e... |
python | def setColorSet( self, colorSet ):
"""
Resets the tree to use the inputed color set information.
:param colorSet | <XColorSet>
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
self.clear()
self._colorSet = colorSet
... |
python | def _is_json_serialized_jws(self, json_jws):
"""
Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False
"""
json_ser_keys = {"payload", "signatures"}
flattened_json_ser_keys = {"payload", "signature"}
if not json... |
java | public static StringDistance[] buildArray(String classNames)
{
String classNamesArray[] = split(classNames);
StringDistance learners[] = new StringDistance[classNamesArray.length];
for (int i = 0; i < classNamesArray.length; i++) {
learners[i] = build(classNamesArray[i]).getDistance();
}
re... |
java | @Nullable Node<E> transferOrCombine(@NonNull Node<E> first, Node<E> last) {
int index = index();
AtomicReference<Node<E>> slot = arena[index];
for (;;) {
Node<E> found = slot.get();
if (found == null) {
if (slot.compareAndSet(null, first)) {
for (int spin = 0; spin < SPINS; sp... |
java | public boolean hasUnhandled() {
for(int i = 0; i < getNumEntries(); i++) {
boolean handled = getEntry(i).hasUnhandled();
if(handled) {
return true;
}
}
return false;
} |
python | def _input_stmt(self, stmt: object) -> tuple:
"""
takes the input key from kwargs and processes it to aid in the generation of a model statement
:param stmt: str, list, or dict that contains the model information.
:return: tuple of strings one for the class statement one for the model st... |
java | public byte[] getBytes() throws IOException {
InputStream input = getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len;
try {
while ((len = input.read(buffer)) != -1) {
... |
python | def get_illegal_targets(part, include):
"""
Retrieve the illegal parent parts where `Part` can be moved/copied.
:param part: `Part` to be moved/copied.
:type part: :class:`Part`
:param include: `Set` object with id's to be avoided as target parent `Part`
:type include: set
:return: `List` o... |
java | public Bundler put(String key, Parcelable value) {
delegate.putParcelable(key, value);
return this;
} |
java | private <T> void add(EjbDescriptor<T> ejbDescriptor) {
InternalEjbDescriptor<T> internalEjbDescriptor = InternalEjbDescriptor.of(ejbDescriptor);
ejbByName.put(ejbDescriptor.getEjbName(), internalEjbDescriptor);
ejbByClass.put(ejbDescriptor.getBeanClass(), internalEjbDescriptor.getEjbName());
... |
python | def nnd_hotdeck_using_feather(receiver = None, donor = None, matching_variables = None, z_variables = None):
"""
Not working
"""
import feather
assert receiver is not None and donor is not None
assert matching_variables is not None
temporary_directory_path = os.path.join(config_files_direc... |
java | private static void copyStream(Reader r, Writer w) throws IOException {
char[] buffer = new char[4096];
for (int n = 0; -1 != (n = r.read(buffer));) {
w.write(buffer, 0, n);
}
} |
python | def create_driver(self):
"""Create a selenium driver using specified config properties
:returns: a new selenium driver
:rtype: selenium.webdriver.remote.webdriver.WebDriver
"""
driver_type = self.config.get('Driver', 'type')
try:
if self.config.getboolean_opt... |
java | @Reference(authors = "G. Marsaglia", //
title = "Evaluating the Normal Distribution", //
booktitle = "Journal of Statistical Software 11(4)", //
url = "https://doi.org/10.18637/jss.v011.i04", //
bibkey = "doi:10.18637/jss.v011.i04")
public static double cdf(double x, double mu, double sigma) {... |
java | public OvhOperation serviceName_cluster_clusterId_allowedNetwork_POST(String serviceName, String clusterId, OvhClusterAllowedNetworkFlowTypeEnum flowType, String network) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/cluster/{clusterId}/allowedNetwork";
StringBuilder sb = path(qPath, serviceName, c... |
java | public static Map<String, Vocab> parsePrefixDeclaration(String value,
Map<String, ? extends Vocab> predefined, Map<String, ? extends Vocab> known,
Set<String> forbidden, Report report, EPUBLocation location)
{
Map<String, Vocab> vocabs = Maps.newHashMap(predefined);
Map<String, String> mappings = ... |
python | def in_dateheure(objet, pattern):
""" abstractSearch dans une date-heure datetime.datetime (cf abstractRender.dateheure) """
if objet:
pattern = re.sub(" ", '', pattern)
objet_str = abstractRender.dateheure(objet)
return bool(re.search(pattern, objet_str))
ret... |
python | def destroy(self, dir_or_plan=None, force=IsFlagged, **kwargs):
"""
refer to https://www.terraform.io/docs/commands/destroy.html
force/no-color option is flagged by default
:return: ret_code, stdout, stderr
"""
default = kwargs
default['force'] = force
opt... |
python | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs):
"""
Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header... |
python | def routingAreaUpdateAccept(PTmsiSignature_presence=0,
MobileId_presence=0, MobileId_presence1=0,
ReceiveNpduNumbersList_presence=0,
GprsTimer_presence=0, GmmCause_presence=0):
"""ROUTING AREA UPDATE ACCEPT Section 9.4.15"""
a =... |
java | public GetAppResponse queryApp(GetAppRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getApp(), "The parameter app should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.GET, request,... |
python | def additions_umount(mount_point):
'''
Unmount VirtualBox Guest Additions CD from the temp directory.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_umount
:param mount_point: directory VirtualBox Guest Additions is mounted to
:return: True or an string with error
... |
java | public static <T> T randomEle(List<T> list) {
return randomEle(list, list.size());
} |
java | public static void write(InputStream in, Path path, StandardCopyOption op) {
try {
Files.copy(in, path, op);
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
python | def convert_to_sequences(dataset, vocab):
"""This function takes a dataset and converts
it into sequences via multiprocessing
"""
start = time.time()
dataset_vocab = map(lambda x: (x, vocab), dataset)
with mp.Pool() as pool:
# Each sample is processed in an asynchronous manner.
o... |
java | public void truncateStream(String scope, String streamName, Duration latency) {
DYNAMIC_LOGGER.incCounterValue(globalMetricName(TRUNCATE_STREAM), 1);
DYNAMIC_LOGGER.incCounterValue(TRUNCATE_STREAM, 1, streamTags(scope, streamName));
truncateStreamLatency.reportSuccessValue(latency.toMillis());
... |
python | def get_returns(
self,
jid,
minions,
timeout=None):
'''
Get the returns for the command line interface via the event system
'''
minions = set(minions)
if timeout is None:
timeout = self.opts['timeout']
start = in... |
java | public void setDeliveryData(com.google.api.ads.admanager.axis.v201808.DeliveryData deliveryData) {
this.deliveryData = deliveryData;
} |
java | public ServiceFuture<ProtectionIntentResourceInner> createOrUpdateAsync(String vaultName, String resourceGroupName, String fabricName, String intentObjectName, ProtectionIntentResourceInner parameters, final ServiceCallback<ProtectionIntentResourceInner> serviceCallback) {
return ServiceFuture.fromResponse(crea... |
java | public void removeDataNode(Node rootNode, String dataId) throws RepositoryException
{
Node parentNode = null;
try
{
Node node = getDataNode(rootNode, dataId);
parentNode = node.getParent();
node.remove();
parentNode.save();
}
catch (InvalidItemStateEx... |
python | def confirm_input(user_input):
"""Check user input for yes, no, or an exit signal."""
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except AttributeError:
u_inp = user_input
# Check for exit signal
if u_inp in ... |
python | def mft_offset(self):
"""
Returns:
int: MFT Table offset from the beginning of the partition in bytes
"""
return self.bpb.bytes_per_sector * \
self.bpb.sectors_per_cluster * self.extended_bpb.mft_cluster |
python | def build_dataset(filename, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
encodings = dict(list(map(reversed, enumerate(string.printable))))
digitize = lambda char: encodings[char] if char in encodings else len(encodings)
encode_line = lambda line: np.array(list(m... |
java | @GET
public List<ITemplate> getTemplates(@QueryParam("providerId") String providerId, @QueryParam("serviceIds") String serviceIds) {
logger.debug("StartOf getTemplates - REQUEST for /templates");
TemplateHelperE templateRestHelper = getTemplateHelper();
// we remove the blank spaces just in... |
python | def select_bed(bed):
"""
Return non-overlapping set of ranges, choosing high scoring blocks over low
scoring alignments when there are conflicts.
"""
ranges = [Range(x.seqid, x.start, x.end, float(x.score), i) for i, x in enumerate(bed)]
selected, score = range_chain(ranges)
selected = [bed[... |
java | public static KeyStore pem2Keystore(File pemFile) throws IOException, CertificateException,
InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException {
String certAndKey = FileUtils.readFileToString(pemFile, StandardCharsets.US_ASCII);
byte[] certBytes = extractCertificate(certAndKey);
byte[]... |
python | def shorten(text):
""" Reduce text length for displaying / logging purposes.
"""
if len(text) >= MAX_DISPLAY_LEN:
text = text[:MAX_DISPLAY_LEN//2]+"..."+text[-MAX_DISPLAY_LEN//2:]
return text |
java | @SuppressWarnings("NarrowingCompoundAssignment")
private static long normalizedDuration(long seconds, int nanos) {
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
nanos %= NANOS_PER_SECOND;
}
if (seconds > 0 && nanos < 0) ... |
java | public static void runExample(
AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId)
throws RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterfa... |
python | def _get_facvar(self, polynomial):
"""Return dense vector representation of a polynomial. This function is
nearly identical to __push_facvar_sparse, but instead of pushing
sparse entries to the constraint matrices, it returns a dense
vector.
"""
facvar = [0] * (self.n_var... |
python | def _validate_excludes(self, excluded_fields, field, value):
""" {'type': ('hashable', 'list'),
'schema': {'type': 'hashable'}} """
if isinstance(excluded_fields, Hashable):
excluded_fields = [excluded_fields]
# Mark the currently evaluated field as not required for now... |
python | def post_request(self, endpoint, body=None, timeout=-1):
"""
Perform a POST request to a given endpoint in UpCloud's API.
"""
return self.request('POST', endpoint, body, timeout) |
java | public short getShort(String key) {
addToDefaults(key, null);
String value = getRequired(key);
return Short.valueOf(value);
} |
python | def parse_assertion_id_request_response(self, response, binding):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
res = self._parse_response(response, AssertionIDResponse, "",... |
java | public EClass getDownload() {
if (downloadEClass == null) {
downloadEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(LogPackage.eNS_URI).getEClassifiers()
.get(15);
}
return downloadEClass;
} |
java | public Vector3D mult(Vector3D source) {
Vector3D result = new Vector3D();
result.setX(m00 * source.getX() + m01 * source.getY() + m02);
result.setY(m10 * source.getX() + m11 * source.getY() + m12);
return result;
} |
python | def deductible(self, loss_type, dummy=None):
"""
:returns: the deductible fraction of the asset cost for `loss_type`
"""
val = self.calc(loss_type, self.deductibles, self.area, self.number)
if self.calc.deduct_abs: # convert to relative value
return val / self.calc(l... |
java | public List<AdapterMonitor> getAdapterMonitors(RuntimeContext context) {
return getAdapterMonitors().stream().filter(monitor ->
monitor.isEnabled(context)
).collect(Collectors.toList());
} |
java | private static boolean exemptedByAnnotation(
List<? extends AnnotationTree> annotations,
VisitorState state) {
for (AnnotationTree annotation : annotations) {
if (((JCAnnotation) annotation).type != null) {
TypeSymbol tsym = ((JCAnnotation) annotation).type.tsym;
if (EXEMPTING_METH... |
python | def evaluate_classifier_fraction_sparse(input_,
labels,
per_example_weights=None,
topk=1,
name=PROVIDED,
phase=Phase.tra... |
python | def from_serializable_dict(x):
"""
Reconstruct a dictionary by recursively reconstructing all its keys and
values.
This is the most hackish part since we rely on key names such as
__name__, __class__, __module__ as metadata about how to reconstruct
an object.
TODO: It would be cleaner to a... |
python | def getGUA(self, filterByPrefix=None):
"""get expected global unicast IPv6 address of OpenThreadWpan
Args:
filterByPrefix: a given expected global IPv6 prefix to be matched
Returns:
a global IPv6 address
"""
print '%s call getGUA' % self.port
pri... |
python | def add_error_marker(text, position, start_line=1):
"""Add a caret marking a given position in a string of input.
Returns (new_text, caret_line).
"""
indent = " "
lines = []
caret_line = start_line
for line in text.split("\n"):
lines.append(indent + line)
if 0 <= positio... |
python | def walk_mapsources(mapsources, root=""):
"""
recursively walk through foldernames of mapsources.
Like os.walk, only for a list of mapsources.
Args:
mapsources (list of MapSource):
Yields:
(root, foldernames, maps)
>>> mapsources = load_maps("test/mapsources")
>>> pprint(... |
python | def extract_rar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RAR archive."""
cmdlist = [cmd, 'x']
if not interactive:
cmdlist.extend(['-p-', '-y'])
cmdlist.extend(['--', os.path.abspath(archive)])
return (cmdlist, {'cwd': outdir}) |
python | def grey_reconstruction(image, mask, footprint=None, offset=None):
'''Perform a morphological reconstruction of the image
grey_dilate the image, constraining each pixel to have a value that is
at most that of the mask.
image - the seed image
mask - the mask, giving the maximum allowed value at ... |
java | public static OWLValueObject buildFromObject(OWLModel model, Object object) throws NotYetImplementedException, OWLTranslationException {
return buildFromClasAndObject(model, OWLURIClass.from(object), object);
} |
java | private static InputStreamWithMetadata compressStreamWithGZIPNoDigest(
InputStream inputStream) throws SnowflakeSQLException
{
try
{
FileBackedOutputStream tempStream =
new FileBackedOutputStream(MAX_BUFFER_SIZE, true);
CountingOutputStream countingStream =
new CountingO... |
java | @Override
public Stream<? extends Ticket> getTicketsStream() {
return this.ticketCatalog.findAll()
.stream()
.map(t -> {
val sql = String.format("select t from %s t", getTicketEntityName(t));
val query = (org.hibernate.query.Query<Ticket>) entityManage... |
java | @SuppressWarnings("unchecked")
public <T extends Tree> List<T> getLeaves(List<T> list) {
if (isLeaf()) {
list.add((T) this);
} else {
for (Tree kid : children()) {
kid.getLeaves(list);
}
}
return list;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.