language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static boolean hasUsbHostFeature(Context context) {
return hasUsbHostFeature(context.getPackageManager());
} |
python | def deposit_code(self, card_id, codes):
"""
导入code
"""
card_data = {
'card_id': card_id,
'code': codes
}
return self._post(
'card/code/deposit',
data=card_data
) |
java | private void readRelationships()
{
for (MapRow row : getTable("CONTAB"))
{
Task task1 = m_projectFile.getTaskByUniqueID(row.getInteger("TASK_ID_1"));
Task task2 = m_projectFile.getTaskByUniqueID(row.getInteger("TASK_ID_2"));
if (task1 != null && task2 != null)
{
... |
java | public void inherit(DocFinder.Input input, DocFinder.Output output) {
if (input.tagId == null) {
input.isTypeVariableParamTag = ((ParamTag) input.tag).isTypeParameter();
Object[] parameters = input.isTypeVariableParamTag ?
(Object[]) ((MethodDoc) input.tag.holder()).typeP... |
java | private Pair<Gradient, INDArray> getGradientsAndDelta(INDArray preOut, LayerWorkspaceMgr workspaceMgr) {
// delta calculation
ILossFunction lossFunction = layerConf().getLossFn();
INDArray delta = lossFunction.computeGradient(getLabels2d(), preOut, layerConf().getActivationFn(), maskArray);
... |
java | public String[] black_box(final Connection connection, final int length) throws DevFailed {
checkIfTango(connection, "black_box");
build_connection(connection);
String[] result = new String[0];
try {
result = connection.device.black_box(length);
} catch (final DevFailed e) {
final String reason ... |
python | def domagicmag(file, Recs):
"""
converts a magic record back into the SIO mag format
"""
for rec in Recs:
type = ".0"
meths = []
tmp = rec["magic_method_codes"].split(':')
for meth in tmp:
meths.append(meth.strip())
if 'LT-T-I' in meths:
ty... |
java | public HostAddress searchByStartName(Protocol secondaryProtocol, List<HostAddress> loopAddress) {
if (!isSecondaryHostFail()) {
int checkWriterAttempts = 3;
HostAddress currentWriter = null;
do {
try {
currentWriter = searchForMasterHostAddress(secondaryProtocol, loopAddress);
... |
python | async def get_stats(self, battletag: str, regions=(EUROPE, KOREA, AMERICAS, CHINA, JAPAN, ANY),
platform=None, _session=None, handle_ratelimit=None, max_tries=None, request_timeout=None):
"""Returns the stats for the profiles on the specified regions and platform. The format for regions ... |
java | public void insert(final DevEncoded argIn) {
attributeValue_5.data_format = AttrDataFormat.FMT_UNKNOWN;
attributeValue_5.err_list = new DevError[0]; // ?? Only for DevEncoded, else
// (NullPointerException)
attributeValue_5.w_dim.dim_x = 1;
attributeValue_5.w_dim.dim_y = 0;
attributeValue_5.value.encoded_at... |
python | def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options):
"""Returns True if user agrees, False otherwise"""
return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message) |
java | protected void addPackageList(Content contentTree) {
Content caption = getTableCaption(configuration.getContent(
"doclet.ClassUse_Packages.that.use.0",
getPackageLink(packageElement, utils.getPackageName(packageElement))));
Content table = (configuration.isOutputHtml5())
... |
java | public static Date getDate(JSONObject json, String key) {
return getDate(json, key, null);
} |
java | public Map<String, Object> fromJson(Reader reader) throws IOException {
if (reader == null) {
throw new IllegalArgumentException("reader == null");
}
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(isLenient);
try {
return readerToMap(jsonReader);
} finally {
... |
java | private static IInfoPanel getInfoPanel(ElementBase element, boolean activeOnly) {
if (element instanceof ElementPlugin) {
ElementPlugin plugin = (ElementPlugin) element;
if ((!activeOnly || plugin.isActivated()) && (plugin.getDefinition().getId().equals("infoPanelPlugin"))) ... |
java | public static <N extends Number> DoubleStream
buildDoubleStream(Collection<N> numberCollection) {
return numberCollection.stream().mapToDouble(Number::doubleValue);
} |
java | private Object getTargetBean(final Invocation invocation)
{
final InvocationContext invocationContext = invocation.getInvocationContext();
return invocationContext.getTargetBean();
} |
java | public void unregister(FileSubscriber fileSubscriber) {
for (IdentificationSet<FileSubscriber> subList : fileSubscribers.values()) {
subList.remove(fileSubscriber);
}
defaultFileSubscribers.remove(fileSubscriber);
} |
java | public java.util.List<String> getPolicyNames() {
if (policyNames == null) {
policyNames = new com.ibm.cloud.objectstorage.internal.SdkInternalList<String>();
}
return policyNames;
} |
java | public boolean load(ByteArray byteArray)
{
if (byteArray == null) return false;
model_header = byteArray.nextString();
root = byteArray.nextString();
use_distance = byteArray.nextInt() == 1;
use_valency = byteArray.nextInt() == 1;
use_cluster = byteArray.nextInt() ==... |
java | public List<Acl> listDefaultAcls() {
// [START listDefaultAcls]
List<Acl> acls = bucket.listDefaultAcls();
for (Acl acl : acls) {
// do something with ACL entry
}
// [END listDefaultAcls]
return acls;
} |
java | public void marshall(DeleteEndpointConfigRequest deleteEndpointConfigRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteEndpointConfigRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshal... |
python | def add_subparser(subparsers):
"""Add command line option for exporting version information.
"""
parser = subparsers.add_parser("version",
help="Export versions of used software to stdout or a file ")
parser.add_argument("--workdir", help="Directory export programs to ... |
python | def _findSingleMemberGroups(classDictionaries):
"""
Find all classes that have only one member.
"""
toRemove = {}
for classDictionaryGroup in classDictionaries:
for classDictionary in classDictionaryGroup:
for name, members in list(classDictionary.items()):
if len... |
java | @XmlElementDecl(namespace = "https://adwords.google.com/api/adwords/o/v201809", name = "ResponseHeader")
public JAXBElement<SoapResponseHeader> createResponseHeader(SoapResponseHeader value) {
return new JAXBElement<SoapResponseHeader>(_ResponseHeader_QNAME, SoapResponseHeader.class, null, value);
} |
python | def oauth_client_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/oauth_clients#create-client"
api_path = "/api/v2/oauth/clients.json"
return self.call(api_path, method="POST", data=data, **kwargs) |
java | public void visit(final WebAppServlet webAppServlet) {
NullArgumentException.validateNotNull(webAppServlet, "Web app servlet");
final String[] urlPatterns = webAppServlet.getAliases();
if (urlPatterns == null || urlPatterns.length == 0) {
LOG.warn("Servlet [" + webAppServlet
+ "] does not have any ma... |
python | def etag(self, etag):
"""
Sets the etag of this BulkResponse.
etag
:param etag: The etag of this BulkResponse.
:type: str
"""
if etag is None:
raise ValueError("Invalid value for `etag`, must not be `None`")
if etag is not None and not re.sear... |
java | @Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
if (annotationClass == null) {
throw new NullPointerException("Cannot check the presence of an annotation with a 'null' annotationClass.");
}
return annotations.containsKey(annotationClas... |
python | def fetch_stackexchange(
dataset,
test_set_fraction=0.2,
min_training_interactions=1,
data_home=None,
indicator_features=True,
tag_features=False,
download_if_missing=True,
):
"""
Fetch a dataset from the `StackExchange network <http://stackexchange.com/>`_.
The datasets contain... |
python | def acl_middleware(callback):
"""Returns a aiohttp_auth.acl middleware factory for use by the aiohttp
application object.
Args:
callback: This is a callable which takes a user_id (as returned from
the auth.get_auth function), and expects a sequence of permitted ACL
groups to... |
python | def search(self):
"redirect to bookmark search"
form = forms.HomeForm()
bbm_filter = bs_filters.BookmarkBukuFilter(
all_keywords=False, deep=form.deep.data, regex=form.regex.data)
op_text = bbm_filter.operation()
values_combi = sorted(itertools.product([True, False], ... |
java | void swap(int element1, int element2) {
int ar1[] = m_buffer[element1 >> m_blockPower];
int ar2[] = m_buffer[element2 >> m_blockPower];
int ind1 = element1 & m_blockMask;
int ind2 = element2 & m_blockMask;
for (int i = 0; i < m_stride; i++) {
int tmp = ar1[ind1 + i];
ar1[ind1 + i] = ar2[ind2 + i];
ar... |
java | public static boolean isPrimitiveDesc(String desc) {
if (desc.length() > 1) return false;
char c = desc.charAt(0);
return c == 'Z'
|| c == 'B'
|| c == 'C'
|| c == 'D'
|| c == 'F'
|| c == 'I'
|| c == 'J'
... |
python | def _edges2conns(G, edge_data=False):
"""Create a mapping from graph edges to agent connections to be created.
:param G:
NetworkX's Graph or DiGraph which has :attr:`addr` attribute for each
node.
:param bool edge_data:
If ``True``, stores also edge data to the returned dictionary.... |
java | public static int[] calculateDimension(int sourceWidth, int sourceHeight, int boxWidth, int boxHeight) {
int[] result = new int[2];
if ((sourceWidth <= boxWidth) && (sourceHeight <= boxHeight)) {
result[0] = sourceWidth;
result[1] = sourceHeight;
} else {
flo... |
python | def geocode(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
country=None,
country_bias=None,
):
"""
Return a location point by address.
:param str query: The address or query you wish to geocode.
:par... |
python | def _reprJSON(self):
"""Returns a JSON serializable represenation of a ``Smi`` class
instance. Use :func:`maspy.core.Sai._fromJSON()` to generate a new
``Smi`` instance from the return value.
:returns: a JSON serializable python object
"""
return {'__Smi__': (self.id, se... |
python | def get_pkg_paths(pkg_name, out_dir):
"""Recursively get all source and stub paths for a package."""
paths = []
try:
pkg = import_module(pkg_name)
if not hasattr(pkg, "__path__"):
return get_mod_paths(pkg_name, out_dir)
for mod_info in walk_packages(pkg.__path__, pkg.__na... |
python | def fromfile(file, dtype, count, *args, **kwargs):
"""Wrapper around np.fromfile to support any file-like object"""
try:
return np.fromfile(file, dtype=dtype, count=count, *args, **kwargs)
except (TypeError, IOError, UnsupportedOperation):
return np.frombuffer(
file.read(count *... |
java | protected void initializeUberspector(String classname)
{
// Avoids direct recursive calls
if (!StringUtils.isEmpty(classname) && !classname.equals(this.getClass().getCanonicalName())) {
Uberspect u = instantiateUberspector(classname);
if (u == null) {
return;
... |
python | async def on_message(message):
"""The on_message event handler for this module
Args:
message (discord.Message): Input message
"""
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.ge... |
python | def trial_ls(args):
'''List trial'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not running...')
return
running, r... |
java | public static base_responses unset(nitro_service client, route6 resources[], String[] args) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
route6 unsetresources[] = new route6[resources.length];
for (int i=0;i<resources.length;i++){
unsetresources[i] = n... |
java | @Override
public int execute(Connection conn, String sql, Object... bindValues) {
long timestampStart = System.currentTimeMillis();
try {
JdbcTemplate jdbcTemplate = jdbcTemplate(conn);
return bindValues != null && bindValues.length > 0
? jdbcTemplate.upda... |
python | def update():
'''
When we are asked to update (regular interval) lets reap the cache
'''
try:
salt.fileserver.reap_fileserver_cache_dir(
os.path.join(__opts__['cachedir'], 'minionfs/hash'),
find_file)
except os.error:
# Hash file won't exist if no files have y... |
python | def do_with_python(python, cmdline, runas=None):
'''
Execute a python command with pyenv's shims using a specific python version.
CLI Example:
.. code-block:: bash
salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler'
salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' deplo... |
java | public void setValue(Number number) {
String txt = null;
if (number != null) {
txt = this.format.format(number);
}
setText(txt);
} |
python | def load_module_from_definition(
definition: dict, parent: Location) -> \
Union[ModuleGeometry, ThermocyclerGeometry]:
"""
Return a :py:class:`ModuleGeometry` object from a specified definition
:param definition: A dict representing all required data for a module's
... |
python | def _add_ssl_info(self):
"""Add SSL cipher info."""
if self.scheme == u'https':
sock = self._get_ssl_sock()
if hasattr(sock, 'cipher'):
self.ssl_cert = sock.getpeercert()
else:
# using pyopenssl
cert = sock.connection.ge... |
python | def download(self, filename, timeout=3600, action=None, query=None,
fields_convert_map=None, type=None, domain=None,
template_filename='', sheet_name='', **kwargs):
"""
Default domain option is PARA/DOMAIN
:param template_filename: Excel template filename, ... |
python | def run(self):
"""
Plays the audio. This method plays the audio, and shouldn't be called
explicitly, let the constructor do so.
"""
# From now on, it's multi-thread. Let the force be with them.
st = self.stream._stream
for chunk in chunks(self.audio,
size=self.chunk_... |
python | def get_unresolved_variables(f):
"""
Gets unresolved vars from file
"""
reporter = RReporter()
checkPath(f, reporter=reporter)
return dict(reporter.messages) |
python | def cmd(send, msg, args):
"""Find a path between two wikipedia articles.
Syntax: {command} [article] [article]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('first', nargs='?')
parser.add_argument('second', nargs='?')
try:
cmdargs = parser.parse_args(msg)
... |
java | void connect(boolean reconnectOnConnect) throws InterruptedException, IOException {
if (options.getServers().size() == 0) {
throw new IllegalArgumentException("No servers provided in options");
}
for (String serverURI : getServers()) {
if (isClosed()) {
... |
python | def line(surf, start, end, color=BLACK, width=1, style=FLAT):
"""Draws an antialiased line on the surface."""
width = round(width, 1)
if width == 1:
# return pygame.draw.aaline(surf, color, start, end)
return gfxdraw.line(surf, *start, *end, color)
start = V2(*start)
end = V2(*end)... |
python | def _get_stack_frame(stacklevel):
"""
utility functions to get a stackframe, skipping internal frames.
"""
stacklevel = stacklevel + 1
if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
# If frame is too small to care or if the warning originated in
# internal code, then do ... |
python | def cached(self, key_fn=_key_fn, timeout=None, metrics=False):
"""
Decorator that will transparently cache calls to the
wrapped function. By default, the cache key will be made
up of the arguments passed in (like memoize), but you can
override this by specifying a custom ``key_fn... |
java | @Override
public long[] getChannelIDs() {
long[] x = new long[this.cicMap.size()];
Iterator<Long> it = this.cicMap.keySet().iterator();
int index = 0;
while (it.hasNext())
x[index++] = it.next();
return x;
} |
python | def init_sentry(self,):
""" Initializes sentry.io error logging for this session """
if not self.use_sentry:
return
sentry_config = self.keychain.get_service("sentry")
tags = {
"repo": self.repo_name,
"branch": self.repo_branch,
"commit":... |
java | public static <E> Collection<E> constrainedCollection(
Collection<E> collection, Constraint<? super E> constraint) {
return new ConstrainedCollection<E>(collection, constraint);
} |
python | def get_rules_from_disk(self):
''' Recursively traverse the yara/rules directory for rules '''
# Try to find the yara rules directory relative to the worker
my_dir = os.path.dirname(os.path.realpath(__file__))
yara_rule_path = os.path.join(my_dir, 'yara/rules')
if not os.path.ex... |
java | private void processChildren( List<RemovrSpec> children, Object subInput ) {
if (subInput != null ) {
if( subInput instanceof List ) {
List<Object> subList = (List<Object>) subInput;
Set<Integer> indiciesToRemove = new HashSet<>();
// build a list ... |
java | protected boolean hasRole(CmsRole role, List<CmsGroup> roles) {
// iterates the role groups the user is in
for (CmsGroup group : roles) {
String groupName = group.getName();
// iterate the role hierarchy
for (String distictGroupName : role.getDistinctGroupNames()) {
... |
python | def proxy(self, signal_source, *signal_names, weak_ref=False):
""" :meth:`.WSignalProxyProto.proxy` implementation
"""
callback = self.__callback if weak_ref is False else self.__weak_ref_callback
for signal_name in signal_names:
signal_source.callback(signal_name, callback) |
python | def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0):
"""Create a |ASN.1| object initialized from a string.
Parameters
----------
value: :class:`str` (Py2) or :class:`bytes` (Py3)
Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
... |
java | public List<ModelServiceInstance> getUPModelInstances(String serviceName){
List<ModelServiceInstance> list = new ArrayList<ModelServiceInstance>();
for(ModelServiceInstance instance : getModelInstances(serviceName)){
if(instance.getStatus().equals(OperationalStatus.UP)) {
lis... |
java | @Override
public boolean handleChild(DDParser parser, String localName) throws ParseException {
if (super.handleChild(parser, localName)) {
return true;
}
if ("webservice-description".equals(localName)) {
WebserviceDescriptionType wsdes = new WebserviceDescriptionTyp... |
python | def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr |
java | public ServiceFuture<StorageAccountManagementPoliciesInner> getManagementPoliciesAsync(String resourceGroupName, String accountName, final ServiceCallback<StorageAccountManagementPoliciesInner> serviceCallback) {
return ServiceFuture.fromResponse(getManagementPoliciesWithServiceResponseAsync(resourceGroupName, ... |
java | public OneLoginResponse<Group> getGroupsBatch(HashMap<String, String> queryParameters, int batchSize, String afterCursor)
throws OAuthSystemException, OAuthProblemException, URISyntaxException {
ExtractionContext context = extractResourceBatch(queryParameters, batchSize, afterCursor, Constants.GET_GROUPS_URL);
L... |
java | public Article get(int id) {
long time = System.currentTimeMillis();
// Look for an article with this id in the Article HashMap
for(List<Article> articleList : articleMap.values()) {
for(Article article : articleList) {
if(article.getId() == id) {
log("get(" + id + ") took " + (System.currentTimeMill... |
java | Option.InvalidValueException newInvalidValueException(String key, Object... args) {
return new Option.InvalidValueException(getLog().localize(PrefixKind.JAVAC, key, args));
} |
python | def subcommand(self, description='', arguments={}):
'''
Decorator for quickly adding subcommands to the omnic CLI
'''
def decorator(func):
self.register_subparser(
func,
func.__name__.replace('_', '-'),
description=description,
... |
python | def neverCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name
"""
Checking the inspector is never called with partial args/kwargs
Args: SinonSpy, args/kwargs
"""
cls.__is_spy(spy)
if not (spy.neverCalledWith(*args, **kwargs)):
raise cls.failExc... |
python | async def get_eventhub_info_async(self):
"""
Get details on the specified EventHub async.
:rtype: dict
"""
alt_creds = {
"username": self._auth_config.get("iot_username"),
"password":self._auth_config.get("iot_password")}
try:
mgmt_aut... |
java | public Reliability getReliability()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getReliability");
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getReliability", _targetStreamReliability);
return _targetStreamReliability... |
python | def rollback(self):
"""Revert the previous modification to the refpkg.
"""
# This is slightly complicated because of Python's freakish
# assignment semantics and because we don't store multiple
# copies of the log.
if self.contents['rollback'] is None:
raise V... |
python | def thumbnail(self, path, height, width, quality=100, **kwargs):
"""获取文件缩略图
:param path: 远程文件路径
:param height: 缩略图高
:param width: 缩略图宽
:param quality: 缩略图质量,默认100
:return: requests.Response
.. note::
如果返回 HTTP 404 说明该文件不存在缩略图形式
"""
... |
java | public static @Nonnull <T> ExtensionList<T> lookup(Class<T> type) {
Jenkins j = Jenkins.getInstanceOrNull();
return j == null ? create((Jenkins) null, type) : j.getExtensionList(type);
} |
java | public static Operation createAddDeploymentOperation(final Deployment deployment) {
Assert.checkNotNullParam("deployment", deployment);
final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);
addDeploymentOperationStep(builder, deployment);
return builder.build(... |
java | public final void setUtc(final boolean utc) {
for (final Period period : this) {
period.setUtc(utc);
}
this.timezone = null;
this.utc = utc;
} |
java | public void ensureNumBuffersReturned(final int minRequiredAvailable) {
if (minRequiredAvailable > this.availableMemory.size() + this.buildSpillRetBufferNumbers) {
throw new IllegalArgumentException("More buffers requested available than totally available.");
}
try {
while (this.availableMemory.size() < min... |
java | public static synchronized ModbusSlave getSlave(AbstractModbusListener listener) {
for (ModbusSlave slave : slaves.values()) {
if (slave.getListener().equals(listener)) {
return slave;
}
}
return null;
} |
java | public static <T> Iterator<T> iterator(Single<T> pub) {
return pub.toFlowable().blockingIterable().iterator();
} |
python | def from_dict(d: Dict[str, Any]) -> 'CoverageInstructions':
"""
Loads a set of coverage instructions from a given dictionary.
Raises:
BadCoverageInstructions: if the given coverage instructions are
illegal.
"""
name_type = d['type']
cls = _NAM... |
python | def attribute(self, value):
"""
Setter for **self.__attribute** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"a... |
java | protected void parse(Node node) {
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
String nodeName = child.getNodeName();
if ("Name".equalsIgnoreCase(nodeName)) {
name = getValueRecursive(child);
} else if ("Title".equals... |
java | @Override
public String addingBundle(Bundle bundle, BundleEvent event) {
//we are invoked on addingBundle, whenever a bundle enters the STOPPING state.
//we use this notification to remove any redirecting urls for the bundle.
NotABundleResourceURLConnection.forgetBundle(bundle);
retu... |
java | @SuppressWarnings("unchecked")
public EList<IfcObjectDefinition> getRelatedObjects() {
return (EList<IfcObjectDefinition>) eGet(Ifc2x3tc1Package.Literals.IFC_REL_DECOMPOSES__RELATED_OBJECTS, true);
} |
java | protected Transformer _newTransformer()
{
Transformer transformer = null;
if (_stylesheet == null) {
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (Exception ex) {
throw new XmlException( ex );
}
... |
java | protected void publishDeletedFile(
CmsDbContext dbc,
CmsProject onlineProject,
CmsResource offlineResource,
CmsUUID publishHistoryId,
int publishTag)
throws CmsDataAccessException {
CmsResourceState resourceState = fixMovedResource(
dbc,
onlin... |
python | def get_versions(default=DEFAULT, verbose=False):
"""This variation of get_versions() will be used in versioneer.py ."""
# returns dict with two keys: 'version' and 'full'
assert versionfile_source is not None, "please set versioneer.versionfile_source"
assert tag_prefix is not None, "please set versi... |
java | public static int getResources_getInteger(Context context, int id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
return context.getResources().getInteger(id);
}
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float widthDp = metrics... |
python | def delete_package(path, packages):
"""Remove downloaded packages
"""
if _meta_.del_all in ["on", "ON"]:
for pkg in packages:
os.remove(path + pkg) |
python | def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix p... |
python | def ignore_copy(func):
"""
Decorator for wrapping the __getattr__ function for classes that are copied via deepcopy. This prevents infinite
recursion caused by deepcopy looking for magic functions in the class. Any class implementing __getattr__ that is
meant to be deepcopy'd should use this decorator.... |
java | public void take() throws AWTException {
Rectangle area = new Rectangle(dimensions);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(area);
data = getByteArray(image);
} |
python | def request_object_encryption(msg, service_context, **kwargs):
"""
Created an encrypted JSON Web token with *msg* as body.
:param msg: The mesaqg
:param service_context:
:param kwargs:
:return:
"""
try:
encalg = kwargs["request_object_encryption_alg"]
except KeyError:
... |
java | private void addImports(Collection<String> sink,
Collection<String> paths, Multimap<String, String> publicImports) {
for (String path : paths) {
if (sink.add(path)) {
addImports(sink, publicImports.get(path), publicImports);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.