language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def write_crc32(fo, bytes):
"""A 4-byte, big-endian CRC32 checksum"""
data = crc32(bytes) & 0xFFFFFFFF
fo.write(pack('>I', data)) |
java | private int matchAnyToOne(final int wordIndex, final int candIndex) {
if (replacementsAnyToOne.containsKey(candidate[candIndex])) {
for (final char[] rep : replacementsAnyToOne.get(candidate[candIndex])) {
int i = 0;
while (i < rep.length && (wordIndex + i) < wordLen && rep[i] == wordProce... |
python | def GetName(self):
"""
Get the asset name based on its type.
Returns:
str: 'NEO' or 'NEOGas'
"""
if self.AssetType == AssetType.GoverningToken:
return "NEO"
elif self.AssetType == AssetType.UtilityToken:
return "NEOGas"
if typ... |
java | public NumberExpression<Integer> indexOf(Expression<String> str, int i) {
return Expressions.numberOperation(Integer.class, Ops.INDEX_OF_2ARGS, mixin, str, ConstantImpl.create(i));
} |
python | def disable_device(self, token, email=None, user_id=None):
"""
This request manually disable pushes to a device until it comes
online again.
"""
call = "/api/users/disableDevice"
payload ={}
payload["token"] = str(token)
if email is not None:
payload["email"] = str(email)
if user_id is not N... |
python | def extract_hash(hash_fn,
hash_type='sha256',
file_name='',
source='',
source_hash_name=None):
'''
.. versionchanged:: 2016.3.5
Prior to this version, only the ``file_name`` argument was considered
for filename matches in the ha... |
java | public IntStream stream()
{
IntStream.Builder builder = IntStream.builder();
forEach(builder);
return builder.build();
} |
java | @Override
public com.liferay.commerce.product.model.CPOption deleteCPOption(
com.liferay.commerce.product.model.CPOption cpOption)
throws com.liferay.portal.kernel.exception.PortalException {
return _cpOptionLocalService.deleteCPOption(cpOption);
} |
java | private boolean isUniqueFileResolved(final Set<String> alreadyHandled,
final String s) {
return this.uniqueFiles && alreadyHandled.contains(s);
} |
python | def simxSetObjectPosition(clientID, objectHandle, relativeToObjectHandle, position, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
c_position = (ct.c_float*3)(*position)
return c_SetObjectPosition(clientID, objectHandle, relativeToObjec... |
java | public Column set(Option option, boolean set) {
if (set) {
options.add(option);
} else {
options.remove(option);
}
return this;
} |
java | public static String getPropertyNameConvention(Object object, String suffix) {
if (object != null) {
Class<?> type = object.getClass();
if (type.isArray()) {
return getPropertyName(type.getComponentType()) + suffix + "Array";
}
if (object instance... |
java | public static boolean isMultiNamedOutput(JobConf conf, String namedOutput) {
checkNamedOutput(conf, namedOutput, false);
return conf.getBoolean(MO_PREFIX + namedOutput + MULTI, false);
} |
python | def assume(self, cond):
"""
Optimizer hint: assume *cond* is always true.
"""
fn = self.module.declare_intrinsic("llvm.assume")
return self.call(fn, [cond]) |
java | public static String yyyy_MM_dd(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
SimpleDateFormat formatter2 = new SimpleDateFormat(dateFormat);
return format... |
java | public ArrayList<InetAddress> getNaturalEndpoints(RingPosition searchPosition)
{
Token searchToken = searchPosition.getToken();
Token keyToken = TokenMetadata.firstToken(tokenMetadata.sortedTokens(), searchToken);
ArrayList<InetAddress> endpoints = getCachedEndpoints(keyToken);
if (e... |
java | public static final <T> int compare(T o1, T o2, Comparator<T> comp)
{
if (comp != null)
{
return comp.compare(o1, o2);
}
else
{
return ((Comparable<T>)o1).compareTo(o2);
}
} |
python | def _value_tomof(
value, type, indent=0, maxline=MAX_MOF_LINE, line_pos=0, end_space=0,
avoid_splits=False):
# pylint: disable=redefined-builtin
"""
Return a MOF string representing a CIM-typed value (scalar or array).
In case of an array, the array items are separated by comma, but the... |
python | def url_for(self, attr=None, filter_value=None,
service_type=None, endpoint_type="publicURL",
service_name=None, volume_service_name=None):
"""Fetches the public URL from the given service for
a particular endpoint attribute. If none given, returns
the first. See tests fo... |
python | def save_config(self, cmd="save config", confirm=False, confirm_response=""):
"""Save Config"""
return super(ExtremeErsSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) |
java | public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double D) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeatur... |
java | @Bean
@ConditionalOnMissingBean
AutoAssignChecker autoAssignChecker(final TargetFilterQueryManagement targetFilterQueryManagement,
final TargetManagement targetManagement, final DeploymentManagement deploymentManagement,
final PlatformTransactionManager transactionManager) {
retu... |
java | public static void accept(SARLQuickfixProvider provider, Issue issue, IssueResolutionAcceptor acceptor) {
final CapacityReferenceRemoveModification modification = new CapacityReferenceRemoveModification();
modification.setIssue(issue);
modification.setTools(provider);
acceptor.accept(issue,
Messages.SARLQui... |
java | public void setAttribute(ObjectName name, String attrName, Object value) throws Exception {
checkClientConnected();
Attribute attribute = new Attribute(attrName, value);
mbeanConn.setAttribute(name, attribute);
} |
python | def berksfile(self):
"""Return this cookbook's Berksfile instance."""
self.berks_path = os.path.join(self.path, 'Berksfile')
if not self._berksfile:
if not os.path.isfile(self.berks_path):
raise ValueError("No Berksfile found at %s"
% ... |
java | public static Locale localeForString(String localeString) {
if (localeString == null || localeString.isEmpty()) {
return null;
}
Locale locale;
String[] localeParts = localeString.split("_");
switch (localeParts.length) {
case 1:
locale = n... |
python | def list_devices(names=None, continue_from=None, **kwargs):
"""List devices in settings file and print versions"""
if not names:
names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread']
if continue_from:
continue_from = names.index(continue_from)
else:
... |
python | def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto",
ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True):
"""Create the specified flavor."""
try:
nova.flavors.find(name=name)
except (exceptions.NotFound, exceptions.NoUniqueMatch):
... |
python | def build_statusbar(self):
"""construct and return statusbar widget"""
info = {}
cb = self.current_buffer
btype = None
if cb is not None:
info = cb.get_info()
btype = cb.modename
info['buffer_no'] = self.buffers.index(cb)
info['buf... |
java | @Override
public RebuildWorkspacesResult rebuildWorkspaces(RebuildWorkspacesRequest request) {
request = beforeClientExecution(request);
return executeRebuildWorkspaces(request);
} |
python | def _fake_openassociatorinstances(self, namespace, **params):
"""
Implements WBEM server responder for
WBEMConnection.OpenAssociatorInstances
with data from the instance repository.
"""
self._validate_namespace(namespace)
self._validate_open_params(**params)
... |
python | def _update_with_like_args(ctx, _, value):
"""Update arguments with options taken from a currently running VS."""
if value is None:
return
env = ctx.ensure_object(environment.Environment)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, value, 'VS')
like... |
java | private void flushHotCacheSlot(SlotReference slot) {
// Iterate over a copy to avoid concurrent modification issues
for (Map.Entry<DeckReference, TrackMetadata> entry : new HashMap<DeckReference,TrackMetadata>(hotCache).entrySet()) {
if (slot == SlotReference.getSlotReference(entry.getValue(... |
python | def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = TimePicker(self.get_context(), None,
d.style or '@attr/timePickerStyle') |
python | def getstats(self, names, default=numpy.nan):
"""Get the requested stats as a tuple.
If a requested stat is not an attribute (implying it hasn't been
stored), then the default value is returned for that stat.
Parameters
----------
names : list of str
The nam... |
java | public ExpectedCondition<?> clickAndExpectOneOf(final List<ExpectedCondition<?>> conditions) {
dispatcher.beforeClick(this, conditions);
getElement().click();
if (Boolean.parseBoolean(Config.getConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING))) {
logUIAction(UIActions.CLICKED);
... |
java | public static Event constructEvent(String payload, String sigHeader, String secret,
long tolerance) throws SignatureVerificationException {
Event event = ApiResource.GSON.fromJson(payload, Event.class);
Signature.verifyHeader(payload, sigHeader, secret, tolerance);
return event;
} |
java | private static int parseLimits(int i, int end, char[] data, int[] limits) throws PatternSyntaxException {
if (limits.length != LIMITS_LENGTH)
throw new IllegalArgumentException("limits.length=" + limits.length + ", should be " + LIMITS_LENGTH);
limits[LIMITS_PARSE_RESULT_INDEX] = LIMITS_OK;
... |
java | @Override
public FastJsonWriter value( String value ) {
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue(false);
string(value);
return this;
} |
python | def help_center_user_segment_topics(self, user_segment_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/user_segments#list-topics-using-a-user-segment"
api_path = "/api/v2/help_center/user_segments/{user_segment_id}/topics.json"
api_path = api_path.format(user_segment_id=u... |
python | def delete_node(self, loadbalancer, node):
"""Removes the node from its load balancer."""
lb = node.parent
if not lb:
raise exc.UnattachedNode("No parent Load Balancer for this node "
"could be determined.")
resp, body = self.api.method_delete("/loadbalanc... |
java | private static void heapify(int[] arr) {
int n = arr.length;
for (int i = n / 2 - 1; i >= 0; i--)
SortUtils.siftDown(arr, i, n - 1);
} |
python | def alterar(self, id_user_group, name, read, write, edit, remove):
"""Edit user group data from its identifier.
:param id_user_group: User group id.
:param name: User group name.
:param read: If user group has read permission ('S' ou 'N').
:param write: If user group has write p... |
java | @Override
public Request<CreateFpgaImageRequest> getDryRunRequest() {
Request<CreateFpgaImageRequest> request = new CreateFpgaImageRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
java | public void fill_1(byte[] v, int byteoff, int nbits, int bitoff) {
if (nbits < 0) throw new NegativeArraySizeException("nbits < 0: " + nbits);
if (byteoff < 0) throw new IndexOutOfBoundsException("byteoff < 0: "+ byteoff);
if (bitoff < 0) throw new IndexOutOfBoundsException("bitoff < 0: " + bitoff);
... |
python | def get_reviews(self, publisher_name, extension_name, count=None, filter_options=None, before_date=None, after_date=None):
"""GetReviews.
[Preview API] Returns a list of reviews associated with an extension
:param str publisher_name: Name of the publisher who published the extension
:par... |
java | public static <P extends Enum<P>> Point optPoint(final JSONObject json, P e, boolean emptyForNull) {
Point p = optPoint(json, e);
if (p == null && emptyForNull) {
p = new Point();
}
return p;
} |
python | def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True, env=os.environ):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are igno... |
java | public static String createTimestampedFilename(String filenamePrefix,
Date date) {
SimpleDateFormat formatter =
new SimpleDateFormat(FORMAT_JOURNAL_FILENAME_TIMESTAMP);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return f... |
python | def mount_point(cls, file_path):
""" Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points)
"""
mount = None
for mp in cls.mounts():
mp_path = mp.path()
if file_path.startswith(mp_... |
java | @Override
public SQLPPMapping createSQLPreProcessedMapping(ImmutableList<SQLPPTriplesMap> ppMappingAxioms,
MappingMetadata mappingMetadata)
throws DuplicateMappingException {
try {
/**
* Instantiation
*/
... |
python | def read_config(config_fname=None):
"""Parse input configuration file and return a config dict."""
if not config_fname:
config_fname = DEFAULT_CONFIG_FNAME
try:
with open(config_fname, 'r') as config_file:
config = yaml.load(config_file)
except IOError as exc:
if ex... |
python | async def connect(self, *args, **kwargs):
"""Connect to a juju model.
This supports two calling conventions:
The model and (optionally) authentication information can be taken
from the data files created by the Juju CLI. This convention will
be used if a ``model_name`` is spec... |
python | def unescape_sql(inp):
"""
:param inp: an input string to be unescaped
:return: return the unescaped version of the string.
"""
if inp.startswith('"') and inp.endswith('"'):
inp = inp[1:-1]
return inp.replace('""','"').replace('\\\\','\\') |
python | def cmd(send, msg, args):
"""Compiles stuff.
Syntax: {command} <code>
"""
if args['type'] == 'privmsg':
send('GCC is a group exercise!')
return
if 'include' in msg:
send("We're not a terribly inclusive community around here.")
return
if 'import' in msg:
... |
python | def setup(app) -> Dict[str, Any]:
"""
Sets up Sphinx extension.
"""
app.setup_extension("sphinx.ext.graphviz")
app.add_node(
inheritance_diagram,
html=(html_visit_inheritance_diagram, None),
latex=(latex_visit_inheritance_diagram, None),
man=(skip, None),
texi... |
python | def fit(self,y_true_cal=None, y_prob_cal=None):
""" If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_pr... |
python | def energy(self):
"""Calculate state's energy."""
arr = self.src.copy()
arr = self.apply_color(arr, self.state)
scores = [histogram_distance(self.ref[i], arr[i]) for i in range(3)]
# Important: scale by 100 for readability
return sum(scores) * 100 |
python | def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None):
"""GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
... |
python | def folderitems(self):
"""TODO: Refactor to non-classic mode
"""
items = super(ARTemplateAnalysesView, self).folderitems()
self.categories.sort()
return items |
python | def logs(awsclient, function_name, start_dt, end_dt=None, tail=False):
"""Send a ping request to a lambda function.
:param awsclient:
:param function_name:
:param start_dt:
:param end_dt:
:param tail:
:return:
"""
log.debug('Getting cloudwatch logs for: %s', function_name)
log_g... |
python | def servicegroup_server_enable(sg_name, s_name, s_port, **connection_args):
'''
Enable a server:port member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort'
'''
ret = True
server = _servi... |
python | def tokenize(qp_pair, tokenizer=None, is_training=False):
'''
tokenize function.
'''
question_tokens = tokenizer.tokenize(qp_pair['question'])
passage_tokens = tokenizer.tokenize(qp_pair['passage'])
if is_training:
question_tokens = question_tokens[:300]
passage_tokens = passage_... |
python | def addSiInfo(self, msrunContainer, specfiles=None,
attributes=['obsMz', 'rt', 'charge']):
"""Transfer attributes to :class:`Sii` elements from the corresponding
:class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an
attribute is not present in the ``Si`` the attribu... |
python | def cleanup(self):
"""Re-enable paging globally."""
if self.allow_disable_global:
# Return paging state
output_mode_cmd = "set output {}".format(self._output_mode)
enable_paging_commands = ["config system console", output_mode_cmd, "end"]
if self.vdoms:
... |
python | def fill_all_headers(self, req):
"""Set content-type, content-md5, date to the request."""
url = urlsplit(req.url)
content_type, __ = mimetypes.guess_type(url.path)
if content_type is None:
content_type = self.DEFAULT_TYPE
logger.warn("can not determine mime-type... |
java | @Override
protected String doBase(String name, Object value) {
if (value instanceof Boolean) {
return (Boolean) value ? TRUE : FALSE;
} else if (value instanceof String) {
return base(name, (String) value);
}
throw new IndexException("Field '{}' requires a boo... |
java | public void removeCollaborator(String appName, String collaborator) {
connection.execute(new SharingRemove(appName, collaborator), apiKey);
} |
java | protected void writeLink(Header header) throws IOException {
addTabs(2);
writeStart(HtmlTags.LINK);
write(HtmlTags.REL, header.getName());
write(HtmlTags.TYPE, HtmlTags.TEXT_CSS);
write(HtmlTags.REFERENCE, header.getContent());
writeEnd();
} |
python | def _get_hash_object(hash_algo_name):
"""Create a hash object based on given algorithm.
:param hash_algo_name: name of the hashing algorithm.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a hash object based on the given named algorithm.
"""
algorithms = (hashlib.algori... |
java | @Override
public void deliver(WriteStream os, OutHttp2 outHttp)
throws IOException
{
int length = _length;
int flags;
switch (_flags) {
case CONT_STREAM:
flags = 0;
break;
case END_STREAM:
flags = Http2Constants.END_STREAM;
break;
default:
flags = ... |
python | def start():
"""
| Start all the registered entrypoints
| that have been added to `ENTRYPOINTS`.
:rtype: None
"""
pool = gevent.threadpool.ThreadPool(len(ENTRYPOINTS))
for entrypoint, callback, args, kwargs in ENTRYPOINTS:
cname = callback.__name__
#1. Retrieve the class whi... |
python | def parse(readDataInstance):
"""
Returns a new L{ImageBaseRelocationEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to parse as a L{ImageBaseRelocationEntry} object.
@rtype: L{ImageBaseRelocationEntry}
... |
python | def do_get(self, line):
"""get <peer>
eg. get sw1
"""
def f(p, args):
print(p.get())
self._request(line, f) |
java | private static Matrix readSVDLIBCsingularVector(File sigmaMatrixFile)
throws IOException {
BufferedReader br =
new BufferedReader(new FileReader(sigmaMatrixFile));
int dimension = -1;
int valsSeen = 0;
Matrix m = null;
for (String line = null; (line = b... |
python | def BSearch(a, x, lo=0, hi=None):
"""Returns index of x in a, or -1 if x not in a.
Arguments:
a -- ordered numeric sequence
x -- element to search within a
lo -- lowest index to consider in search*
hi -- highest index to consider in search*
*bisect.bisect_left capability t... |
python | def make_grid_transformed(numPix, Mpix2Angle):
"""
returns grid with linear transformation (deltaPix and rotation)
:param numPix: number of Pixels
:param Mpix2Angle: 2-by-2 matrix to mat a pixel to a coordinate
:return: coordinate grid
"""
x_grid, y_grid = make_grid(numPix, deltapix=1)
r... |
python | def ssh(container, cmd='', user='root', password='root'):
'''
SSH into a running container, using the host as a jump host. This requires
the container to have a running sshd process.
Args:
* container: Container name or ID
* cmd='': Command to run in the container
* user='root':... |
python | def is_reserved(self):
"""Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.
"""
reserved_nets = [IPv6Network(u'::/8'), IPv6Network(u'100::/8'),
IPv6... |
java | public static boolean JVMSupportsLargeMappedFiles() {
String arch = System.getProperty("os.arch");
if(arch==null || !arch.contains("64")) {
return false;
}
if(isWindows())
return false;
//TODO better check for 32bit JVM
return true;
} |
java | public void setEventCreatedOn(String eventCreatedOn) {
Long milliseconds = TimeUnit.SECONDS.toMillis(Long.parseLong(eventCreatedOn));
this.eventCreatedOn = new Date(milliseconds);
} |
java | public final void sortCatalogs(final List<TradingCatalog> pCurrentList) {
Collections.sort(pCurrentList, this.cmprCatalogs);
for (TradingCatalog tc : pCurrentList) {
if (tc.getSubcatalogs().size() > 0) {
sortCatalogs(tc.getSubcatalogs());
}
}
} |
java | public static <T> T[] append(final T[] array, final T element) {
Class<?> compType = getClassType(array, element);
if (compType == null) {
return null;
}
int newArrLength = array != null ? array.length + 1 : 1;
@SuppressWarnings("unchecked")
T[] newArray = (T[]) Array.newInstance(compType... |
python | def main():
"""
Create all the argparse-rs and invokes the function from set_defaults().
:return: The result of the function from set_defaults().
"""
parser = argparse.ArgumentParser()
parser.add_argument("--log-level", default="INFO",
choices=logging._nameToLevel,
... |
python | def api_range(
self, serial: str, date: Optional[timelike] = None
) -> SensorRange:
"""Wraps a polygon representing a sensor's range.
By default, returns the current range. Otherwise, you may enter a
specific day (as a string, as an epoch or as a datetime)
"""
if da... |
java | public static MozuUrl updateItemDutyUrl(Double dutyAmount, String orderId, String orderItemId, String responseFields, String updateMode, String version)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/items/{orderItemId}/dutyAmount/{dutyAmount}?updatemode={updateMode}&version={version}&... |
java | public static String getClassType(Class expectedType) {
String classType = expectedType.getName();
if (expectedType.isPrimitive()) {
if (expectedType.equals(Boolean.TYPE)) {
classType = Boolean.class.getName();
}
else if (expectedType.equals(Byte.TYPE)... |
python | def Ceil(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Applies the Ceiling operator to a vertex.
This maps a vertex to the smallest integer greater than or equal to its value
:param input_vertex: the vertex to be ceil'd
"""
return Double(context.jvm... |
java | public static double sumOfSquares(NumberVector v) {
final int dim = v.getDimensionality();
double sum = 0;
for(int d = 0; d < dim; d++) {
double x = v.doubleValue(d);
sum += x * x;
}
return sum;
} |
java | public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
// must be EE M... |
java | public void write(@NonNull Normalizer normalizer, @NonNull File file) throws IOException {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
write(normalizer, out);
}
} |
java | protected void login(final Request request, final Response response)
{
// Login detected
final Form form = new Form(request.getEntity());
final Parameter identifier = form.getFirst(this.getIdentifierFormName());
final Parameter secret = form.getFirst(this.getSecretFormName());
... |
java | public Object invokeOperation(ObjectName name, String operName, String... paramStrings) throws Exception {
String[] paramTypes = lookupParamTypes(name, operName, paramStrings);
Object[] paramObjs;
if (paramStrings.length == 0) {
paramObjs = null;
} else {
paramObjs = new Object[paramStrings.length];
fo... |
java | public static Date addMonths(Date date, int iMonths) {
Calendar dateTime = dateToCalendar(date);
dateTime.add(Calendar.MONTH, iMonths);
return dateTime.getTime();
} |
python | def context_chain(self) -> List['Context']:
"""Return a list of contexts starting from this one, its parent and so on."""
contexts = []
ctx = self # type: Optional[Context]
while ctx is not None:
contexts.append(ctx)
ctx = ctx.parent
return contexts |
java | public Set<Class<? extends GrammaticalRelationAnnotation>> arcLabelsToNode(TreeGraphNode destNode) {
Set<Class<? extends GrammaticalRelationAnnotation>> arcLabels = Generics.newHashSet();
CyclicCoreLabel cl = label();
for (Iterator<Class<?>> it = cl.keySet().iterator(); it.hasNext();) {
Class<? ex... |
python | def agm(x, y, context=None):
"""
Return the arithmetic geometric mean of x and y.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_agm,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) |
java | public OvhSmsBuilder url(String... url) {
for (String u : url) {
if (u != null) {
urls.add(u);
}
}
return this;
} |
python | def is_comment_deleted(comid):
"""
Return True of the comment is deleted. Else False
:param comid: ID of comment to check
"""
query = """SELECT status from "cmtRECORDCOMMENT" WHERE id=%s"""
params = (comid,)
res = run_sql(query, params)
if res and res[0][0] != 'ok':
return True
... |
python | def make_DID(name_type, address, index):
"""
Standard way of making a DID.
name_type is "name" or "subdomain"
"""
if name_type not in ['name', 'subdomain']:
raise ValueError("Require 'name' or 'subdomain' for name_type")
if name_type == 'name':
address = virtualchain.address_ree... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.