language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public List<AssignmentRow> getAssignmentRows(VariableType varType) {
List<AssignmentRow> rows = new ArrayList<AssignmentRow>();
List<Variable> handledVariables = new ArrayList<Variable>();
// Create an AssignmentRow for each Assignment
for (Assignment assignment : assignments) {
... |
java | public void showPreview(int buttonLeft) {
UrlBuilder location = Window.Location.createUrlBuilder();
location.setParameter(CmsGwtConstants.PARAM_DISABLE_DIRECT_EDIT, Boolean.toString(true));
location.setParameter(CmsGwtConstants.PARAM_BUTTON_LEFT, Integer.toString(buttonLeft));
Window.Lo... |
java | public void addHeaderView(View view, int index, ViewGroup.LayoutParams lp) {
mHeader.addView(view, index, lp);
} |
java | public void closeAssociated() throws XAException {
Xid associatedXid = cpoXaStateMap.getXaResourceMap().get(this);
if ( associatedXid != null) {
close(associatedXid);
}
} |
python | def call_later(self, delay, func, *args, **kwargs):
"""
IBatchedTimer API
"""
# "quantize" the delay to the nearest bucket
now = self._get_seconds()
real_time = int(now + delay) * 1000
real_time -= int(real_time % self._bucket_milliseconds)
call = _Batched... |
java | public void saveAsANY(File file, int width, int height, float quality) throws IOException, TranscoderException, TransformerFactoryConfigurationError, TransformerException, ClassNotFoundException {
String extension = FileUtil.getFilenameExtension(file);
if("svg".equals(extension)) {
saveAsSVG(file);
}
... |
java | public Date getFinish()
{
Date result = (Date) getCachedValue(AssignmentField.FINISH);
if (result == null)
{
result = getTask().getFinish();
}
return result;
} |
java | public SwipeBack setSwipeBackView(View view, LayoutParams params) {
mSwipeBackView = view;
mSwipeBackContainer.removeAllViews();
mSwipeBackContainer.addView(view, params);
notifySwipeBackViewCreated(mSwipeBackView);
return this;
} |
java | public void setDescription(String newDescription) {
String oldDescription = description;
description = newDescription;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.SCENARIO__DESCRIPTION, oldDescription, description));
} |
java | private int scan(String string, int i, CharBuffer cb, boolean dash)
throws Exception
{
char ch;
cb.length(0);
int strlen = string.length();
for (; i < strlen; i++) {
if (! Character.isWhitespace(ch = string.charAt(i)) &&
(ch != ':' && (! dash || ch != '-')))
break;
}
... |
python | def rank1d(X, y=None, ax=None, algorithm='shapiro', features=None,
orient='h', show_feature_names=True, **kwargs):
"""Scores each feature with the algorithm and ranks them in a bar plot.
This helper function is a quick wrapper to utilize the Rank1D Visualizer
(Transformer) for one-off analysis.
... |
java | public boolean removeItem(T item) {
int index = mListItems.indexOf(item);
if (index < 0) return false;
mListItems.remove(index);
notifyItemRemoved(index);
return true;
} |
python | def _GetVisitSource(self, visit_identifier, cache, database):
"""Retrieves a visit source type based on the identifier.
Args:
visit_identifier (str): identifier from the visits table for the
particular record.
cache (SQLiteCache): cache which contains cached results from querying
... |
python | def layers(self):
""" gets the layers for the feature service """
if self._layers is None:
self.__init()
self._getLayers()
return self._layers |
python | def console_set_char(
con: tcod.console.Console, x: int, y: int, c: Union[int, str]
) -> None:
"""Change the character at x,y to c, keeping the current colors.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from ... |
python | def append(self, item):
"""
Add an item to the Composite. Item can be a Composite, list etc
"""
if isinstance(item, Composite):
self._content += item.get_content()
elif isinstance(item, list):
self._content += item
elif isinstance(item, dict):
... |
java | private void checkTable() {
// Documentation says that "0 xxx" means data-aging is disabled.
if (m_retentionAge.getValue() == 0) {
m_logger.info("Data aging disabled for table: {}", m_tableDef.getTableName());
return;
}
m_logger.info("Checking expired obj... |
java | public CmsSitemapTreeItem createSitemapItem(CmsClientSitemapEntry entry) {
CmsSitemapTreeItem result = create(entry);
result.clearChildren();
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
CmsSitemapTreeItem childItem = createSitemapItem(child);
if (!entry.i... |
python | def fetch_txs_rpc( self, bitcoind_opts, txids ):
"""
Fetch the given list of transactions
via the JSON-RPC interface.
Return a dict of parsed transactions on success,
keyed by txid.
Return None on error
"""
headers = {'content-type': 'application/json'}... |
python | def stream(queryset_or_adapter, basename=None):
"""Stream a csv file from an object list,
a queryset or an instanciated adapter.
"""
if isinstance(queryset_or_adapter, Adapter):
adapter = queryset_or_adapter
elif isinstance(queryset_or_adapter, (list, tuple)):
if not queryset_or_ada... |
python | def wait_till_stopped(self, conf, container_id, timeout=10, message=None, waiting=True):
"""Wait till a container is stopped"""
stopped = False
inspection = None
for _ in until(timeout=timeout, action=message):
try:
inspection = conf.harpoon.docker_api.inspect... |
python | def _build_command(self, python_executable, lib_dir_fq, proxy_enabled):
"""Build the pip command for installing dependencies.
Args:
python_executable (str): The fully qualified path of the Python executable.
lib_dir_fq (str): The fully qualified path of the lib directory.
... |
python | def git_wrapper(path):
'''
Get appropriate wrapper factory and cache instance for path
'''
path = os.path.abspath(path)
if path not in _wrapper_cache:
if hasattr(Repo, 'commits'):
_wrapper_cache[path] = _GitWrapperLegacy(path)
else:
_wrapper_cache[path] = _Git... |
java | public ServerListenerBuilder addStartedCallbacks(Iterable<Consumer<? super Server>> consumers) {
requireNonNull(consumers, "consumers");
for (Consumer<? super Server> consumer : consumers) {
serverStartedCallbacks.add(requireNonNull(consumer, "consumer"));
}
return this;
... |
python | def help_center_user_votes(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes"
api_path = "/api/v2/help_center/users/{user_id}/votes.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_path, **kwargs) |
python | def log_deprecated(name="", text="", eos=""):
"""
Log deprecation warning.
Args:
name (str): name of the deprecated item.
text (str, optional): information about the deprecation.
eos (str, optional): end of service date such as "YYYY-MM-DD".
"""
assert name or text
if eo... |
python | def getContextsForExpressions(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0):
"""Bulk get contexts for input expressions
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if the fing... |
python | def rejectionOptionsList(self):
"Return a sorted list with the options defined in bikasetup"
plone = getSite()
settings = plone.bika_setup
# RejectionReasons will return something like:
# [{'checkbox': u'on', 'textfield-2': u'b', 'textfield-1': u'c', 'textfield-0': u'a'}]
... |
python | def partition(pred, iterable):
"""Partition an iterable.
Arguments
---------
pred : function
A function that takes an element of the iterable and returns
a boolen indicating to which partition it belongs
iterable : iterable
Returns
-------
A two-tuple ... |
java | public boolean isCompatibleME(SIBUuid8 meUuid, ProtocolVersion version)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "isCompatibleME", new Object[] {meUuid});
boolean result = false;
MPConnection conn = findMPConnection(meUuid);
if (conn!=null)
... |
java | @Override
public Dialect createCustomDialect(KamInfo kamInfo,
List<Namespace> geneNamespaces, List<Namespace> bpNamespaces,
List<Namespace> chemicalNamespaces, BELSyntax form,
boolean removeNamespacePrefix) throws KAMStoreException {
// cache all namespaces of the kam by... |
python | def authorization_header_parameters(self):
"""
The parameters from the Authorization header (only). If the
Authorization header is not present or is not an AWS SigV4 header, an
AttributeError exception is raised.
"""
result = getattr(self, "_authorization_header_paramete... |
java | public List<VirtualFile> getChildren(VirtualFileFilter filter) throws IOException {
// isDirectory does the read security check
if (!isDirectory()) { return Collections.emptyList(); }
if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }
FilterVirtualFileVisitor visitor = ... |
java | public static long[] reductionShape(INDArray x, int[] dimension, boolean newFormat, boolean keepDims){
boolean wholeArray = Shape.wholeArrayDimension(dimension) || dimension.length == x.rank();
long[] retShape;
if(!newFormat) {
retShape = wholeArray ? new long[] {1, 1} : ArrayUtil.re... |
java | protected final void requestCheckpoint(boolean persistent)
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"requestCheckpoint",
new O... |
python | def delete_port_channel(self, nexus_host, vpc_nbr):
"""Deletes delete port channel on Nexus switch."""
starttime = time.time()
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_DEL_PORT_CH % (vpc_nbr)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.captur... |
python | def add_platforms(in_wheel, platforms, out_path=None, clobber=False):
""" Add platform tags `platforms` to `in_wheel` filename and WHEEL tags
Add any platform tags in `platforms` that are missing from `in_wheel`
filename.
Add any platform tags in `platforms` that are missing from `in_wheel`
``WHEE... |
python | def _fetch_socket_data(self, parsed_url):
''' Hit a given stats socket and return the stats lines '''
self.log.debug("Fetching haproxy stats from socket: %s" % parsed_url.geturl())
if parsed_url.scheme == 'tcp':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s... |
java | @Override
public Object inject(Class Klass, boolean doPostConstruct, ExternalContext eContext) throws InjectionProviderException {
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINE, CLASS_NAME,
"inject(Cla... |
java | public static String getHeaderUserAgent(@Nullable String clientAppName,
@NonNull String osName,
@NonNull String osVersion,
@NonNull String osArch) {
osName = osName.replaceAll(ONLY_PRINTAB... |
java | public static boolean async(InvocationContext context) {
return !isDetached(context, Async.class) &&
(context.getRequest().isAnnotationPresent(Async.class) ||
(context.getEndpoint().isAnnotationPresent(Async.class)));
} |
python | def serialize(objects=None):
"""A simple wrapper of Django's serializer with defaults
for JSON and natural keys.
Note: use_natural_primary_keys is False as once
a pk is set, it should not be changed throughout the
distributed data.
"""
return serializers.serialize(
"json",
... |
java | public Enumeration<String> getElements() {
AttributeNameEnumeration elements = new AttributeNameEnumeration();
elements.addElement(VERSION);
return (elements.elements());
} |
java | public static RecurrenceIterator createRecurrenceIterator(Recurrence recurrence, ICalDate start, TimeZone timezone) {
DateValue startValue = convert(start, timezone);
return RecurrenceIteratorFactory.createRecurrenceIterator(recurrence, startValue, timezone);
} |
java | @SuppressWarnings( "PMD.CollapsibleIfStatements" )
private <V extends FileAttributeView> V addIsLinkIfPossible( Class<V> type, V fav ) {
if( BasicFileAttributeView.class.isAssignableFrom( type ) ) {
if( (! v( () -> BasicFileAttributeView.class.cast( fav ).readAttributes()).isSymbolicLink() )) {
... |
python | def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = self.getFile(file_id)
try:
d = dest if _isfile(dest) else open(dest, 'wb')
r = api.download((self._token, f['file_path']),... |
java | public static void main(String[] args) {
ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);
Props props = entryPoint.getProps();
new CeProcessLogging().configure(props);
CeServer server = new CeServer(
new ComputeEngineImpl(props, new ComputeEngineContainerImpl()),
ne... |
java | public static List<CPAttachmentFileEntry> findByLtD_S(Date displayDate,
int status) {
return getPersistence().findByLtD_S(displayDate, status);
} |
java | public static void installDefaultRegistry(@NonNull final DefaultResolverRegistry registry) {
/*
* register built-in cards & mCells
*/
MVHelper mvHelper = new MVHelper(new MVResolver());
registry.setMVHelper(mvHelper);
// built-in mCells
registry.reg... |
java | private Date seasonalDateFromIcs(String icsFileName, String eventSummary, int year) {
Map<Integer, Date> dates = getDatesFromIcs(icsFileName, eventSummary, year, year);
return dates.get(year - (eventSummary.equals(Holiday.NEW_YEARS_EVE.getSummary()) ? 1 : 0));
} |
python | def simxGetUIButtonProperty(clientID, uiHandle, uiButtonID, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
prop = ct.c_int()
return c_GetUIButtonProperty(clientID, uiHandle, uiButtonID, ct.byref(prop), operationMode), prop.value |
java | public boolean saveList(boolean fast) {
try {
InsertManyOptions ops = new InsertManyOptions();
if (fast) {
ops.ordered(false);
}
MongoKit.INSTANCE.insert(collectionName, documents, ops);
documents.clear();
return true;
... |
python | def get_proteins_for_peptide(self, psm_id):
"""Returns list of proteins for a passed psm_id"""
protsql = self.get_sql_select(['protein_acc'], 'protein_psm')
protsql = '{0} WHERE psm_id=?'.format(protsql)
cursor = self.get_cursor()
proteins = cursor.execute(protsql, psm_id).fetcha... |
python | def nodeAt( self, point ):
"""
Returns the node at the inputed positions.
:return <XNode>
"""
items = self.items(point)
for item in items:
if ( isinstance(item, XNode) ):
return item
return None |
java | private void initActionButtonAttrs(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ActionButton,
defStyleAttr, defStyleRes);
try {
initType(attributes);
initSize(attributes);
initButtonColor(a... |
python | def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'):
""" Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """
path = find_data_path(path) or path
if os.path.isdir(path):
paths = os.listdir(path)
paths = [os.path.join(path, p) for p in paths]
e... |
java | @Override
public Object invoke(final ELContext context, final Object base, final Object method,
Class<?>[] paramTypes, final Object[] params) {
if ((base == null) || (method == null)) {
return null;
}
final MethodDescriptor[] methodDescriptors = getMethodDescriptors(context, base);
if (m... |
java | public AbstractColumnFamilyTemplate<K,N> addColumn(N columnName, Serializer<?> valueSerializer) {
columnValueSerializers.put(columnName, valueSerializer);
activeSlicePredicate.addColumnName(columnName);
return this;
} |
java | static byte[] marshallIDL4(final AttributeValue_4 attributeValue) throws DevFailed {
XLOGGER.entry();
final CDROutputStream os = new CDROutputStream();
try {
AttributeValue_4Helper.write(os, attributeValue);
XLOGGER.exit();
return cppAlignment(os.getBufferCopy... |
python | def strainer(self):
"""
Determine whether it is required to run the MLST analyses
"""
# Initialise a variable to store whether the analyses need to be performed
analyse = list()
for sample in self.runmetadata.samples:
if sample.general.bestassemblyfile != 'NA'... |
python | def modify_key_parity(key):
"""
The prior use of the function is to return the parity-validated key.
The incoming key is expected to be hex data binary representation, e.g. b'E7A3C8B1'
"""
validated_key = b''
for byte in key:
if parityOf(int(byte)) == -1:
byte_candidate = in... |
python | def cross(v, w):
"""
cross product of two vectors
"""
x = v[1] * w[2] - v[2] * w[1]
y = v[2] * w[0] - v[0] * w[2]
z = v[0] * w[1] - v[1] * w[0]
return [x, y, z] |
java | protected void cleanupConnection(Conversation conversation) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "cleanupConnection", conversation);
ConversationState convState = (ConversationState) conversation.getAttachment();
ServerSideConnecti... |
python | def display_page(self):
"""
Returns the current page the paginator interface is on.
"""
self._display_page = max(0, min(self.page_count - 1, self._display_page))
return self._display_page |
python | def register_package(pkg):
"""
Allow to register packages by loading and exposing: templates, static,
and exceptions for abort()
Structure of package
root
| $package_name
| __init__.py
|
| exceptions.py
|
... |
python | def get_labels_and_texts(self, metadata=None):
'''
Parameters
----------
metadata : (array like or None)
Returns
-------
{'labels':[], 'texts': []} or {'labels':[], 'texts': [], 'meta': []}
'''
to_ret = {'categories': self._corpus.get_categories(), 'labels': [], 'texts': []}
labels = self._corpus._... |
java | public String getDecodedPath() {
if (_decodedPath == null && _path != null)
_decodedPath = URIUtils.decodePath(_path);
return _decodedPath;
} |
java | protected void computeINFLO(Relation<O> relation, ModifiableDBIDs pruned, KNNQuery<O> knnq, WritableDataStore<ModifiableDBIDs> rNNminuskNNs, WritableDoubleDataStore inflos, DoubleMinMax inflominmax) {
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing INFLOs", relation.size(), LOG) : null;
Ha... |
java | public boolean removeUserFromTeam(final UserPrincipal user, final Team team) {
final List<Team> teams = user.getTeams();
if (teams == null) {
return false;
}
boolean found = false;
for (final Team t: teams) {
if (team.getUuid().equals(t.getUuid())) {
... |
python | def compute(mechanism, subsystem, purviews, cause_purviews,
effect_purviews):
"""Compute a |Concept| for a mechanism, in this |Subsystem| with the
provided purviews.
"""
concept = subsystem.concept(mechanism,
purviews=purviews,
... |
java | public void writeExcelFile() throws IOException, WriteException {
WritableWorkbook excelWrkBook = null;
int curDsPointer = 0;
try {
final String[] columnNames = ds.getColumns();
final List<String> exportOnlyColumnsList = getExportOnlyColumns() != null ? Arrays.asLi... |
java | public KamInfo getKamInfoById(final int id) throws SQLException {
KamInfo kamInfo = null;
ResultSet rset = null;
try {
PreparedStatement ps = getPreparedStatement(SELECT_KAM_BY_ID_SQL);
ps.setInt(1, id);
rset = ps.executeQuery();
if (rset.next()... |
python | def profile(ctx, filepath, calltree=False):
""" Run and profile a given Python script.
:param str filepath: The filepath of the script to profile
"""
filepath = pathlib.Path(filepath)
if not filepath.is_file():
report.error(ctx, "profile", f"no such script {filepath!s}")
else:
... |
java | public void marshall(GetActiveNamesRequest getActiveNamesRequest, ProtocolMarshaller protocolMarshaller) {
if (getActiveNamesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getActiveNamesRe... |
python | def _peek_async_request(self, msg_id, msg_name):
"""Peek at the set of callbacks for a request.
Return tuple of Nones if callbacks don't exist.
"""
assert get_thread_ident() == self.ioloop_thread_id
if msg_id is None:
msg_id = self._msg_id_for_name(msg_name)
... |
java | public WindowedStream<T, KEY, TimeWindow> timeWindow(Time size, Time slide) {
if (environment.getStreamTimeCharacteristic() == TimeCharacteristic.ProcessingTime) {
return window(SlidingProcessingTimeWindows.of(size, slide));
} else {
return window(SlidingEventTimeWindows.of(size, slide));
}
} |
java | public ServiceFuture<BackupShortTermRetentionPolicyInner> updateAsync(String resourceGroupName, String serverName, String databaseName, Integer retentionDays, final ServiceCallback<BackupShortTermRetentionPolicyInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGr... |
python | def _run(self, command: List[str], notebook: Optional[str] = None) -> int:
"""Run command from terminal and notebook and view output from subprocess."""
if notebook is None:
return Popen(command, cwd=self._build_dir).wait()
cmd = Popen(command, cwd=self._build_dir, stdout=PIPE, stder... |
java | protected String getSecureBaseUrl(String siteUrl) {
if(!siteUrl.startsWith("http://") && !siteUrl.startsWith("https://")) {
siteUrl = "http://" + siteUrl;
}
Matcher urlMatcher = URL_PATTERN.matcher(siteUrl);
if(urlMatcher.matches()) {
logger.debug("Url matches [{}]", siteUrl);
boolean ... |
python | def register_account():
"""
Agree to LE TOS
"""
LOGGER.info("Registering account...")
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", {
"resource": "new-reg",
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
})
if code == 201... |
python | def min_depth_img(self, num_img=1):
"""Collect a series of depth images and return the min of the set.
Parameters
----------
num_img : int
The number of consecutive frames to process.
Returns
-------
:obj:`DepthImage`
The min DepthImage c... |
python | def remove_all_callbacks(self):
""" Removes all registered callbacks."""
for cb_id in list(self._next_tick_callback_removers.keys()):
self.remove_next_tick_callback(cb_id)
for cb_id in list(self._timeout_callback_removers.keys()):
self.remove_timeout_callback(cb_id)
... |
java | private void rewriteReturns(Node fnNode) {
checkState(fnNode.isFunction());
final Node body = fnNode.getLastChild();
NodeUtil.visitPostOrder(
body,
new NodeUtil.Visitor() {
@Override
public void visit(Node n) {
if (n.isReturn() && n.hasOneChild()) {
Node res... |
java | public void stop() {
if (accelerometer != null) {
queue.clear();
sensorManager.unregisterListener(this, accelerometer);
sensorManager = null;
accelerometer = null;
}
} |
python | def convert_to_geoff(discoursegraph):
"""
Parameters
----------
discoursegraph : DiscourseDocumentGraph
the discourse document graph to be converted into GEOFF format
Returns
-------
geoff : string
a geoff string representation of the discourse graph.
"""
dg_copy = d... |
java | private void add(final long[] triple, final long value) throws IOException {
final int chunk = (int)(triple[0] >>> DISK_CHUNKS_SHIFT);
count[chunk]++;
checkedForDuplicates = false;
if (DEBUG) System.err.println("Adding " + Arrays.toString(triple));
writeLong(triple[0], byteBuffer[chunk], writableByteChannel[c... |
java | public void writeContent(final OutputStream result) throws IOException
{
result.write(PARAGRAPH_DEFAULTS);
result.write(PLAIN);
if(inTable) {
result.write(IN_TABLE);
}
if(this.lineLeading > 0) {
result.write(LINE_SPACING);
result.write(intT... |
java | private final static HttpServletRequest createServletRequest(final HttpServletRequest req, final String translatedPath) {
return new HttpServletRequestWrapper(req){
@Override
public String getServletPath() {
return translatedPath;
}
};
} |
python | def _export_to_exporter(network, exporter, basename, export_standard_types=False):
"""
Export to exporter.
Both static and series attributes of components are exported, but only
if they have non-default values.
Parameters
----------
exporter : Exporter
Initialized exporter instance... |
java | public void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, WebAppSecurityConfig webAppSecConfig) {
ReferrerURLCookieHandler referrerURLCookieHandler = getCookieHandler();
referrerURLCookieHandler.clearReferrerURLCookie(request, response, cookieName);
C... |
java | public void onBeforeWriteResponseBody(HttpServletRequest request, XHttpServletResponse response) {
if (!isEligibleToExpirationHeaderGeneration(request, response)) {
return;
}
Date expirationDate = getExpirationDate(request, response);
if (expirationDate == null) {
... |
java | @Override
public boolean parseManagementInterfaces(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> operationsList)
throws XMLStreamException {
requireNoAttributes(reader);
boolean interfaceDefined = false;
while (reader.hasNext() && reader.nextTag() != END_ELE... |
python | def _vpcs_path(self):
"""
Returns the VPCS executable path.
:returns: path to VPCS
"""
search_path = self._manager.config.get_section_config("VPCS").get("vpcs_path", "vpcs")
path = shutil.which(search_path)
# shutil.which return None if the path doesn't exists
... |
python | def _validate_services(services, machines, add_error):
"""Validate each service within the bundle.
Receive the services and machines sections of the bundle.
Use the given add_error callable to register validation error.
"""
machine_ids = set()
for service_name, service in services.items():
... |
java | private void setFormat() {
if(getMinorTickSpacing() == (int) getMinorTickSpacing()){
format = "%.0f";
} else {
// BigDecimal dec = new BigDecimal(getMinorTickSpacing());
// String s = String.valueOf(getMinorTickSpacing());
// int precision = s.substring(s.lastIndexOf('.')+1).length();
// fo... |
python | def multivariate_multiply(m1, c1, m2, c2):
"""
Multiplies the two multivariate Gaussians together and returns the
results as the tuple (mean, covariance).
Examples
--------
.. code-block:: Python
m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
... |
python | def realpred(cls, lemma, pos, sense=None):
"""Instantiate a Pred from its components."""
string_tokens = [lemma]
if pos is not None:
string_tokens.append(pos)
if sense is not None:
sense = str(sense)
string_tokens.append(sense)
predstr = '_'.jo... |
java | public void marshall(DeregisterScalableTargetRequest deregisterScalableTargetRequest, ProtocolMarshaller protocolMarshaller) {
if (deregisterScalableTargetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarsha... |
java | public void marshall(Scte35TimeSignalScheduleActionSettings scte35TimeSignalScheduleActionSettings, ProtocolMarshaller protocolMarshaller) {
if (scte35TimeSignalScheduleActionSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
... |
python | def cast2theano_var(self, array_like, name=None):
'''Cast `numpy.ndarray` into `theano.tensor` keeping `dtype` and `ndim`
compatible
'''
# extract the information of the input value
array = np.asarray(array_like)
args = (name, array.dtype)
ndim = array.ndim
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.