language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def on_for_seconds(self, steering, speed, seconds, brake=True, block=True):
"""
Rotate the motors according to the provided ``steering`` for ``seconds``.
"""
(left_speed, right_speed) = self.get_speed_steering(steering, speed)
MoveTank.on_for_seconds(self, SpeedNativeUnits(left_s... |
python | def parse_line(line: str, char_index=0) -> Tuple[ListingType, str]:
"""Parse FTP directory listing into (type, filename)."""
entry_name = str.rpartition(line, ' ')[-1]
entry_type = LISTING_FLAG_MAP.get(line[char_index], ListingType.other)
return entry_type, entry_name |
python | def status_raw(name=None, user=None, conf_file=None, bin_env=None):
'''
Display the raw output of status
user
user to run supervisorctl as
conf_file
path to supervisord config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
... |
python | def restore_gc_state():
"""
Restore the garbage collector state on leaving the with block.
"""
old_isenabled = gc.isenabled()
old_flags = gc.get_debug()
try:
yield
finally:
gc.set_debug(old_flags)
(gc.enable if old_isenabled else gc.disable)() |
java | private String getStringValue(Object o) {
if (o instanceof String) {
return (String) o;
} else if (o instanceof XmlNodeArray) {
XmlNodeArray array = (XmlNodeArray) o;
switch (array.size()) {
case 0:
return null;
case... |
python | def compute_schema(schema_cls, default_kwargs, qs, include):
"""Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field t... |
java | public static void runWith(
String[] args, Function<BenchmarkSettings, SmCodecBenchmarkState> benchmarkStateFactory) {
BenchmarkSettings settings =
BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build();
SmCodecBenchmarkState benchmarkState = benchmarkStateFactory.apply(settings... |
java | private static void simpleClassTypeSignature(Result sb, TypeMirror type) throws IOException
{
switch (type.getKind())
{
case DECLARED:
DeclaredType dt = (DeclaredType) type;
TypeElement te = (TypeElement) dt.asElement();
nestedSimpleName(sb... |
python | def tags_to_versions(tags, config=None):
"""
take tags that might be prefixed with a keyword and return only the version part
:param tags: an iterable of tags
:param config: optional configuration object
"""
result = []
for tag in tags:
tag = tag_to_version(tag, config=config)
... |
python | def located_error(
original_error: Union[Exception, GraphQLError],
nodes: Sequence["Node"],
path: Sequence[Union[str, int]],
) -> GraphQLError:
"""Located GraphQL Error
Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL
operation, produce a new GraphQLError aware ... |
java | public AC start(String taskName, Object... args) {
final ProfilingTimerNode parent = current.get();
current.set(findOrCreateNode(String.format(taskName, args), parent));
return new AC() {
@Override public void close() {
// return to the parent that we had when this AC was created
current.set(parent);
... |
python | def get_url_for_id(client_site_url, apikey, resource_id):
"""Return the URL for the given resource ID.
Contacts the client site's API to get the URL for the ID and returns it.
:raises CouldNotGetURLError: if getting the URL fails for any reason
"""
# TODO: Handle invalid responses from the client... |
java | private Date addDays(final Date date, final int days) {
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
} |
java | public void execute(Task task) {
LOG.info(String.format("Executing task %s", task.getTaskId()));
this.taskExecutor.execute(new TrackingTask(task));
} |
java | synchronized void resetAccounting(long newLastTime) {
long interval = newLastTime - lastTime.getAndSet(newLastTime);
if (interval == 0) {
// nothing to do
return;
}
if (logger.isDebugEnabled() && interval > checkInterval() << 1) {
logger.debug("Acct sc... |
java | @Override
public Request<DescribeVpcClassicLinkRequest> getDryRunRequest() {
Request<DescribeVpcClassicLinkRequest> request = new DescribeVpcClassicLinkRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
python | def phase2radians(phasedata, v0):
""" Convert phase in seconds to phase in radians
Parameters
----------
phasedata: np.array
Data array of phase in seconds
v0: float
Nominal oscillator frequency in Hz
Returns
-------
fi:
phase data in radians
"""
fi = [2... |
python | def short_repr(obj, noneAsNA=False):
'''Return a short representation of obj for clarity.'''
if obj is None:
return 'unspecified' if noneAsNA else 'None'
elif isinstance(obj, str) and len(obj) > 80:
return '{}...{}'.format(obj[:60].replace('\n', '\\n'),
obj[-2... |
python | def __set_bp(self, aThread):
"""
Sets this breakpoint in the debug registers.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
if self.__slot is None:
aThread.suspend()
try:
ctx = aThread.get_context(win32.CONTEXT_DEBUG... |
java | public void setEnabled(boolean enabled) {
if (enabled && engine == null) {
return;
}
if (this.enabled != enabled) {
this.enabled = enabled;
this.changed = true;
}
} |
java | public static CurrencyUnit getCurrency(Locale locale, String... providers) {
return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(
() -> new MonetaryException("No MonetaryCurrenciesSingletonSpi loaded, check your system setup."))
.getCurrency(locale, provid... |
java | public PagedList<ExperimentInner> listByWorkspaceNext(final String nextPageLink) {
ServiceResponse<Page<ExperimentInner>> response = listByWorkspaceNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<ExperimentInner>(response.body()) {
@Override
public P... |
python | def click_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" This method clicks link text on a page """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeo... |
python | def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
... |
python | def _read_services(self):
"""
Read the control XML file and populate self.services with a list of
services in the form of Service class instances.
"""
# The double slash in the XPath is deliberate, as services can be
# listed in two places (Section 2.3 of uPNP device arch... |
python | def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True,
encoding=None, tupleize_cols=None,
infer_datetime_format=False):
"""
Read CSV file.
.. deprecated:: 0.21.0
Use :func:`read_csv` instead.
It is preferable to use the m... |
python | def unpause(name):
'''
Unpauses a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well as the new state
- ``result`` - A boolean noting... |
python | def _PrintEventLabelsCounter(
self, event_labels_counter, session_identifier=None):
"""Prints the event labels counter.
Args:
event_labels_counter (collections.Counter): number of event tags per
label.
session_identifier (Optional[str]): session identifier.
"""
if not event_... |
java | @Override
public void quit(String reason) {
if (!connected) {
throw new NotConnectedException();
}
Message quit = new Message(MessageType.QUIT, reason);
ChannelFuture future = connection.send(quit);
/* Wait for message to be sent and then close the underlying co... |
java | public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException {
if (!(actionType.equals(DOCUMENT_CLOSE) ||
actionType.equals(WILL_SAVE) ||
actionType.equals(DID_SAVE) ||
actionType.equals(WILL_PRINT) ||
actionType.equals(DID_PRINT))) {
thro... |
java | public TableRef off(StorageEvent eventType, OnItemSnapshot onItemSnapshot) {
Event ev = new Event(eventType, this.name, null, null, false, true, false, onItemSnapshot);
context.removeEvent(ev);
return this;
} |
java | private void closeResultSet
(CodeBuilder b, LocalVariable rsVar, Label tryAfterRs)
{
Label contLabel = b.createLabel();
Label endFinallyLabel = b.createLabel().setLocation();
b.loadLocal(rsVar);
b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null... |
python | def save_to_file(self, filename_prefix):
"""Save the vocabulary to a file."""
# Wrap in single quotes to make it easier to see the full subword when
# it has spaces and make it easier to search with ctrl+f.
filename = self._filename(filename_prefix)
lines = ["'%s'" % s for s in self._subwords]
s... |
java | public static base_response update(nitro_service client, snmpgroup resource) throws Exception {
snmpgroup updateresource = new snmpgroup();
updateresource.name = resource.name;
updateresource.securitylevel = resource.securitylevel;
updateresource.readviewname = resource.readviewname;
return updateresource.upd... |
java | public static boolean deleteProperty(Scriptable obj, String name)
{
Scriptable base = getBase(obj, name);
if (base == null)
return true;
base.delete(name);
return !base.has(name, obj);
} |
java | public static Predicate<Map.Entry<Long, Boolean>> amongDeadHsids(final Set<Long> hsids) {
return new Predicate<Map.Entry<Long,Boolean>>() {
@Override
public boolean apply(Entry<Long, Boolean> e) {
return hsids.contains(e.getKey()) && e.getValue();
}
};... |
python | def get_files(input_file):
"""
Initializes an index of files to generate, returns the base
directory and index.
"""
file_index = {}
base_dir = None
if os.path.isfile(input_file):
file_index[input_file] = None
base_dir = os.path.dirname(input_file)
elif os.path.isdir(input_file):
base_dir = ... |
java | private void error(PageException pe) {
if (error == null) throw new PageRuntimeException(pe);
try {
pc = ThreadLocalPageContext.get(pc);
error.call(pc, new Object[] { pe.getCatchBlock(pc.getConfig()) }, false);
}
catch (PageException e) {}
} |
java | public void project(double x, double y, double z, double[] out) {
glu.gluProject(x, y, z, modelview, 0, projection, 0, viewp, 0, out, 0);
} |
java | public void writeFile(String resourceName, String exportpoint, byte[] content) {
writeResource(resourceName, exportpoint, content);
} |
java | public Observable<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>> stopResizeWithServiceResponseAsync(String poolId, PoolStopResizeOptions poolStopResizeOptions) {
if (this.client.batchUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and canno... |
python | def _convert_strls(self, data):
"""Convert columns to StrLs if either very large or in the
convert_strl variable"""
convert_cols = [
col for i, col in enumerate(data)
if self.typlist[i] == 32768 or col in self._convert_strl]
if convert_cols:
ssw = Sta... |
java | @Override
@SuppressWarnings("unchecked")
@LogarithmicTime(amortized = true)
public AddressableHeap.Handle<K, V> deleteMin() {
if (size == 0) {
throw new NoSuchElementException();
}
Node<K, V> min;
if (decreasePoolMinPos >= decreasePoolSize) {
// decre... |
java | public List<V> getAll(Object key) {
List<V> res = map.get(key);
if (res == null) {
res = Collections.emptyList();
}
return res;
} |
python | def chunks(data, size):
"""
Generator that splits the given data into chunks
"""
for i in range(0, len(data), size):
yield data[i:i + size] |
java | public static <T> T use(Class categoryClass, Closure<T> closure) {
return THREAD_INFO.getInfo().use(categoryClass, closure);
} |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Instance, OperationMetadata> failoverInstanceAsync(
InstanceName name, FailoverInstanceRequest.DataProtectionMode dataProtectionMode) {
FailoverInstanceRequest request =
... |
java | public static void setFileData(final File file, final byte[] fileData, final String contentType) throws FrameworkException, IOException {
FileHelper.setFileData(file, fileData, contentType, true);
} |
java | public ZoneAwareLoadBalancer<T> buildDynamicServerListLoadBalancerWithUpdater() {
if (serverListImpl == null) {
serverListImpl = createServerListFromConfig(config, factory);
}
if (rule == null) {
rule = createRuleFromConfig(config, factory);
}
if (serverLi... |
python | def validator(node, rrn):
'''
Colander validator that checks whether a given value is a valid
Belgian national ID number .
:raises colander.Invalid: If the value is no valid Belgian national ID number.
'''
def _valid(_rrn):
x = 97 - (int(_rrn[:-2]) - (int(_rr... |
python | def logout(self):
"""Explicit Abode logout."""
if self._token:
header_data = {
'ABODE-API-KEY': self._token
}
self._session = requests.session()
self._token = None
self._panel = None
self._user = None
se... |
python | def create_launch_configuration(self, launch_config):
"""
Creates a new Launch Configuration.
:type launch_config: :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration`
:param launch_config: LaunchConfiguration object.
"""
params = {'ImageId': launch_config.image_... |
python | def lset(self, name, index, value):
"""
Set the value in the list at index *idx*
:param name: str the name of the redis key
:param value:
:param index:
:return: Future()
"""
with self.pipe as pipe:
value = self.valueparse.encode(value)
... |
java | private CmsContainerElementBean getModelReplacementElement(
CmsContainerElementBean element,
CmsContainerElementBean baseElement,
boolean allowCopyModel) {
boolean resetSettings = false;
if (!baseElement.isCopyModel() && !baseElement.getFormatterId().equals(element.getFormatterI... |
java | public Vector2i sub(int x, int y, Vector2i dest) {
dest.x = this.x - x;
dest.y = this.y - y;
return dest;
} |
python | def clean_html(self, html):
"""Apply ``Cleaner`` to HTML string or document and return a cleaned string or document."""
result_type = type(html)
if isinstance(html, six.string_types):
doc = html_fromstring(html)
else:
doc = copy.deepcopy(html)
self(doc)
... |
java | void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator,
Relation relation, Object relObject, Map<String, Object> relationsMap)
{
// For M-M relationship of Collection type, relationship entities are
// always fetched from Join Table.
... |
java | public final void entry(Class sourceClass, String methodName)
{
entry(null, sourceClass, methodName, (Object[]) null);
} |
java | public void reconnect() throws IOException, SlackApiException, URISyntaxException, DeploymentException {
// Call rtm.connect again to refresh wss URL
RTMConnectResponse response = slack.methods().rtmConnect(RTMConnectRequest.builder().token(botApiToken).build());
if (response.isOk()) {
... |
python | def encode(self, reference_boxes, proposals):
"""
Encode a set of proposals with respect to some
reference boxes
Arguments:
reference_boxes (Tensor): reference boxes
proposals (Tensor): boxes to be encoded
"""
TO_REMOVE = 1 # TODO remove
... |
java | public static <T extends Enum<T>> T enuum(Class<T> enumClass, String value) {
List<Enum> values = (List<Enum>) EnumUtils.valueList(enumClass);
for (Enum enumValue : values) {
if (enumValue.name().equalsIgnoreCase(value)) {
return (T) enumValue;
}
}
return InvalidValues.createInvalidEnum(enumCla... |
java | private void readNotationDeclaration() throws IOException, KriptonRuntimeException {
read(START_NOTATION);
skip();
readName();
if (!readExternalId(false, false)) {
throw new KriptonRuntimeException("Expected external ID or public ID for notation", true, this.getLineNumber(), this.getColumnNumber(), getPositi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.