language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def chunked_list(_list, _chunk_size=50):
"""
Break lists into small lists for processing:w
"""
for i in range(0, len(_list), _chunk_size):
yield _list[i:i + _chunk_size] |
java | public void addELResolver(ELResolver resolver)
{
// The following concrete methods were added for JSF 1.2. They supply default
// implementations that throw UnsupportedOperationException.
// This allows old Application implementations to still work.
Application application = getM... |
java | private void inflateLayers(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
throws XmlPullParserException, IOException {
final LayerState state = mLayerState;
final int innerDepth = parser.getDepth() + 1;
int type;
int depth;
while ((type... |
python | def ch_config(cmd, *args, **kwargs):
'''
This function is called by the
:mod:`salt.modules.esxi.cmd <salt.modules.esxi.cmd>` shim.
It then calls whatever is passed in ``cmd`` inside the
:mod:`salt.modules.vsphere <salt.modules.vsphere>` module.
Passes the return through from the vsphere module.
... |
java | private void initialize(final File logDirectory, final String aaplName) {
if (logDirectory == null) {
captureEnabled = false;
return;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
// C... |
python | def save_data(self, filename = None, data_tag = None, verbose=False):
"""
saves the script data to a file
filename: target filename, if not provided, it is created from internal function
data_tag: string, if provided save only the data that matches the tag, otherwise save all data
... |
java | static Shell createTelnetConsoleShell(String prompt, String appName,
ShellCommandHandler mainHandler, InputStream input, OutputStream output) {
try {
// Set up nvt4j; ignore the initial clear & reposition
final nvt4j.impl.Terminal nvt4jTerminal = new nvt4j.impl.Terminal(input... |
python | def laid_out_slice_num(self, tensor_shape):
"""A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar.
"""
ret = self.... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.TEXT_FIDELITY__STP_TXT_EX:
return getStpTxtEx();
case AfplibPackage.TEXT_FIDELITY__REP_TXT_EX:
return getRepTxtEx();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public String printExample(OptionHandlerFilter mode, ResourceBundle rb) {
StringBuilder buf = new StringBuilder();
checkNonNull(mode, "mode");
for (OptionHandler h : options) {
OptionDef option = h.option;
if(option.usage().length()==0) continue; // ignore
... |
java | public ReplicationInner get(String resourceGroupName, String registryName, String replicationName) {
return getWithServiceResponseAsync(resourceGroupName, registryName, replicationName).toBlocking().single().body();
} |
java | public static double computeDistance( double lat1, double lon1, double lat2, double lon2 ) {
// Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
// using the "Inverse Formula" (section 4)
int MAXITERS = 20;
// Convert lat/long to radians
lat1 *= Math.PI / 180.0;
lat2... |
java | @SuppressWarnings("deprecation")
@Override
public List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try ... |
java | @Override
public int compareTo(ExtendedSet<T> o) {
return indices.compareTo(convert(o).indices);
} |
python | def stack_template_key_name(blueprint):
"""Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint.
"""
name = bluep... |
python | def _SetHeader(self, new_values):
"""Sets header of table to the given tuple.
Args:
new_values: Tuple of new header values.
"""
row = self.row_class()
row.row = 0
for v in new_values:
row[v] = v
self._table[0] = row |
python | def _words_at_the_beginning(word, tree, prefix=""):
'''
We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations.
'''
l = []
if "" in tree:
l.append([prefix, tree[""]])
... |
java | public String format(CheckLevel level, MessageFormatter formatter) {
switch (level) {
case ERROR:
return formatter.formatError(this);
case WARNING:
return formatter.formatWarning(this);
default:
return null;
}
} |
java | @Pure
public BusItineraryHalt getBusHalt(UUID uuid) {
if (uuid == null) {
return null;
}
for (final BusItineraryHalt busHalt : this.validHalts) {
if (uuid.equals(busHalt.getUUID())) {
return busHalt;
}
}
for (final BusItineraryHalt busHalt : this.invalidHalts) {
if (uuid.equals(busHalt.getUUI... |
java | @Inject(method = "loadTextureAtlas", at = @At("RETURN"), locals = LocalCapture.CAPTURE_FAILSOFT)
private void onLoadTextureAtlas(IResourceManager resourceManager, CallbackInfo ci, int i, Stitcher stitcher, int j, int k, ProgressManager.ProgressBar bar)
{
Icon.BLOCK_TEXTURE_WIDTH = stitcher.getCurrentWidth();
Icon... |
python | def load_tweets(filename='tweets.zip'):
r"""Extract the cached tweets "database" if necessary and load + parse the json.
>>> js = load_tweets()
>>> len(js)
8000
>>> js[0].keys()
[u'contributors',
u'truncated',
u'text',
u'is_quote_status',
u'in_reply_to_status_id',
u'id'... |
java | static TypeSignature parse(final Parser parser, final String definingClass) throws ParseException {
final ReferenceTypeSignature referenceTypeSignature = ReferenceTypeSignature
.parseReferenceTypeSignature(parser, definingClass);
if (referenceTypeSignature != null) {
return r... |
java | private void readColDefinitions() {
// VALUE COLUMNS AND COLUMNS THAT ARE NOT PART OF THE PRIMARY KEY
Statement query = QueryBuilder.select().from("system", "schema_columns")
.where(eq("keyspace_name", keyspaceName))
.and(eq("columnfamily_name", cfName));
ResultSet rs = session.execute(query);
Lis... |
python | def generate(env):
"""Add Builders and construction variables for dvipdf to an Environment."""
global PDFAction
if PDFAction is None:
PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')
global DVIPDFAction
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdf... |
java | public EObject getIndexedJvmType(URI javaObjectURI, ResourceSet resourceSet) throws UnknownNestedTypeException {
return getIndexedJvmType(javaObjectURI, resourceSet, false);
} |
python | def _parse_logfile(self, logfile):
"""
Parse the formatted logfile.
"""
cycle_patt = re.compile(r"Coordinates\sin\sGeometry\sCycle\s(\d+)")
coord_patt = re.compile(r"\s+([0-9]+)\.([A-Za-z]+)"+3*r"\s+([-\.0-9]+)")
energy_patt = re.compile(r"<.*>\s<.*>\s+current\senergy\s+... |
python | def get_log_likelihood(inputs,data,clust):
"""Get the LL of a combined set of clusters, ignoring time series offsets.
Get the log likelihood of a cluster without worrying about the fact
different time series are offset. We're using it here really for those
cases in which we only have one cluster to... |
python | def write_uchar(self, c):
"""
Writes an C{unsigned char} to the stream.
@param c: Unsigned char
@type c: C{int}
@raise TypeError: Unexpected type for int C{c}.
@raise OverflowError: Not in range.
"""
if type(c) not in python.int_types:
raise T... |
python | def clear(self):
"""Clears the cache."""
if self._cache is None:
return _NO_RESULTS
if self._cache is not None:
with self._cache as k:
res = [x.as_operation() for x in k.values()]
k.clear()
k.out_deque.clear()
... |
java | public static String decrypt(String key, String source) {
try {
// Get our secret key
Key key0 = getKey(key);
// Create the cipher
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//byte[] b64cipherText = StringUtil.getAsciiBytes(source)... |
python | def branch(self, root, parts):
"""
Traverse the path until a leaf is reached.
@param parts: A list of path parts.
@type parts: [str,..]
@param root: The root.
@type root: L{xsd.sxbase.SchemaObject}
@return: The end of the branch.
@rtype: L{xsd.sxbase.Schem... |
java | OutboundTcpConnection getConnection(MessageOut msg)
{
Stage stage = msg.getStage();
return stage == Stage.REQUEST_RESPONSE || stage == Stage.INTERNAL_RESPONSE || stage == Stage.GOSSIP
? ackCon
: cmdCon;
} |
java | @NonNull
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users
public Searcher removeFacetRefinement(@NonNull String attribute, @NonNull String value) {
List<String> attributeRefinements = getOrCreateRefinements(attribute);
attributeRefinements.remove(value);
rebuildQueryFac... |
python | def find_customer(cls, session, mailbox, customer):
"""Return conversations for a specific customer in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to search.
customer (helpscout.models.Custo... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case XtextPackage.CHARACTER_RANGE__LEFT:
return getLeft();
case XtextPackage.CHARACTER_RANGE__RIGHT:
return getRight();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public java.util.List<NetworkAclEntry> getEntries() {
if (entries == null) {
entries = new com.amazonaws.internal.SdkInternalList<NetworkAclEntry>();
}
return entries;
} |
java | private boolean linksToOtherDomain(Adaptable adaptable, Page currentPage, Resource targetResource) {
if (currentPage == null || targetResource == null) {
return false;
}
UrlHandlerConfig urlHandlerConfig = AdaptTo.notNull(adaptable, UrlHandlerConfig.class);
Resource currentResource = AdaptTo.notN... |
java | @MemberOrder(sequence = "2")
public ExampleTaggableEntity create(
final @ParameterLayout(named="Name") String name,
final @ParameterLayout(named="Brand") String brand,
final @ParameterLayout(named="Sector") String sector) {
final ExampleTaggableEntity obj = container.newT... |
python | def mandelbrot_iterate(c, max_iterations, julia_seed=None):
"""
Returns the number of iterations before escaping the Mandelbrot fractal.
:param c: Coordinates as a complex number
:type c: complex
:param max_iterations: Limit of how many tries are attempted.
:return: Tuple containing the last co... |
python | def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False,
truesize=None):
"""Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
... |
java | public static byte[] hexString2Bytes(String hexString) {
if (StringKit.isBlank(hexString)) return null;
int len = hexString.length();
if (len % 2 != 0) {
hexString = "0" + hexString;
len = len + 1;
}
char[] hexBytes = hexString.toUpperCase().toCharArray();... |
java | CmsTreeOpenState getVfsTreeState(String treeToken) {
return (CmsTreeOpenState)(getRequest().getSession().getAttribute(
getTreeOpenStateAttributeName(I_CmsGalleryProviderConstants.TREE_VFS, treeToken)));
} |
java | public EvolutionResult<G, C> evolve(final EvolutionStart<G, C> start) {
final Timer timer = Timer.of(_clock).start();
// Initial evaluation of the population.
final Timer evaluateTimer = Timer.of(_clock).start();
final ISeq<Phenotype<G, C>> evalPop =
_evaluator.evaluate(start.getPopulation());
if (start.... |
java | private boolean hasFallbackChildren()
{
for (ElemTemplateElement child = m_firstChild; child != null;
child = child.m_nextSibling)
{
if (child.getXSLToken() == Constants.ELEMNAME_FALLBACK)
return true;
}
return false;
} |
python | def get_query(query_id, session, retry_count=5):
"""attemps to get the query and retry if it cannot"""
query = None
attempt = 0
while not query and attempt < retry_count:
try:
query = session.query(Query).filter_by(id=query_id).one()
except Exception:
attempt += 1... |
python | def get_package_changes(self, feed_id, continuation_token=None, batch_size=None):
"""GetPackageChanges.
[Preview API] Get a batch of package changes made to a feed. The changes returned are 'most recent change' so if an Add is followed by an Update before you begin enumerating, you'll only see one chan... |
java | public void abort(final Executor exec) throws SQLException {
if (exec == null) {
throw new SQLException("Missing executor");
} // end of if
if (this.closed) {
return;
} // end of if
this.closed = true;
} |
python | def getDignities(self):
""" Returns the dignities belonging to this object. """
info = self.getInfo()
dignities = [dign for (dign, objID) in info.items()
if objID == self.obj.id]
return dignities |
python | def nfa_nonuniversality_check(nfa: dict) -> bool:
""" Checks if the language read by the input NFA is different
from Σ∗ (i.e. contains all possible words), returning
True/False.
To test nfa A for nonuniversality, it suffices to test Ā (
complementary automaton of A) for nonemptiness
:param dic... |
python | def clear_breakpoints(self):
"""Clear breakpoints"""
self.breakpoints = []
for data in self.editor.blockuserdata_list[:]:
data.breakpoint = False
# data.breakpoint_condition = None # not necessary, but logical
if data.is_empty():
# This is not... |
python | def _version(self):
"""Deduce the version number of the downloaded package from its filename."""
# TODO: Can we delete this method and just print the line from the
# reqs file verbatim instead?
def version_of_archive(filename, package_name):
# Since we know the project_name, ... |
java | protected KdTree.Node computeBranch(List<P> points, GrowQueue_I32 indexes)
{
// declare storage for the split data
List<P> left = new ArrayList<>(points.size()/2);
List<P> right = new ArrayList<>(points.size()/2);
GrowQueue_I32 leftIndexes,rightIndexes;
if( indexes == null ) {
leftIndexes = null; rightIn... |
java | @SuppressWarnings("unchecked")
private CompletableFuture<Object> execute(final String oldHostId, final TaskData taskData, final TaggedResource taggedResource) {
log.debug("Host={} attempting to execute task {}-{} for child <{}, {}> of {}",
this.hostId, taskData.getMethodName(), taskData.get... |
python | def getService(self, serviceIdentifier):
"""
Return the requested service instance.
:param serviceIdentifier: <str> service identifier
:return: <object> service instance
"""
if serviceIdentifier in self._services:
return self._services[serviceIdentifier]
... |
java | public static boolean hasNonDeuteratedEquiv(Atom atom, Group currentGroup) {
if(atom.getElement()==Element.D && currentGroup.hasAtom(replaceFirstChar(atom.getName(),'D', 'H'))) {
// If it's deuterated and has a non-deuterated brother
return true;
}
return false;
} |
python | def tune_learning_rate(self, h, parameter_list=None):
""" Naive tuning of the the learning rate on the in-sample data
Parameters
----------
h : int
How many steps to run Aggregate on
parameter_list: list
List of parameters to search for a good le... |
java | public void unshare(int needExtra)
{
int len = mInputLen;
mInputLen = 0;
char[] inputBuf = mInputBuffer;
mInputBuffer = null;
int start = mInputStart;
mInputStart = -1;
// Is buffer big enough, or do we need to reallocate?
int needed = len+needExtra;
... |
python | def _error_msg_iface(iface, option, expected):
'''
Build an appropriate error message from a given option and
a list of expected values.
'''
msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]'
return msg.format(iface, option, '|'.join(str(e) for e in expected)) |
java | public Project.Layouts.Layout.Bars.BarGroup createProjectLayoutsLayoutBarsBarGroup()
{
return new Project.Layouts.Layout.Bars.BarGroup();
} |
python | def _judeNOtIn(self, raw_str, ele_list):
'''
判断ele是否在原始字符串中
args:
raw_str 源字符串
ele_list 待检查的列表
return
boolean
'''
for ele in ele_list:
if ele in raw_str:
return False
return True |
java | @SuppressWarnings("unchecked")
public static Map<String, List<Object[]>> getDebugInfoMap(String clientId)
{
final Map<String, Object> requestMap = FacesContext.getCurrentInstance()
.getExternalContext().getRequestMap();
Map<String, List<Object[]>> debugInfo = (Map<String, List<Ob... |
python | def yticktext(self, labels, index=1):
"""Set the tick labels.
Parameters
----------
labels : array-like
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['ticktext'] = labels
return self |
java | private Matrix<Double> generateRandomMatrix(final int nRows, final int nColumns) {
final List<List<Double>> rows = new ArrayList<>(nRows);
final Random random = new Random();
for (int i = 0; i < nRows; i++) {
final List<Double> row = new ArrayList<>(nColumns);
for (int j = 0; j < nColumns; j++) ... |
java | public static void initialize(HttpServletRequest request) {
if (factory == null) {
throw new RuntimeException("RaygunClient is not initialized. Call RaygunClient.Initialize()");
}
client.set(factory.newClient(request));
} |
java | private static String generateCrudReplicatedUpdate(Table table, Constraint pkey)
{
StringBuilder sb = new StringBuilder();
sb.append("UPDATE " + table.getTypeName() + " SET ");
generateCrudExpressionColumns(table, sb);
generateCrudPKeyWhereClause(null, pkey, sb);
sb.append('... |
java | @Override
public void configure() throws Exception {
final Namespaces ns = new Namespaces("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
ns.add("indexing", "http://fedora.info/definitions/v4/indexing#");
final XPathBuilder indexable = new XPathBuilder(
String.format... |
java | @EventHandler("drop")
private void onDrop(DropEvent event) {
BaseComponent dragged = event.getRelatedTarget();
if (dragged instanceof DropContainer) {
getParent().addChild(dragged, this);
}
} |
java | public void setDeferredTrailer(HeaderKeys hdr, HttpTrailerGenerator htg) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "setDeferredTrailer(HeaderKeys): " + hdr);
}
if (null == hdr) {
throw new IllegalArgumentException("Null header name");
}
if (null == htg) {
... |
java | public ListUploadsResult withUploads(Upload... uploads) {
if (this.uploads == null) {
setUploads(new java.util.ArrayList<Upload>(uploads.length));
}
for (Upload ele : uploads) {
this.uploads.add(ele);
}
return this;
} |
python | def sink(self, *args, **kwargs):
"""Define URL prefixes/handler matches where everything under the URL prefix should be handled"""
kwargs['api'] = self.api
return sink(*args, **kwargs) |
java | public static LocalDate of(int year, Month month, int dayOfMonth) {
YEAR.checkValidValue(year);
Objects.requireNonNull(month, "month");
DAY_OF_MONTH.checkValidValue(dayOfMonth);
return create(year, month.getValue(), dayOfMonth);
} |
java | public static void setFlotHome(String flotHome) {
if (flotHome == null || flotHome.trim().isEmpty()) {
System.clearProperty(SYSTEM_PROPERTY_FLOT_HOME);
} else {
final String propValue = flotHome.endsWith("/") ? flotHome.substring(0, flotHome.length() - 1) : flotHome;
... |
java | public void setInstructions(List<String> instructions) {
synchronized (this.instructions) {
this.instructions.clear();
this.instructions.addAll(instructions);
}
} |
python | def normalized(self):
""":obj:`DualQuaternion`: This quaternion with qr normalized.
"""
qr = self.qr /1./ np.linalg.norm(self.qr)
return DualQuaternion(qr, self.qd, True) |
java | public void startMcGregorIteration(int largestMappingSize, List<Integer> cliqueVector,
List<Integer> compGraphNodes) throws IOException {
this.globalMCSSize = (largestMappingSize / 2);
List<String> cTab1Copy = McGregorChecks.generateCTabCopy(source);
List<String> cTab2Copy = McGrego... |
python | def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method.
"""
component1 = self
component2 = other
# base glyphs
if component1.baseName != compo... |
python | def default(self, line):
''' if no other commands was invoked '''
try:
encoding, count = self._ks.asm(line)
machine_code = ""
for opcode in encoding:
machine_code += "\\x" + hexlify(pack("B", opcode)).decode()
print("\"" + machine_code + "\... |
python | def get(self, request, bot_id, id, format=None):
"""
Get Messenger chat state by id
---
serializer: MessengerChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(MessengerChatStateDetail, s... |
python | def search(self):
"""
The search function returns an array of Listing objects.
:return: Listing object
"""
self.set_url()
listings = []
request = Request(debug=self._debug)
url = self.get_url()
soup = request.get(url)
divs = soup.find_all("... |
java | public Date getDate(String name) {
String value = get(name);
return value != null ? HttpDate.parse(value) : null;
} |
python | def put(self, measurementId, deviceId):
"""
Fails the measurement for this device.
:param measurementId: the measurement name.
:param deviceId: the device name.
:return: 200 if
"""
payload = request.get_json()
failureReason = json.loads(payload).get('failu... |
java | private void dateLabelMousePressed(MouseEvent e) {
// Get the label that was clicked.
JLabel label = (JLabel) e.getSource();
// If the label is empty, do nothing and return.
String labelText = label.getText();
if ("".equals(labelText)) {
return;
}
// W... |
python | def unauthorized(cls, errors=None):
"""Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'a... |
python | def docker_inspect(image):
'''Inspects a docker image
Returns: Parsed JSON data
'''
args = ['docker', 'inspect', '--type', 'image', image]
p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stder... |
java | @Modified
protected void modified(ComponentContext context,
Map<String, Object> properties) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, CLASS_NAME + "modified", new Object[] { context,
... |
python | def _get_url_node(parser, bits):
"""
Parses the expression as if it was a normal url tag. Was copied
from the original function django.template.defaulttags.url,
but unnecessary pieces were removed.
"""
viewname = parser.compile_filter(bits[1])
args = []
kwargs = {}
bits = bits[2:]
... |
python | def get(self, key, defaultValue=None):
"""Get the configured value for some key, or return a default otherwise."""
if defaultValue is None: # Py4J doesn't call the right get() if we pass None
if self._jconf is not None:
if not self._jconf.contains(key):
... |
java | public List<AuditLogChange> getChangesForKeys(AuditLogKey... keys)
{
Checks.notNull(keys, "Keys");
List<AuditLogChange> changes = new ArrayList<>(keys.length);
for (AuditLogKey key : keys)
{
AuditLogChange change = getChangeByKey(key);
if (change != null)
... |
python | def gss(args):
"""
%prog gss fastafile plateMapping
Generate sequence files and metadata templates suited for gss submission.
The FASTA file is assumed to be exported from the JCVI data delivery folder
which looks like:
>1127963806024 /library_name=SIL1T054-B-01-120KB /clear_start=0
/clear... |
java | public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
methodVisitor.visitLdcInsn(javaConstant.asConstantPoolValue());
return StackSize.SINGLE.toIncreasingSize();
} |
python | def current_livechat(request):
"""
Checks if a live chat is currently on the go, and add it to the request
context.
This is to allow the AskMAMA URL in the top-navigation to be redirected to
the live chat object view consistently, and to make it available to the
views and tags that depends on i... |
java | public ServiceFuture<ContainerServiceInner> beginCreateOrUpdateAsync(String resourceGroupName, String containerServiceName, ContainerServiceInner parameters, final ServiceCallback<ContainerServiceInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGrou... |
python | def getRoles(self, principal_id):
"""
give an Owner who is also a 'selfpublisher', the reviewer role
"""
context = self.context
current_roles = list(DefaultLocalRoleAdapter.getRoles(
self,
principal_id,
))
# check we are not on the workspa... |
python | def extended_help_option(extended_help=None, *param_decls, **attrs):
"""
Based on the click.help_option code.
Adds a ``--extended-help`` option which immediately ends the program
printing out the extended extended-help page. Defaults to using the
callback's doc string, but can be given an explicit ... |
python | def by_id(cls, semantictag_id, autoflush=True):
'''Return the semantic tag with the given id, or None.
:param semantictag_id: the id of the semantic tag to return
:type semantictag_id: string
:returns: the semantic tag with the given id, or None if there is no tag with
that id
:rtype: ckan.model.semantic... |
python | def delta_encode(data, axis=-1, out=None):
"""Encode Delta."""
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
diff = numpy.diff(data, axis=0)
return numpy.insert(diff, 0, data[0]).tobytes()
dtype = data.dtype
if dtype.kind == 'f':
data... |
java | @Override
public ExprBuilderKelp buildKelp(QueryBuilderKraken builder)
{
ExprBuilderKelp expr = _expr.buildKelp(builder);
ExprBuilderKelp min = _min.buildKelp(builder);
ExprBuilderKelp max = _max.buildKelp(builder);
return expr.between(min, max);
} |
java | public static Pair<String, ImageArchiveManifestEntry> findEntryByRepoTagPattern(Pattern repoTagPattern, ImageArchiveManifest manifest) throws PatternSyntaxException {
if(repoTagPattern == null || manifest == null) {
return null;
}
Matcher matcher = repoTagPattern.matcher("");
... |
java | public static @Nonnull
Collection<User> getAll() {
final IdStrategy strategy = idStrategy();
ArrayList<User> users = new ArrayList<>(AllUsers.values());
users.sort((o1, o2) -> strategy.compare(o1.getId(), o2.getId()));
return users;
} |
python | def create(self, article, attachment, inline=False, file_name=None, content_type=None):
"""
This function creates attachment attached to article.
:param article: Numeric article id or :class:`Article` object.
:param attachment: File object or os path to file
:param inline: If tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.