language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String getControllerName() {
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
if (sessionMap.containsKey(DART_CONTROLLER_NAME)) {
return (String) sessionMap.get(DART_CONTROLLER_NAME);
}
return null;
} |
java | public ReviewResult parseResults() throws IOException {
ReviewResult result = new ReviewResult();
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(new FileReader(resultFile));
JsonNode issues = rootNode.path("issues");
Iterator<JsonNode> issuesIterato... |
java | public ScalingPolicy withStepAdjustments(StepAdjustment... stepAdjustments) {
if (this.stepAdjustments == null) {
setStepAdjustments(new com.amazonaws.internal.SdkInternalList<StepAdjustment>(stepAdjustments.length));
}
for (StepAdjustment ele : stepAdjustments) {
this.st... |
python | def stop_consuming(self):
"""Tell RabbitMQ that we would like to stop consuming."""
if self._channel:
logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ')
self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) |
java | public static void printUsage(PrintWriter out) {
CliArguments arguments = new CliArguments();
CmdLineParser parser = new CmdLineParser(arguments);
parser.setUsageWidth(120);
parser.printUsage(out, null);
} |
java | public WdrVideoDto parse(String jsUrl) {
WdrVideoDto dto = new WdrVideoDto();
String javascript = urlLoader.executeRequest(jsUrl);
if(javascript.isEmpty()) {
return dto;
}
// URL suchen
String url = getSubstring(javascript, JS_SEARCH_ALT, "\"");
Stri... |
python | def all_network_files():
"""All network files"""
# TODO: list explicitly since some are missing?
network_types = [
'AND-circle',
'MAJ-specialized',
'MAJ-complete',
'iit-3.0-modular'
]
network_sizes = range(5, 8)
network_files = []
for n in network_sizes:
... |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString id_validator = new MPSString();
id_validator.validate(operationType, id, "\"id\"");
MPSBoolean secure_access_only_validator = new MPSBoolean();
secure_access_only_validator.validate(operation... |
python | def from_files(cls, filepaths, specie, step_skip=10, ncores=None,
initial_disp=None, initial_structure=None, **kwargs):
"""
Convenient constructor that takes in a list of vasprun.xml paths to
perform diffusion analysis.
Args:
filepaths ([str]): List of pat... |
python | def factorize(self,A):
"""
Factorizes A.
Parameters
----------
A : matrix
For symmetric systems, should contain only lower diagonal part.
"""
A = coo_matrix(A)
self.mumps.set_centralized_assembled_values(A.data)
self.mumps.run(job=2) |
java | public String getAttributeTextDescription(final ResourceBundle bundle, final String prefix) {
final String bundleKey = prefix == null ? name : (prefix + "." + name);
return bundle.getString(bundleKey);
} |
python | def fetch(self):
"""
Fetch a IpAddressInstance
:returns: Fetched IpAddressInstance
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address.IpAddressInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
... |
java | private Map<String, String> getHttpHeaderStrong() throws Exception {
final OAuthToken token = root.getOAuthTokenManager().getToken();
if (token == null || token.getAccessToken().length() == 0 || token.getTokenType().length() == 0)
throw new Exception ("OAuth token is n... |
python | def _stream(self, char):
"""
Process a character when in the
default 'stream' state.
"""
num = ord(char)
if num in self.basic:
self.dispatch(self.basic[num])
elif num == ctrl.ESC:
self.state = "escape"
elif num == 0x00:
... |
java | public OHLCSeries addSeries(
String seriesName,
int[] xData,
int[] openData,
int[] highData,
int[] lowData,
int[] closeData) {
return addSeries(
seriesName,
Utils.getDoubleArrayFromIntArray(xData),
Utils.getDoubleArrayFromIntArray(openData),
Utils... |
java | public Time getTime(int columnIndex, Calendar cal) throws SQLException {
checkObjectRange(columnIndex);
return row.getInternalTime(columnsInformation[columnIndex - 1], cal, timeZone);
} |
python | def set_properties(self, path, mode):
"""Set file's properties (name and mode).
This function is also in charge of swapping between textual and
binary streams.
"""
self.name = path
self.mode = mode
if 'b' in self.mode:
if not isinstance(self.read_dat... |
python | def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
"""Gather rate limit information from HTTP headers.
The mapping providing the headers is expected to support lowercase
keys. Returns ``None`` if ratelimit info is not found in the headers.
"""
try:
... |
python | async def become(self, layer_type: Type[L], request: 'Request') -> L:
"""
Transform this layer into another layer type
"""
raise ValueError('Cannot become "{}"'.format(layer_type.__name__)) |
java | @Override
public String getString(@NonNull String key) {
if (key == null) { throw new IllegalArgumentException("key cannot be null."); }
final int index = indexForColumnName(key);
return index >= 0 ? getString(index) : null;
} |
java | protected ValidationMessage<Origin> reportMessage(Severity severity, Origin origin,
String messageKey, Object... params) {
ValidationMessage<Origin> message = EntryValidations.createMessage(origin, severity, messageKey, params);
message.getMessage();
// System.out.println("message = " + messag... |
java | public Rational pow(int exponent) {
if (exponent == 0) {
return new Rational(1, 1);
}
BigInteger num = a.pow(Math.abs(exponent));
BigInteger deno = b.pow(Math.abs(exponent));
if (exponent > 0) {
return (new Rational(num, deno));
} else {
... |
python | def update_redirect(self):
"""Update the parent redirect to the current last child.
This method should be called on the parent PID node.
Use this method when the status of a PID changed (ex: draft changed
from RESERVED to REGISTERED)
"""
if self.last_child:
... |
java | public void marshall(DeleteScriptRequest deleteScriptRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteScriptRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteScriptRequest.ge... |
java | public static ImmutableList<ChildNumber> concat(List<ChildNumber> path, List<ChildNumber> path2) {
return ImmutableList.<ChildNumber>builder().addAll(path).addAll(path2).build();
} |
java | public void marshall(DeleteParametersRequest deleteParametersRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteParametersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deletePara... |
java | public boolean contains(T object) {
synchronized (mLock) {
if (mOriginalValues != null) {
return mOriginalValues.contains(object);
} else {
return mObjects.contains(object);
}
}
} |
python | def explode(self, hosts, hostgroups, contactgroups):
"""Loop over all escalation and explode hostsgroups in host
and contactgroups in contacts
Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts
:param hosts: host list to explode
:type hosts: ... |
python | def simple_name_generator(obj):
"""
Simple name_generator designed for HoloViews objects.
Objects are labeled with {group}-{label} for each nested
object, based on a depth-first search. Adjacent objects with
identical representations yield only a single copy of the
representation, to avoid lon... |
python | def tags(self):
"""Returns the tags that should be set on this stack. Includes both the
global tags, as well as any stack specific tags or overrides.
Returns:
dict: dictionary of tags
"""
tags = self.definition.tags or {}
return dict(self.context.tags, **ta... |
python | def transpose(matrix):
"""
transpose 2D matrix (list)
"""
return [[x[i] for x in matrix] for i in range(len(matrix[0]))] |
python | def migrate_cluster(cluster):
"""Called when loading a cluster when it comes from an older version
of elasticluster"""
for old, new in [('_user_key_public', 'user_key_public'),
('_user_key_private', 'user_key_private'),
('_user_key_name', 'user_key_name'),]:
... |
java | private boolean createWorker(boolean isSpare) {
ForkJoinWorkerThreadFactory fac = factory;
Throwable ex = null;
ForkJoinWorkerThread wt = null;
WorkQueue q;
try {
if (fac != null && (wt = fac.newThread(this)) != null) {
if (isSpare && (q = wt.workQueue... |
java | private static void _logCommError(Exception e, HttpURLConnection conn, String url,
String appKey, String method, Map<String, String> params) {
DateFormat df = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
df.setTimeZone(TimeZone.getTimeZone(AlipayConstants... |
python | def open(self):
"""Implementation of NAPALM method open."""
try:
connection = self.transport_class(
host=self.hostname,
username=self.username,
password=self.password,
timeout=self.timeout,
**self.eapi_kwargs
... |
java | public void load(MemoryShortArray shortArray) throws IOException {
if (!_file.exists() || _file.length() == 0) {
return;
}
Chronos c = new Chronos();
DataReader r = IOFactory.createDataReader(_file, _type);
try {
r.open();
r.position(DATA_START_POSITION);
for... |
java | public static List<StackTraceElement> cleanup(StackTraceElement[] stack) {
List<StackTraceElement> elements = new ArrayList<>();
if (stack == null) {
return elements;
} else {
for (StackTraceElement element : stack) {
// Remove all iPOJO calls.
... |
python | def update_changed_requirements():
"""
Checks for changes in the requirements file across an update,
and gets new requirements if changes have occurred.
"""
reqs_path = join(env.proj_path, env.reqs_path)
get_reqs = lambda: run("cat %s" % reqs_path, show=False)
old_reqs = get_reqs() if env.re... |
java | public static final Promise all(Collection<Promise> promises) {
if (promises == null || promises.isEmpty()) {
return Promise.resolve();
}
Promise[] array = new Promise[promises.size()];
promises.toArray(array);
return all(array);
} |
python | def add_boundary_pores(self, labels=['top', 'bottom', 'front', 'back',
'left', 'right'], spacing=None):
r"""
Add pores to the faces of the network for use as boundary pores.
Pores are offset from the faces by 1/2 a lattice spacing such that
they ... |
python | def delete_collection_namespaced_resource_quota(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_resource_quota # noqa: E501
delete collection of ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP r... |
python | def frameify(self, state, data):
"""Yield the data as a single frame."""
try:
yield state.recv_buf + data
except FrameSwitch:
pass
finally:
state.recv_buf = '' |
python | def datetime_to_str(dt='now', no_fractions=False):
"""The Last-Modified data in ISO8601 syntax, Z notation.
The lastmod is stored as unix timestamp which is already
in UTC. At preesent this code will return 6 decimal digits
if any fraction of a second is given. It would perhaps be
better to return ... |
python | def serve(self):
"""Run the server forever."""
# We don't have to trap KeyboardInterrupt or SystemExit here,
# Select the appropriate socket
if isinstance(self.bind_addr, basestring):
# AF_UNIX socket
# So we can reuse the socket...
try: os.unlink(self.bind_addr)
exce... |
python | def get_dropout(x, rate=0.0, init=True):
"""Dropout x with dropout_rate = rate.
Apply zero dropout during init or prediction time.
Args:
x: 4-D Tensor, shape=(NHWC).
rate: Dropout rate.
init: Initialization.
Returns:
x: activations after dropout.
"""
if init or rate == 0:
return x
re... |
java | protected List<String> resolveScalacOptions( CompilerConfiguration configuration )
{
String scalacOptions = configuration.getScalacOptions();
String sourceEncoding = configuration.getSourceEncoding();
List<String> result = new ArrayList<String>( Arrays.asList( parseArgLine( scalacOptions ) )... |
java | public static void main(String args[]) throws Exception {
LaunchAppropriateUI launcher = new LaunchAppropriateUI(args);
launcher.launch();
} |
java | public void print(DocTree tree) throws IOException {
try {
if (tree == null)
print("/*missing*/");
else {
tree.accept(this, null);
}
} catch (UncheckedIOException ex) {
throw new IOException(ex.getMessage(), ex);
}
... |
python | def get_blocks(self, block_structure=None):
"""For a reducible circuit, get a sequence of subblocks that when
concatenated again yield the original circuit. The block structure
given has to be compatible with the circuits actual block structure,
i.e. it can only be more coarse-grained.
... |
java | public final EObject ruleRuleOptions() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
Token otherlv_4=null;
Token otherlv_5=null;
Token otherlv_6=null;
EObject lv_options_0_0 = null;
EObject lv_element_2_0 = null;
enterRul... |
python | def complete(self):
"""https://developers.coinbase.com/api/v2#complete-request-money"""
response = self.api_client._post(self.resource_path, 'complete')
return self.api_client._make_api_object(response, APIObject) |
java | @Override
protected final Principal getPrincipal(final Credentials credentials) {
try {
Optional<Principal> principalOptional = cache.get(credentials.getApiKey(), new Callable<Optional<Principal>>() {
public Optional<Principal> call() throws Exception {
return... |
java | protected double updateEvaluationWindow(int index,int val){
int[] newEnsembleWindows = new int[this.ensembleWindows[index].length];
int wsize = (int)Math.min(this.evaluationSizeOption.getValue(),this.ensembleAges[index]+1);
int sum = 0;
for (int i = 0; i < wsize-1 ; i++){
... |
java | public void simpleGet(String url, Consumer<InputStream> consumer) throws IOException {
simpleGetInternal(url, consumer, null);
} |
python | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... |
java | private static IPAddressStringParameters toMaskOptions(final IPAddressStringParameters validationOptions,
final IPVersion ipVersion) {
//We must provide options that do not allow a mask with wildcards or ranges
IPAddressStringParameters.Builder builder = null;
if(ipVersion == null || ipVersion.isIPv6()) {
I... |
python | def is_orthogonal_nifti(nifti_file):
"""
Validate that volume is orthonormal
:param dicoms: check that we have a volume without skewing
"""
nifti_image = nibabel.load(nifti_file)
affine = nifti_image.affine
transformed_x = numpy.transpose(numpy.dot(affine, [[1], [0], [0], [0]]))[0][:3]
... |
python | def get_user_settings_module(project_root: str):
"""Return project-specific user settings module, if it exists.
:param project_root: Absolute path to project root directory.
A project settings file is a file named `YSETTINGS_FILE` found at the top
level of the project root dir.
Return `None` if p... |
python | def _run_eos_cmds(self, commands, commands_to_log=None):
"""Execute/sends a CAPI (Command API) command to EOS.
In this method, list of commands is appended with prefix and
postfix commands - to make is understandble by EOS.
:param commands : List of command to be executed on EOS.
... |
java | public ServiceFuture<TaskInner> createAsync(String resourceGroupName, String registryName, String taskName, TaskInner taskCreateParameters, final ServiceCallback<TaskInner> serviceCallback) {
return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, registryName, taskName, taskCreatePa... |
python | def _is_valid_channel(self, channel,
conda_url='https://conda.anaconda.org'):
"""Callback for is_valid_channel."""
if channel.startswith('https://') or channel.startswith('http://'):
url = channel
else:
url = "{0}/{1}".format(conda_url, channel)
... |
java | public IntTrie compactToTrieWithRowIndexes() {
PVecToTrieCompactHandler compactor = new PVecToTrieCompactHandler();
compact(compactor);
return compactor.builder.serialize(new DefaultGetFoldedValue(
compactor.builder), new DefaultGetFoldingOffset());
} |
java | private void setupDefaultExecutorServicesIfNecessary() {
if (isPartitioningBehaviorEnabled()) {
if (MapUtils.isEmpty(getDataSourceSpecificExecutors())) {
Set<CobarDataSourceDescriptor> dataSourceDescriptors = getCobarDataSourceService()
.getDataSourceDescrip... |
python | def export(self, nidm_version, export_dir):
"""
Create prov graph.
"""
attributes = [(PROV['type'], NIDM_STATISTIC_MAP),
(DCT['format'], self.fmt)]
if not self.isderfrommap:
attributes.insert(0, (
NIDM_IN_COORDINATE_SPACE, self.... |
python | def dns_log_graph(self, stream):
''' Build up a graph (nodes and edges from a Bro dns.log) '''
dns_log = list(stream)
print 'Entering dns_log_graph...(%d rows)' % len(dns_log)
for row in dns_log:
# Skip '-' hosts
if (row['id.orig_h'] == '-'):
... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.RENDERING_INTENT__RESERVED:
return getReserved();
case AfplibPackage.RENDERING_INTENT__IOCARI:
return getIOCARI();
case AfplibPackage.RENDERING_INTENT__OCRI:
return getOCRI();... |
java | public static DbTypeRegister getRegistry(final Connection connection) throws SQLException {
// if connection URL is null we can't proceed. fail fast
Preconditions.checkNotNull(connection);
final String connectionURL = connection.getMetaData().getURL();
Preconditions.checkNotNull(connec... |
java | TemporalAccessor toResolved(ResolverStyle resolverStyle, Set<TemporalField> resolverFields) {
Parsed parsed = currentParsed();
parsed.chrono = getEffectiveChronology();
parsed.zone = (parsed.zone != null ? parsed.zone : formatter.getZone());
return parsed.resolve(resolverStyle, resolverF... |
python | def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0):
"""
Recursive generator to traverse through the next attribute and \
crawl through the links to be followed.
:param page: The current page being parsed
:param next: The next attribute of the current scraping dict
:pa... |
java | @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
if (msg instanceof CreateStreamCommand) {
createStream((CreateStreamCommand) msg, promise);
} else if (msg instanceof SendGrpcFrameCommand) {
sendGrpcFrame(ctx, (SendGrpcFrameCom... |
java | public boolean isStartedBy(final T element) {
if (element == null) {
return false;
}
return comparator.compare(element, minimum) == 0;
} |
java | @Override
public ListVaultsResult listVaults(ListVaultsRequest request) {
request = beforeClientExecution(request);
return executeListVaults(request);
} |
java | public static <KI, VI, KO, VO> Builder<KI, VI, KO, VO> builder(String name,
TaskInputOutputContext<KI, VI, KO, VO> hadoopContext) {
return new Builder<KI, VI, KO, VO>(name, hadoopContext);
} |
python | def _store_request_line(self, req_line):
"""
Splits the request line given into three components.
Ensures that the version and method are valid for this server,
and uses the urllib.parse function to parse the request URI.
Note:
This method has the additional side eff... |
python | def wrap(obj, wrapper=None, methods_to_add=(), name=None, skip=(), wrap_return_values=False, clear_cache=True):
"""
Wrap module, class, function or another variable recursively
:param Any obj: Object to wrap recursively
:param Optional[Callable] wrapper: Wrapper to wrap functions and methods in (accept... |
python | def _eager_expr_from_flat_schema(flat_schema):
"""
:type flat_schema: dict
"""
result = []
for path, join_method in flat_schema.items():
if join_method == JOINED:
result.append(joinedload(path))
elif join_method == SUBQUERY:
result.append(subqueryload... |
java | protected int getNumAttr() {
int num = element.tree.elemNodeNumAttributes[element.tree.nodeRepID[element.node]];
return num >= 0 ? num : 0;
} |
python | def _check(self):
"""Check if the access token is expired or not."""
import time
if self.expires_in is None or self.authenticated is None:
return False
current = time.time()
expire_time = self.authenticated + self.expires_in
return expire_time > current |
java | public static final void fileDump(String fileName, byte[] data)
{
System.out.println("FILE DUMP");
try
{
FileOutputStream os = new FileOutputStream(fileName);
os.write(data);
os.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
... |
java | @Override
public java.util.concurrent.Future<UpdateApplicationResult> updateApplicationAsync(
com.amazonaws.handlers.AsyncHandler<UpdateApplicationRequest, UpdateApplicationResult> asyncHandler) {
return updateApplicationAsync(new UpdateApplicationRequest(), asyncHandler);
} |
java | public void subscriber(String path,
@Pin ServiceRefAmp serviceRef,
Result<? super Cancel> result)
{
if (path.isEmpty()) {
result.fail(new ServiceException(L.l("Invalid event location '{0}'", path)));
return;
}
String address = address(path);
... |
java | public void setChanged() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setChanged");
changed = true;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setChanged");
} |
java | protected <T> C10NImplementationBinder<T> bind(Class<T> c10nInterface) {
C10NImplementationBinder<T> binder = new C10NImplementationBinder<T>();
binders.put(c10nInterface, binder);
return binder;
} |
java | public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {
QueryStringBuilder builder = new QueryStringBuilder()
.appendParam("limit", limit)
.appendParam("offset", offset);
if (fields.length > 0) {
builder.appendPara... |
java | private void saveDefaultTokens() {
((HierarchicalConfiguration) getConfig()).clearTree(ALL_DEFAULT_TOKENS_KEY);
for (int i = 0, size = defaultTokens.size(); i < size; ++i) {
String elementBaseKey = ALL_DEFAULT_TOKENS_KEY + "(" + i + ").";
HttpSessionToken token = defaultTokens.get(i);
getConfig... |
java | @Override
protected boolean loadMore() throws XMLStreamException
{
WstxInputSource input = mInput;
// Any flattened not-yet-output input to flush?
if (mFlattenWriter != null) {
/* Note: can not trust mInputPtr; may not be correct. End of
* input should be, thoug... |
java | private Status executeNamedBlock(Stmt.NamedBlock stmt, CallStack frame, EnclosingScope scope) {
return executeBlock(stmt.getBlock(),frame,scope);
} |
python | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, memoryview):
... |
java | public static <S extends Node, E extends Event> void installFallback(InputMapTemplate<S, E> imt, S node) {
Nodes.addFallbackInputMap(node, imt.instantiate(node));
} |
java | @Override
public void visitClassContext(final ClassContext classContext) {
JavaClass cls = classContext.getJavaClass();
Field[] flds = cls.getFields();
for (Field f : flds) {
String sig = f.getSignature();
if (sig.startsWith(Values.SIG_QUALIFIED_CLASS_PREFIX)) {
if (sig.startsWith("Ljava/util/") && sig... |
java | @Override
public OpenFileInfo[] iterativeGetOpenFiles(
Path prefix, int millis, String start)
throws IOException{
return dfs.iterativeGetOpenFiles(prefix, millis, start);
} |
java | public FessMessages addErrorsInvalidQueryUnsupportedSortOrder(String property, String arg0) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_invalid_query_unsupported_sort_order, arg0));
return this;
} |
java | public static int inconsistentCompare(MimeType o1, MimeType o2) {
if ((o1 == null) && (o2 == null)) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
int wilchCharComparison = compareByWildCardCount(o1, ... |
python | async def get_next_match(self):
""" Return the first open match found, or if none, the first pending match found
|methcoro|
Raises:
APIException
"""
if self._final_rank is not None:
return None
matches = await self.get_matches(MatchState.open_)... |
python | def init():
""" Initializes this module
"""
global ORG
global LEXER
global MEMORY
global INITS
global AUTORUN_ADDR
global NAMESPACE
ORG = 0 # Origin of CODE
INITS = []
MEMORY = None # Memory for instructions (Will be initialized with a Memory() instance)
AUTORUN_ADDR =... |
java | @SuppressWarnings({"unused", "WeakerAccess"})
public Object getProperty(String name) {
if (!this.config.isPersonalizationEnabled()) return null;
return getLocalDataStore().getProfileProperty(name);
} |
java | public String getPlayingTimeString()
{
long time = getPlayingTime();
long mins = time / 60;
long secs = time % 60;
StringBuilder str = new StringBuilder();
if (mins<10) str.append('0');
str.append(mins).append(':');
if (secs<10) str.append('0');
str.append(secs);
return str.toString();
} |
java | protected void store(HttpServletRequest req, HttpServletResponse resp, String token) {
HttpSession session = req.getSession();
session.setAttribute(ATR_SESSION_TOKEN, token);
} |
python | def validate_unwrap(self, value):
''' Check that ``value`` is valid for unwrapping with ``ComputedField.computed_type``'''
try:
self.computed_type.validate_unwrap(value)
except BadValueException as bve:
self._fail_validation(value, 'Bad value for computed field', cause=bv... |
python | def ordinal(value):
'''
Converts a number to its ordinal representation.
:param value: number
>>> print(ordinal(1))
1st
>>> print(ordinal(11))
11th
>>> print(ordinal(101))
101st
>>> print(ordinal(104))
104th
>>> print(ordinal(113))
113th
>>> print(ordinal(123))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.