language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_port_profile_status_input_request_type_getnext_request_last_received_port_profile_info_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
... |
java | @BetaApi
public final AggregatedListAcceleratorTypesPagedResponse aggregatedListAcceleratorTypes(
ProjectName project) {
AggregatedListAcceleratorTypesHttpRequest request =
AggregatedListAcceleratorTypesHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
... |
python | def sample_upper_hull(upper_hull, random_stream):
"""
Return a single value randomly sampled from
the given `upper_hull`.
Parameters
----------
upper_hull : List[pyars.hull.HullNode]
Upper hull to evaluate.
random_stream : numpy.random.RandomState
(Seeded) stream of random ... |
java | public static int search(short[] shortArray, short value, int occurrence) {
if(occurrence <= 0 || occurrence > shortArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
... |
java | protected FaihyUnifiedFailureResult newUnifiedFailureResult(FaihyUnifiedFailureType failureType, List<FaihyFailureErrorPart> errors) {
return new FaihyUnifiedFailureResult(failureType, errors);
} |
java | public Set<Permission> authorize(AuthenticatedUser user, IResource resource)
{
if (user.isSuper())
return Permission.ALL;
UntypedResultSet result;
try
{
ResultMessage.Rows rows = authorizeStatement.execute(QueryState.forInternalCalls(),
... |
java | private boolean accepted(Row row, List<IndexExpression> expressions) {
if (!expressions.isEmpty()) {
Columns columns = rowMapper.columns(row);
for (IndexExpression expression : expressions) {
if (!accepted(columns, expression)) {
return false;
... |
python | def bool_from(obj, default=False):
"""Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is
None, 'default' is used.
"""
return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default) |
java | public Observable<ServiceResponse<Page<SiteInner>>> beginResumeNextWithServiceResponseAsync(final String nextPageLink) {
return beginResumeNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() {
@Overr... |
java | public StringBuffer format(Object pObj, StringBuffer pToAppendTo,
FieldPosition pPos) {
if (!(pObj instanceof Time)) {
throw new IllegalArgumentException("Must be instance of " + Time.class);
}
return pToAppendTo.append(format(pObj));
} |
java | public JMenuItem add(UserInterfaceAction action)
{
try
{
Method _specializedMethod = getClass().getMethod(FUNCTION_NAME_ADD, new Class[]
{
action.getClass()
});
return (JMenuItem) _specializedMethod.invoke(this, new Object[]
{
action
});
}
catch (Exception _exception)
{
_exceptio... |
python | def clone(self, opts):
'''
Create a new instance of this type with the specified options.
Args:
opts (dict): The type specific options for the new instance.
'''
topt = self.opts.copy()
topt.update(opts)
return self.__class__(self.modl, self.name, self... |
python | def ravel(self, name=None):
"""
Convert 2D histogram into 1D histogram with the y-axis repeated along
the x-axis, similar to NumPy's ravel().
"""
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
left_edge = self.xedgesl(1)
right_edge = self.xedgesh(nbinsx)
... |
python | def localize(date_time, time_zone):
"""Returns a datetime adjusted to a timezone:
* If dateTime is a naive datetime (datetime with no timezone information), timezone information is added but date
and time remains the same.
* If dateTime is not a naive datetime, a datetime object with new tzinfo att... |
python | def variable_length_to_fixed_length_categorical(
self, left_edge=4, right_edge=4, max_length=15):
"""
Encode variable-length sequences using a fixed-length encoding designed
for preserving the anchor positions of class I peptides.
The sequences must be of length at l... |
python | def check():
"""Command for checking upgrades."""
upgrader = InvenioUpgrader()
logger = upgrader.get_logger()
try:
# Run upgrade pre-checks
upgrades = upgrader.get_upgrades()
# Check if there's anything to upgrade
if not upgrades:
logger.info("All upgrades h... |
python | def flux_randomization(model, threshold, tfba, solver):
"""Find a random flux solution on the boundary of the solution space.
The reactions in the threshold dictionary are constrained with the
associated lower bound.
Args:
model: MetabolicModel to solve.
threshold: dict of additional l... |
java | public CMAArray<CMASpaceMembership> fetchAll(Map<String, String> query) {
throwIfEnvironmentIdIsSet();
return fetchAll(spaceId, query);
} |
java | synchronized public void addClusterChangeListener(ClusterEventListener l) {
if (listeners == null)
listeners = new Vector();
listeners.addElement(l);
} |
python | def request_anime(client, aid: int) -> 'Anime':
"""Make an anime API request."""
response = api.httpapi_request(client, request='anime', aid=aid)
etree = api.unpack_xml(response.text)
return _unpack_anime(etree.getroot()) |
java | public static RequestReporter initRequestReporter(FilterConfig filterConfig) {
String className = filterConfig.getInitParameter(SimonServletFilter.INIT_PARAM_REQUEST_REPORTER_CLASS);
if (className == null) {
return new DefaultRequestReporter();
} else {
try {
return (RequestReporter) Class.forNa... |
java | public void marshall(InstanceFleet instanceFleet, ProtocolMarshaller protocolMarshaller) {
if (instanceFleet == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(instanceFleet.getId(), ID_BINDING);
... |
java | protected Comparator<OpenCLDevice> getDefaultAcceleratorComparator() {
return new Comparator<OpenCLDevice>() {
@Override
public int compare(OpenCLDevice left, OpenCLDevice right) {
return (right.getMaxComputeUnits() - left.getMaxComputeUnits());
}
};
} |
python | def make_secure_adaptor(service, mod, client_id, client_secret, tok_update_sec=None):
"""
:param service: Service to wrap in.
:param mod: Name (type) of token refresh backend.
:param client_id: Client identifier.
:param client_secret: Client secret.
:param tok_update_sec:... |
python | def get_position(self, dt):
"""Given dt in [0, 1], return the current position of the tile."""
return self.sx + self.dx * dt, self.sy + self.dy * dt |
java | @Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__EXPRESSION:
return basicSetExpression(null, msgs);
case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__EACH_EXPRESSION:
re... |
python | def explain_instance(self,
text_instance,
classifier_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
distance_metric='cosine... |
java | public Model addEdge(Edge edge) {
edges.add(edge);
if (isNotNull(edge.getSourceVertex()) && !vertices.contains(edge.getSourceVertex())) {
vertices.add(edge.getSourceVertex());
}
if (isNotNull(edge.getTargetVertex()) && !vertices.contains(edge.getTargetVertex())) {
vertices.add(edge.getTarget... |
java | protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId,
final Authentication authentication, final OAuthCode code) {
val attributes = authentication.getAttributes();
val state = attributes.get(OAut... |
python | def delete_account_group(self, account_id, group_id, **kwargs): # noqa: E501
"""Delete a group. # noqa: E501
An endpoint for deleting a group. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID} -H 'Authorization: Bearer API_KEY'` ... |
python | def format_error(status=None, title=None, detail=None, code=None):
'''Formatting JSON API Error Object
Constructing an error object based on JSON API standard
ref: http://jsonapi.org/format/#error-objects
Args:
status: Can be a http status codes
title: A summary of error
detail: ... |
python | def update_ports(self):
"""
Sets the `ports` attribute to the set of valid port values set in
the configuration.
"""
ports = set()
for port in self.configured_ports:
try:
ports.add(int(port))
except ValueError:
logg... |
java | public static BlockPos chunkPosition(BlockPos pos)
{
return new BlockPos(pos.getX() - (pos.getX() >> 4) * 16, pos.getY() - (pos.getY() >> 4) * 16, pos.getZ() - (pos.getZ() >> 4) * 16);
} |
python | def classifySPoutput(targetOutputColumns, outputColumns):
"""
Classify the SP output
@param targetOutputColumns (list) The target outputs, corresponding to
different classes
@param outputColumns (array) The current output
@return classLabel (int) classification outcome
""... |
java | public LeafNode<K, V> prevNode() {
if (leftid == NULL_ID) {
return null;
}
return (LeafNode<K, V>) tree.getNode(leftid);
} |
java | public synchronized void insert(double value) {
buffer[bufferCount] = value;
bufferCount++;
if (bufferCount == buffer.length) {
insertBatch();
compress();
}
} |
java | protected int transitionWithRoot(int nodePos, char c)
{
int b = base[nodePos];
int p;
p = b + c + 1;
if (b != check[p])
{
if (nodePos == 0) return 0;
return -1;
}
return p;
} |
python | def neighbors2(self, distance, chain_residue, atom = None, resid_list = None):
#atom = " CA "
'''this one is more precise since it uses the chain identifier also'''
if atom == None: # consider all atoms
lines = [line for line in self.atomlines(resid_list) if line[17:20] in allo... |
java | public Map<String, Integer> countByStatusAndMainComponentUuids(DbSession dbSession, CeQueueDto.Status status, Set<String> projectUuids) {
if (projectUuids.isEmpty()) {
return emptyMap();
}
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
executeLargeUpdates(
projectUu... |
python | def unpack(n, r=32):
"""Yield r > 0 bit-length integers splitting n into chunks.
>>> list(unpack(42, 1))
[0, 1, 0, 1, 0, 1]
>>> list(unpack(256, 8))
[0, 1]
>>> list(unpack(2, 0))
Traceback (most recent call last):
...
ValueError: unpack needs r > 0
"""
if r < 1:
... |
python | def convert_cluster_dict_keys_to_aliases(self, cluster_dict, alias_hash):
'''
Parameters
----------
cluster_dict : dict
dictionary stores information on pre-placement clustering
alias_hash : dict
Stores information on each input read file given to GraftM, ... |
java | public static String getString(String key)
{
if (RESOURCE_BUNDLE == null)
throw new RuntimeException("Localized messages from resource bundle '" + BUNDLE_NAME + "' not loaded during initialization of driver.");
try
{
if (key == null)
throw new Illegal... |
java | @Override
public void onModuleLoad() {
Theme defaultTheme = ThemeController.get().getDefaultTheme();
defaultTheme.addLink(new CssLink("theme/default/style/bootstrap.min.css", -2));
defaultTheme.addLink(new CssLink("theme/default/style/pwt-core.css", 0));
IconFont font = new IconFont("theme/default/style/fonte... |
python | def unset_impact_state(self):
"""Unset impact, only if impact state change is set in configuration
:return: None
"""
cls = self.__class__
if cls.enable_problem_impacts_states_change and not self.state_changed_since_impact:
self.state = self.state_before_impact
... |
java | public Map<String, String> mapAllStrings(String uri) throws IOException {
Map<String, String> strings = new HashMap<>();
Map<String, URL> resourcesMap = getResourcesMap(uri);
for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.En... |
python | def clientConnected(self, proto):
"""
Called when a client connects to the bus. This method assigns the
new connection a unique bus name.
"""
proto.uniqueName = ':1.%d' % (self.next_id,)
self.next_id += 1
self.clients[proto.uniqueName] = proto |
python | def gmean(x, weights=None):
"""
Return the weighted geometric mean of x
"""
w_arr, x_arr = _preprocess_inputs(x, weights)
return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=0)) |
python | def from_element(cls, element):
"""Set the resource properties from a ``<res>`` element.
Args:
element (~xml.etree.ElementTree.Element): The ``<res>``
element
"""
def _int_helper(name):
"""Try to convert the name attribute to an int, or None."""
... |
python | def fastqIteratorComplex(fn, useMutableString=False, verbose=False):
"""
A generator function which yields FastqSequence objects read from a file or
stream. This iterator can handle fastq files that have their sequence
and/or their quality data split across multiple lines (i.e. there are
newline chara... |
python | def median_fltr(dem, fsize=7, origmask=False):
"""Scipy.ndimage median filter
Does not properly handle NaN
"""
print("Applying median filter with size %s" % fsize)
from scipy.ndimage.filters import median_filter
dem_filt_med = median_filter(dem.filled(np.nan), fsize)
#Now mask all nans
... |
java | private static StringMap filterParam(StringMap params) {
final StringMap ret = new StringMap();
if (params == null) {
return ret;
}
params.forEach(new StringMap.Consumer() {
@Override
public void accept(String key, Object value) {
if (v... |
java | public FirewallRuleInner createOrUpdateFirewallRule(String resourceGroupName, String accountName, String name, FirewallRuleInner parameters) {
return createOrUpdateFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, name, parameters).toBlocking().single().body();
} |
python | def __set_html(self, html=None):
"""
Sets the html content in the View using given body.
:param html: Html content.
:type html: unicode
"""
self.__html = self.__get_html(html)
self.__view.setHtml(self.__html) |
java | private static final double scoreAfp(AFP afp, double badRmsd, double fragScore)
{
//longer AFP with low rmsd is better
double s, w;
//s = (rmsdCut - afptmp.rmsd) * afptmp.len; //the same scroing strategy as that in the post-processing
w = afp.getRmsd() / badRmsd;
w = w * w;
s = fragScore * (1.0 - w);
re... |
python | def search(self, CorpNum, JobID, Type, TaxType, PurposeType, TaxRegIDType, TaxRegIDYN, TaxRegID, Page, PerPage,
Order, UserID=None):
""" ์์ง ๊ฒฐ๊ณผ ์กฐํ
args
CorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
JobID : ์์
์์ด๋
Type : ๋ฌธ์ํํ ๋ฐฐ์ด, N-์ผ๋ฐ์ ์์ธ๊ธ๊ณ์ฐ์, M-์์ ์ ์์ธ๊ธ๊ณ์ฐ์
... |
java | protected Thread createPump(InputStream is, OutputStream os,
boolean closeWhenExhausted) {
return createPump(is, os, closeWhenExhausted, true);
} |
java | public void marshall(OrderByElement orderByElement, ProtocolMarshaller protocolMarshaller) {
if (orderByElement == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(orderByElement.getFieldName(), FIELDN... |
python | def _copy(self, other, copy_func):
"""
Copies the contents of another Constructable object to itself
:param object:
Another instance of the same class
:param copy_func:
An reference of copy.copy() or copy.deepcopy() to use when copying
lists, dicts a... |
python | def unpack(self, struct):
"""Read as many bytes as are required to extract struct then
unpack and return a tuple of the values.
Raises
------
UnderflowDecodeError
Raised when a read failed to extract enough bytes from the
underlying stream to extract the ... |
java | private boolean hasRoleMaster(String userId, String domain) {
DomainRoleEntry domainRole = domainAccessStore.getDomainRole(userId, Role.MASTER);
if (domainRole == null || !Arrays.asList(domainRole.getDomains()).contains(domain)) {
return false;
}
return true;
} |
java | public <T extends BaseNode> T attachNode(BuildContext context, T candidate) {
BaseNode node = null;
RuleBasePartitionId partition = null;
if ( candidate.getType() == NodeTypeEnums.EntryPointNode ) {
// entry point nodes are always shared
node = context.getKnowledgeBase().... |
java | public static String mix(String string, int key) {
return ascii(JavaEncrypt.base64(xor(string, key)), key);
} |
java | public static byte[] encodeSingleNullableDesc(byte[] value,
int prefixPadding, int suffixPadding) {
if (prefixPadding <= 0 && suffixPadding <= 0) {
if (value == null) {
return new byte[] {NULL_BYTE_LOW};
}
... |
python | def _merge_states(self, states):
"""
Merges a list of states.
:param states: the states to merge
:returns SimState: the resulting state
"""
if self._hierarchy:
optimal, common_history, others = self._hierarchy.most_mergeable(states)
else:
... |
java | public static void writeToOutputStream(String s, OutputStream output, String encoding) throws IOException {
BufferedReader reader = new BufferedReader(new StringReader(s));
PrintStream writer;
if (encoding != null) {
writer = new PrintStream(output, true, encoding);
}
else {
writer = new PrintStream(out... |
python | def appliance_device_snmp_v3_users(self):
"""
Gets the ApplianceDeviceSNMPv3Users API client.
Returns:
ApplianceDeviceSNMPv3Users:
"""
if not self.__appliance_device_snmp_v3_users:
self.__appliance_device_snmp_v3_users = ApplianceDeviceSNMPv3Users(self.__... |
python | def unload(self):
"""
Overridable method called when a view is unloaded (either on view change or on application shutdown).
Handles by default the unregistering of all event handlers previously registered by
the view.
"""
self.is_loaded = False
for evt in self._ev... |
java | public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager(
GenericStyledArea<PS, SEG, S> area, Duration preventMergeDelay) {
return plainTextUndoManager(area, UndoManagerFactory.unlimitedHistoryFactory(), preventMergeDelay);
} |
python | def register_plugins():
"""find any installed plugins and register them."""
if pkg_resources: # pragma: no cover
for ep in pkg_resources.iter_entry_points('slam_plugins'):
plugin = ep.load()
# add any init options to the main init command
if hasattr(plugin, 'init') ... |
java | public Observable<UUID> createCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, CreateCompositeEntityRoleOptionalParameter createCompositeEntityRoleOptionalParameter) {
return createCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, createCompositeEntityRoleOptionalPar... |
java | public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
if (active) {
if (log.isDebugEnabled())
log.debug("sessionDestroyed called for sessionId = "
+ httpSessionEvent.getSession().getId());
HttpSession session = httpSessionEvent.getSession();
HttpSessionWrapper wrapper = new Http... |
python | def get_value_from_user(sc):
"""
Prompts the user for a value for the symbol or choice 'sc'. For
bool/tristate symbols and choices, provides a list of all the assignable
values.
"""
if not sc.visibility:
print(sc.name + " is not currently visible")
return False
prompt = "Val... |
java | public void marshall(DeleteApnsVoipChannelRequest deleteApnsVoipChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteApnsVoipChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.mars... |
java | @NonNull
public Caffeine<K, V> ticker(@NonNull Ticker ticker) {
requireState(this.ticker == null, "Ticker was already set to %s", this.ticker);
this.ticker = requireNonNull(ticker);
return this;
} |
python | def _create_bam_region(paired, region, tmp_dir):
"""create temporal normal/tumor bam_file only with reads on that region"""
tumor_name, normal_name = paired.tumor_name, paired.normal_name
normal_bam = _slice_bam(paired.normal_bam, region, tmp_dir, paired.tumor_config)
tumor_bam = _slice_bam(paired.tumor... |
python | def on_message(self, message):
"""
Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
if 'content' in message['d']:
metadata = self._parse_metadata(message)
messa... |
python | def _check_coop(self, pore, queue):
r"""
Method run in loop after every pore invasion. All connecting throats
are now given access to the invading phase. Two throats with access to
the invading phase can cooperatively fill any pores that they are both
connected to, common pores.
... |
python | def run(self, from_email, recipients, message):
"""
This does the dirty work. Connects to Amazon SES via boto and fires
off the message.
:param str from_email: The email address the message will show as
originating from.
:param list recipients: A list of email addres... |
java | private String fixupAuthority(String uriAuthority, String charset) throws URIException {
// Lowercase the host part of the uriAuthority; don't destroy any
// userinfo capitalizations. Make sure no illegal characters in
// domainlabel substring of the uri authority.
if (uriAuthority != n... |
python | def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None):
'''
If template is a valid template engine, process the cmd and cwd through
that engine.
'''
if not template:
return (cmd, cwd)
# render the path as a template using path_template_engine as the en... |
java | public static <K, V> Pipes<K, V> of(final Map<K, Adapter<V>> registered) {
Objects.requireNonNull(registered);
final Pipes<K, V> pipes = new Pipes<>();
pipes.registered.putAll(registered);
return pipes;
} |
java | public synchronized void setString(String value) throws SQLException {
if (value == null) {
throw Util.nullArgument("value");
}
checkWritable();
setStringImpl(value);
setReadable(true);
setWritable(false);
} |
python | def to_json(self):
"""
Returns:
str:
"""
data = dict()
for key, value in self.__dict__.items():
if value:
if hasattr(value, 'to_dict'):
data[key] = value.to_dict()
elif isinstance(value, datetime):
... |
python | def get_indelcaller(d_or_c):
"""Retrieve string for indelcaller to use, or empty string if not specified.
"""
config = d_or_c if isinstance(d_or_c, dict) and "config" in d_or_c else d_or_c
indelcaller = config["algorithm"].get("indelcaller", "")
if not indelcaller:
indelcaller = ""
if is... |
java | @Override
public String filter(String value, String previousValue){
if(previousValue != null && value.length() > previousValue.length())
return value;
return value.equals("0") || value.equals("0.0") ? "" : value;
} |
python | def find_mismatches(gene, sbjct_start, sbjct_seq, qry_seq, alternative_overlaps = []):
"""
This function finds mis matches between two sequeces. Depending on the
the sequence type either the function find_codon_mismatches or
find_nucleotid_mismatches are called, if the sequences contains both
a pr... |
python | def restore(mongo_user, mongo_password, backup_tbz_path,
backup_directory_output_path="/tmp/mongo_dump",
drop_database=False, cleanup=True, silent=False,
skip_system_and_user_files=False):
"""
Runs mongorestore with source data from the provided .tbz backup, using
t... |
java | public void script(String line, DispatchCallback callback) {
if (sqlLine.getScriptOutputFile() == null) {
startScript(line, callback);
} else {
stopScript(line, callback);
}
} |
java | public String getFileSystemTypeLabel() {
final StringBuilder sb = new StringBuilder(FILE_SYSTEM_TYPE_LENGTH);
for (int i=0; i < FILE_SYSTEM_TYPE_LENGTH; i++) {
sb.append ((char) get8(getFileSystemTypeLabelOffset() + i));
}
return sb.toString();
} |
python | def clear_caches(self):
""" Clears the Caches for all model elements """
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, 'cache_val'):
delattr(element, 'cache_val') |
java | public int commandToDocType(String strCommand)
{
if (UserInfo.VERBOSE_MAINT_SCREEN.equalsIgnoreCase(strCommand))
return UserInfo.VERBOSE_MAINT_MODE;
if (UserInfo.LOGIN_SCREEN.equalsIgnoreCase(strCommand))
return UserInfo.LOGIN_SCREEN_MODE;
if (UserInfo.ENTRY_SCREEN.eq... |
java | public void genArgs(List<JCExpression> trees, List<Type> pts) {
for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
genExpr(l.head, pts.head).load();
pts = pts.tail;
}
// require lists be of same length
Assert.check(pts.isEmpty());
} |
java | public void setAdapter(final BaseCircularViewAdapter adapter) {
mAdapter = adapter;
if (mAdapter != null) {
mAdapter.registerDataSetObserver(mAdapterDataSetObserver);
}
postInvalidate();
} |
python | def authorize_url(self):
"""
Build the authorization url and save the state. Return the
authorization url
"""
url, self.state = self.oauth.authorization_url(
'%sauthorize' % OAUTH_URL)
return url |
python | def query_user_info(user):
"""
Returns the scraped user data from a twitter user page.
:param user: the twitter user to web scrape its twitter page info
"""
try:
user_info = query_user_page(INIT_URL_USER.format(u=user))
if user_info:
logger.info(f"Got user information... |
python | def _delete(self, **kwargs):
"""wrapped with delete, override that in a subclass to customize """
requests_params = self._handle_requests_params(kwargs)
delete_uri = self._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
# Check the generation for m... |
python | def error_message_and_exit(message, error_result):
"""Prints error messages in blue, the failed task result and quits."""
if message:
error_message(message)
puts(json.dumps(error_result, indent=2))
sys.exit(1) |
python | def dictdict_to_listdict(dictgraph):
"""Transforms a dict-dict graph representation into a
adjacency dictionary representation (list-dict)
:param dictgraph: dictionary mapping vertices to dictionary
such that dictgraph[u][v] is weight of arc (u,v)
:complexity: linear
:returns: tuple with... |
python | def get_site_name(request):
"""Return the domain:port part of the URL without scheme.
Eg: facebook.com, 127.0.0.1:8080, etc.
"""
urlparts = request.urlparts
return ':'.join([urlparts.hostname, str(urlparts.port)]) |
java | public final <R> Ix<R> map(IxFunction<? super T, ? extends R> mapper) {
return new IxMap<T, R>(this, mapper);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.