language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def zopen(filename, *args, **kwargs):
"""
This function wraps around the bz2, gzip and standard python's open
function to deal intelligently with bzipped, gzipped or standard text
files.
Args:
filename (str/Path): filename or pathlib.Path.
\*args: Standard args for python open(..). ... |
python | def restore(self, state):
"""Unserialize saved note data.
Args:
state (dict): Serialized state to load.
"""
self._clear()
self._parseUserInfo({'labels': state['labels']})
self._parseNodes(state['nodes'])
self._keep_version = state['keep_version'] |
python | def get_age(self, **kwargs):
"""
Returns the particlees age (how long it has been forced) in a variety of units.
Rounded to 8 decimal places.
Parameters:
units (optional) = 'days' (default), 'hours', 'minutes', or 'seconds'
"""
try:
units = kwargs... |
java | public static boolean createEmptyFile(File file) {
try {
file.getParentFile().mkdirs();
return file.createNewFile();
} catch (Exception e) {
return JMExceptionManager.handleExceptionAndReturnFalse(log, e,
"createEmptyFile", file);
}
} |
python | def convert_path(cls, file):
"""
Check to see if an extended path is given and convert appropriately
"""
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
... |
java | public static void storeTimestamp(File tsFile, Date buildDate) throws MojoExecutionException {
try {
if (tsFile.exists()) {
tsFile.delete();
}
File dir = tsFile.getParentFile();
if (!dir.exists()) {
if (!dir.mkdirs()) {
... |
python | def main(book_dir=BOOK_PATH, include_tags=None, verbosity=1):
r""" Parse all the asciidoc files in book_dir, returning a list of 2-tuples of lists of 2-tuples (tagged lines)
>>> main(BOOK_PATH, verbosity=0)
[('.../src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ..... |
java | public static CmsResource readOrCreateDetailOnlyPage(CmsObject cms, CmsUUID detailId, String detailOnlyRootPath)
throws CmsException {
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsResource containerpage;
if (rootCms.existsResource(d... |
python | def method_file_cd(f):
"""
A decorator to cd back to the original directory where this object was
created (useful for any calls to TObject.Write).
This function can decorate methods.
"""
@wraps(f)
def wrapper(self, *args, **kwargs):
with preserve_current_directory():
self... |
python | def search_datasets(dataset_id=None,
dataset_name=None,
collection_name=None,
data_type=None,
unit_id=None,
scenario_id=None,
metadata_key=None,
metadata_val=None,
attr_id = None,
... |
java | public PropertyOwner retrieveUserProperties()
{
if (m_registration == null)
{
BasePanel parent = this.getParentScreen();
if (parent == null)
return null;
if (!(parent instanceof TopScreen))
return parent.retrieveUserProperties(); ... |
java | public void write(Object obj) {
try {
writer.addRecord((Object[]) obj);
} catch (DBFException e) {
throw new RuntimeException(e.getMessage());
}
} |
java | public static String getTopic(final Map<String, Object> stormConfig) {
if (stormConfig.containsKey(CONFIG_TOPIC)) {
// get configured topic from config as string, removing whitespace from both ends
final String topic = String.valueOf(stormConfig.get(CONFIG_TOPIC)).trim();
if ... |
java | public void configureCoreProperties(
Project project,
AppEngineCoreExtensionProperties appEngineCoreExtensionProperties,
String taskGroup,
boolean requiresAppEngineJava) {
project
.getLogger()
.warn(
"WARNING: You are a using release candidate "
+ ... |
python | def deleted_keys(self) -> Iterable[bytes]:
"""
List all the keys that have been deleted.
"""
for key, value in self._changes.items():
if value is DELETED:
yield key |
java | private boolean goToNextStartPosition() throws IOException {
int nextSpans1StartPosition;
int nextSpans1EndPosition;
int nextSpans2StartPosition;
int nextSpans2EndPosition;
// loop over span1
while ((nextSpans1StartPosition = spans1.spans
.nextStartPosition()) != NO_MORE_POSITIONS) {
... |
java | public static BigMoney add(BigMoney money1, BigMoney money2) {
if (money1 == null) {
return money2;
}
if (money2 == null) {
return money1;
}
return money1.plus(money2);
} |
python | def ssh(name):
"""Executes the given command"""
env.host_string = lib.get_env_host_string()
print("\nExecuting the command '{0}' on node {1}...".format(
name, env.host_string))
# Execute remotely using either the sudo or the run fabric functions
with settings(hide("warnings"), warn_only=Tr... |
java | public static void main(String[] args) {
if (args.length < 3) {
System.out.println(
"Usage: java twitter4j.examples.user.UpdateFriendship [screen name] [enable device notification(true|false)] [enable retweets(true|false)]");
System.exit(-1);
}
try {
... |
python | def _lsm_fix_strip_offsets(self):
"""Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented).
"""
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series... |
python | def domain_add(self, domain, description=DESCRIPTION):
"""
Sends a POST to /1.0/domains/ using this post-data:
{"domain": "www.fogfu.com",
"description":"Added by tagcube-api"}
:param domain: The domain name to add as a new resource
:return: The newly created r... |
java | protected List<Event> filterEvents(List<Event> toFilter, Long lastIndex) {
List<Event> events = toFilter;
if (lastIndex != null) {
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
Long eventIndex = event.getWaitIndex();
if (lastIndex.equals(eventIndex)) {
events = events.su... |
java | private String getEntryEditURI(final String fsid, final boolean relative, final boolean singleEntry) {
String entryURI = null;
if (relative) {
if (singleEntry) {
entryURI = fsid;
} else {
entryURI = singular + "/" + fsid;
}
} el... |
java | public Consumer<UpdateCellOp> asUpdateCellConsumer() {
return new Consumer<UpdateCellOp>() {
@Override
public void accept(UpdateCellOp op) throws Exception {
update(op.getArg1());
}
};
} |
python | def get_players(self, team):
"""
Loads the players of a team.
Args:
* team (:obj: json): a team in json format obtained from the service.
Returns:
* :obj: json: the players of the team
"""
team_id = self.__get_team_id(team)
self.logger.de... |
java | public static ModelNode createBatchRequest(ModelNode... steps) {
final ModelNode composite = new ModelNode();
composite.get(OPERATION).set(BATCH);
composite.get(ADDRESS).setEmptyList();
final ModelNode stepsNode = composite.get(BATCH_STEPS);
for (ModelNode step : steps) {
... |
java | public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: PortableTypeGenerator <classDir>");
System.exit(0);
}
try {
instrumentClasses(new File(args[0]));
}
catch (Exception e) {
System.out.println... |
python | def data(self):
"""list of mean numeric values of categorical responses."""
means = []
table = self._slice.as_array()
products = self._inner_prods(table, self.values)
for axis, product in enumerate(products):
if product is None:
means.append(product)
... |
java | private void update(GeometryIndex index, boolean moveToBack) {
try {
VectorObject shape;
if (index == null) {
shape = nullShape;
} else {
shape = shapes.get(index);
}
if (shape != null) {
// We don't consider position at this point. Just style:
ShapeStyle style = styleFactory.create(edi... |
python | def register_channel(model_class, search_fields=()):
"""
Register channel for model
:param model_class: model to register channel for
:param search_fields:
:return:
"""
if len(search_fields) == 0:
search_fields = get_fields_with_icontains_filter(model_class)
channel_class = type(... |
python | def add_arc(self, src, dst, char):
"""Adds a new Arc
Args:
src (int): The source state identifier
dst (int): The destination state identifier
char (str): The character for the transition
Returns:
None
"""
# assert type(src) == type(... |
python | def get_mlp():
"""Get multi-layer perceptron"""
data = mx.symbol.Variable('data')
fc1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, name='fc1',
prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 128} }")
act1 = mx.symbol.CaffeOp(data_0=fc1, prototxt="layer... |
java | @Override
public boolean isIsolationLevelSwitchingSupport() {
// We assume that we are running on the local server so we can determine the os version
// Check that the OS is V5R3 or higher and set isolationLevelSwitchingSupported to true.
// Note: isolationLevelSwitchingSupport is defaulted... |
java | @SuppressWarnings("unchecked")
protected <T extends Source>T createStreamSource(
Class<T> sourceClass) throws SQLException {
StreamSource source = null;
try {
source = (sourceClass == null) ? new StreamSource()
: (StreamSource) sourceClass.newInstance();... |
python | def cross_section_components(data_x, data_y, index='index'):
r"""Obtain the tangential and normal components of a cross-section of a vector field.
Parameters
----------
data_x : `xarray.DataArray`
The input DataArray of the x-component (in terms of data projection) of the vector
field.
... |
java | static RedisNodeDescription findNodeByHostAndPort(Collection<RedisNodeDescription> nodes, String host, int port) {
for (RedisNodeDescription node : nodes) {
RedisURI nodeUri = node.getUri();
if (nodeUri.getHost().equals(host) && nodeUri.getPort() == port) {
return node;
... |
java | public int hashValue(Object object) {
int x;
// make sure the hash value is consistent across JVM invocations
if (object instanceof Boolean || object instanceof Character || object instanceof String || object instanceof Number || object instanceof Date) {
x = object.hashCode();
... |
python | def users_update_many(self, data, external_ids=None, ids=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#update-many-users"
api_path = "/api/v2/users/update_many.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
... |
python | def join(self, right, on=None, how='inner'):
"""
Merge two SFrames. Merges the current (left) SFrame with the given
(right) SFrame using a SQL-style equi-join operation by columns.
Parameters
----------
right : SFrame
The SFrame to join.
on : None | ... |
java | public T getDynamic(String className) {
for (T t : this)
if (t.getClass().getName().equals(className))
return t;
return null;
} |
python | def wheels(opts, whitelist=None, context=None):
'''
Returns the wheels modules
'''
if context is None:
context = {}
return LazyLoader(
_module_dirs(opts, 'wheel'),
opts,
tag='wheel',
whitelist=whitelist,
pack={'__context__': context},
) |
python | def get_usedby_aql(self, params):
"""
Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return:
"""
if self._usedby is None:
return None
_result = {}
params = self.merge_valued(params)
for k, v in self._use... |
java | public void addFilter(final String columnFamily, Filter filter)
{
((HBaseDataHandler) handler).addFilter(columnFamily, filter);
} |
python | def click_a_point(self, x=0, y=0, duration=100):
""" Click on a point"""
self._info("Clicking on a point (%s,%s)." % (x,y))
driver = self._current_application()
action = TouchAction(driver)
try:
action.press(x=float(x), y=float(y)).wait(float(duration)).release(... |
java | public void setBurnIn(double burnIn)
{
if(Double.isNaN(burnIn) || burnIn < 0 || burnIn >= 1)
throw new IllegalArgumentException("BurnInFraction must be in [0, 1), not " + burnIn);
this.burnIn = burnIn;
} |
java | private void syncMenu() {
if (bugInstance != null) {
BugProperty severityProperty = bugInstance.lookupProperty(BugProperty.SEVERITY);
if (severityProperty != null) {
try {
int severity = severityProperty.getValueAsInt();
if (severit... |
python | def load(file, channels=None, devices=None, get_header=False, remote=False, out_dict=False, signal_sample=False, **kwargs):
"""
-----
Brief
-----
Universal function for reading .txt, .h5 and .edf (future) files generated by OpenSignals.
-----------
Description
-----------
Each acqui... |
python | def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_... |
java | @Bean
@ConditionalOnBean(CacheManager.class)
@ConditionalOnProperty("wro4j.cacheName")
@ConditionalOnMissingBean(CacheStrategy.class)
@Order(-100)
<K, V> CacheStrategy<K, V> springCacheStrategy(CacheManager cacheManager, Wro4jProperties wro4jProperties) {
LOGGER.debug("Creating cache strategy 'SpringCacheStrateg... |
java | @JsonSetter("enterpriseContextViews")
void setEnterpriseContextViews(Collection<SystemLandscapeView> enterpriseContextViews) {
if (enterpriseContextViews != null) {
this.systemLandscapeViews = new HashSet<>(enterpriseContextViews);
}
} |
java | private void processFiles() {
String[] fileArgs = getOptionValues(INFILE_SHORT_OPT);
final List<File> files = new ArrayList<File>(fileArgs.length);
for (final String fileArg : fileArgs) {
File file = new File(fileArg);
if (!file.canRead()) {
error(INPUT_FI... |
java | protected boolean skipMojo()
{
if (skip)
{
getLog().info("Skipping protostuff mojo execution");
return true;
}
if (!forceMojoExecution && "pom".equals(this.project.getPackaging()))
{
getLog().info("Skipping protostuff mojo execut... |
python | def push(self):
'''Deliver the message.'''
message = self.build_message()
return requests.post(self.hook, json=message) |
python | def fetch(self, fmt_p=None, fmt_j=None):
"""Fetches latest data
Prepares the query URL based on self.params and executes the request
Returns
-------
response: requests.response
A response object
"""
url = self._prepare_query()
data... |
java | protected ORecordInternal<?> retrieveRecord(final ORID iRID) {
if (!isEnabled() || iRID.getClusterId() == excludedCluster)
return null;
ORecordInternal<?> record;
underlying.lock(iRID);
try {
record = underlying.remove(iRID);
if (record == null || record.isDirty()) {
... |
python | def rmdir(path):
"""Safe rmdir (non-recursive) which doesn't throw if the directory is not empty."""
try:
os.rmdir(path)
except OSError as exc:
print(str(exc)) |
python | def clean_s_name(self, s_name, root):
""" Helper function to take a long file name and strip it
back to a clean sample name. Somewhat arbitrary.
:param s_name: The sample name to clean
:param root: The directory path that this file is within
:config.prepend_dirs: boolean, whether... |
java | @Pure
@SuppressWarnings("static-method")
public Object getFirstOptionValue(String optionLabel) {
final List<Object> options = getCommandLineOption(optionLabel);
if (options == null || options.isEmpty()) {
return null;
}
return options.get(0);
} |
java | public ServiceFuture<OperationBatchStatusResponseInner> getOperationBatchStatusAsync(String userName, List<String> urls, final ServiceCallback<OperationBatchStatusResponseInner> serviceCallback) {
return ServiceFuture.fromResponse(getOperationBatchStatusWithServiceResponseAsync(userName, urls), serviceCallback)... |
java | protected Object findValue(String expr, Class<?> toType) {
if (altSyntax() && toType == String.class) {
return TextParseUtil.translateVariables('%', expr, stack);
} else {
expr = stripExpressionIfAltSyntax(expr);
return stack.findValue(expr, toType, false);
}
} |
python | def import_class(klass):
"""
Imports a class from a fully qualified name string.
:param klass: class string, e.g.
"pyqode.core.backend.workers.CodeCompletionWorker"
:return: The corresponding class
"""
path = klass.rfind(".")
class_name = klass[path + 1: len(klass)]
try:
... |
python | def remove(src, new_file=None):
"""
py:function:: piexif.remove(filename)
Remove exif from JPEG.
:param str filename: JPEG
"""
output_is_file = False
if src[0:2] == b"\xff\xd8":
src_data = src
file_type = "jpeg"
elif src[0:4] == b"RIFF" and src[8:12] == b"WEBP":
... |
java | public InputStream generateImage() {
if (closed) {
throw new ActivitiImageException("ProcessDiagramGenerator already closed");
}
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Writer out;
out = new OutputStreamWriter(stream,
... |
java | protected void initialiseComms() throws UnknownHostException
{
// Start polling for missions:
if (this.missionPoller != null)
{
this.missionPoller.stopServer();
}
this.missionPoller = new TCPInputPoller(AddressHelper.getMissionControlPortOverride(), AddressHelper... |
java | public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = WebFilter.request.get();
try {
WebFilter.request.set((HttpServletRequest) request);
chain.doFilter(request, response);
} finally {
... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUTION_TYPE__MAX:
return isSetMax();
case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUTION_TYPE__MEAN:
return isSetMean();
case BpsimPackage.TRUNCATED_NORMAL_DISTRIBUTION_TYPE__MIN:
return is... |
java | protected boolean urlPatternMatch(String pattern1, String pattern2) {
if (pattern1.equals(pattern2)) {
return true;
}
if (pattern1.equals("/*")) {
return true;
}
if (pattern1.startsWith("/") && pattern1.endsWith("/*")) {
String subPattern = pat... |
java | public static CmsFlexBucketConfiguration loadFromVfsFile(CmsObject cms, String path) throws CmsException {
if (!cms.existsResource(path)) {
return null;
}
CmsResource configRes = cms.readResource(path);
if (configRes.isFolder()) {
return null;
}
C... |
java | public void forAllIndexDescriptorColumns(String template, Properties attributes) throws XDocletException
{
String fields = _curIndexDescriptorDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);
FieldDescriptorDef fieldDef;
String name;
for (CommaListIt... |
python | def _GetLink(self):
"""Retrieves the link.
Returns:
str: link.
"""
if self._link is None:
if self._tar_info:
self._link = self._tar_info.linkname
return self._link |
java | private void mapControllerAndEntityClasses(
BeanDefinitionRegistry reg,
Map<String, Class<?>> controllerToEntityMapping,
Map<Class<?>, String> entityToRepositoryMapping,
Map<Class<?>, Set<String>> entityToControllerMappings) throws ClassNotFoundException {
// Loop thru the bean registry
//
for(String... |
python | def refresher(name, refreshers=CompletionRefresher.refreshers):
"""Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine."""
def wrapper(wrapped):
refreshers[name] = wrapped
... |
java | public <Message extends PMessage<Message, Field>, Field extends PField>
void formatTo(OutputStream out, Message message) {
IndentedPrintWriter builder = new IndentedPrintWriter(out, indent, newline);
if (message == null) {
builder.append(null);
} else {
builder.append... |
python | def replace_return_operation_by_id(cls, return_operation_id, return_operation, **kwargs):
"""Replace ReturnOperation
Replace all attributes of ReturnOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>... |
python | def read_stream (stream):
"""Python 3 compat note: we're assuming `stream` gives bytes not unicode."""
section = None
key = None
data = None
for fullline in stream:
line = fullline.split ('#', 1)[0]
m = sectionre.match (line)
if m is not None:
# New section
... |
python | def match(self, request: httputil.HTTPServerRequest) -> Optional[Dict[str, Any]]:
"""Matches current instance against the request.
:arg httputil.HTTPServerRequest request: current HTTP request
:returns: a dict of parameters to be passed to the target handler
(for example, ``handler_... |
python | def serial_udb_extra_f2_a_encode(self, sue_time, sue_status, sue_latitude, sue_longitude, sue_altitude, sue_waypoint_index, sue_rmat0, sue_rmat1, sue_rmat2, sue_rmat3, sue_rmat4, sue_rmat5, sue_rmat6, sue_rmat7, sue_rmat8, sue_cog, sue_sog, sue_cpu_load, sue_voltage_milis, sue_air_speed_3DIMU, sue_estimated_wind_0, sue... |
java | public void marshall(KinesisStreamsOutputDescription kinesisStreamsOutputDescription, ProtocolMarshaller protocolMarshaller) {
if (kinesisStreamsOutputDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarsha... |
python | def get_session(self, app_path, session_id):
''' Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
... |
java | public static ElementOption element(WebElement element, Point offset) {
return new ElementOption().withElement(element).withCoordinates(offset);
} |
python | def to_args(s):
""" parse a string into args and kwargs
the input is a blank-delimited set of tokens, which may be grouped
as strings (tick or double tick delimited) with embedded blanks.
a non-string equal (=) acts as a delimiter between key-value pairs.
the initial tokens are tre... |
java | public FingerprintSimilarity getFingerprintsSimilarity() {
HashMap<Integer, Integer> offset_Score_Table = new HashMap<>(); // offset_Score_Table<offset,count>
int numFrames;
float score = 0;
int mostSimilarFramePosition = Integer.MIN_VALUE;
// one frame may contain several point... |
java | public boolean containsThumbnail(int userPage, int page, float width, float height, RectF pageRelativeBounds) {
PagePart fakePart = new PagePart(userPage, page, null, width, height, pageRelativeBounds, true, 0);
for (PagePart part : thumbnails) {
if (part.equals(fakePart)) {
... |
python | def _check_approval_wrapper(self, grr_object, grr_function, *args, **kwargs):
"""Wraps a call to GRR functions checking for approval.
Args:
grr_object: the GRR object to create the eventual approval on.
grr_function: The GRR function requiring approval.
*args: Positional arguments that are to... |
java | public MultiPatternSearcher searcher() {
final MultiPatternAutomaton searcherAutomaton = makeAutomatonWithPrefix(".*");
final List<Automaton> indidivualAutomatons = new ArrayList<>();
for (final String pattern: this.patterns) {
final Automaton automaton = new RegExp(pattern).toAutoma... |
python | def attach(self, instance_id, device):
"""
Attach this EBS volume to an EC2 instance.
:type instance_id: str
:param instance_id: The ID of the EC2 instance to which it will
be attached.
:type device: str
:param device: The device on the insta... |
python | def get_module_path(exc_type):
""" Return the dotted module path of `exc_type`, including the class name.
e.g.::
>>> get_module_path(MethodNotFound)
>>> "nameko.exceptions.MethodNotFound"
"""
module = inspect.getmodule(exc_type)
return "{}.{}".format(module.__name__, exc_type.__na... |
python | def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If `... |
java | protected HttpRequestRetryHandler buildRequestRetryHandler(int retryCount,
boolean requestSentRetryEnabled, boolean retryUnknownHostException, boolean retryConnectException,
BackoffStrategy backoffStrategy, WaitStrategy waitStrategy,
IdempotentPredicate idempotentPredicate){
return buildRequestRetryHandler... |
python | def clean(self, timeout=60):
"""Deletes the contents of the index.
This method blocks until the index is empty, because it needs to restore
values at the end of the operation.
:param timeout: The time-out period for the operation, in seconds (the
default is 60).
:ty... |
java | public static <E> boolean any(E[] array, Predicate<E> predicate) {
return new Any<E>(predicate).test(new ArrayIterator<E>(array));
} |
java | public ImageHeuristics getImageSizes(String imgFileName) throws
IOException
{
int pos = imgFileName.lastIndexOf(".");
if (pos == -1)
{
throw new IOException("No extension for file: " + imgFileName);
}
String suffix = imgFileName.substring(pos + 1);
File tempFile = null;
if ("s... |
python | def closest_waypoint(self, latlon):
'''find closest waypoint to a position'''
(lat, lon) = latlon
best_distance = -1
closest = -1
for i in range(self.module('wp').wploader.count()):
w = self.module('wp').wploader.wp(i)
distance = mp_util.gps_distance(lat, ... |
java | private synchronized boolean needsToThrottle(String signature)
{
AtomicInteger sigCount;
// Are we already throttling this signature?
if (throttledIncidents.containsKey(signature))
{
// Lazily check if it's time to unthrottle
if (throttledIncidents.get(signature).plusHours(THROTTLE_DURATI... |
python | def _make_load_partial(self):
"""
Return a function that loads a partial by name.
"""
if self.partials is None:
return self._make_load_template()
# Otherwise, create a function from the custom partial loader.
partials = self.partials
def load_partia... |
java | public ModelNode createNewVaultRequest(String className) {
String dmrTemplate = "" //
+ "{" //
+ "\"code\" => \"%s\""
+ "}";
String dmr = String.format(dmrTemplate, className);
Address addr = Address.root().add(CORE_SERVICE, VAULT);
final ModelNode r... |
java | public void marshall(ColumnMetadata columnMetadata, ProtocolMarshaller protocolMarshaller) {
if (columnMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(columnMetadata.getArrayBaseColumnType... |
python | def attach_to_fbo(self):
"""Attach the texture to a bound FBO object, for rendering to texture."""
gl.glFramebufferTexture2DEXT(gl.GL_FRAMEBUFFER_EXT, self.attachment_point, self.target0, self.id, 0) |
java | public void setSrcPath(String in) throws IOException {
srcPath = new Path(in);
srcPath = srcPath.makeQualified(srcPath.getFileSystem(conf));
} |
python | def create_api_object_type(self):
"""Get an instance of Api Vip Requests services facade."""
return ApiObjectType(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.