language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def path(self):
"""URL path for change set APIs.
:rtype: str
:returns: the path based on project, zone, and change set names.
"""
return "/projects/%s/managedZones/%s/changes/%s" % (
self.zone.project,
self.zone.name,
self.name,
) |
python | def _collect_fields(self):
'''
Collects all the attributes that are instance of
:class:`incoming.datatypes.Types`. These attributes are used for
defining rules of validation for every field/key in the incoming JSON
payload.
:returns: a tuple of attribute names from an in... |
python | def process_extensions(
headers: Headers,
available_extensions: Optional[Sequence[ClientExtensionFactory]],
) -> List[Extension]:
"""
Handle the Sec-WebSocket-Extensions HTTP response header.
Check that each extension is supported, as well as its parameters.
Return ... |
python | def iteritems(self):
"""
Iterate through the property names and values of this CIM instance.
Each iteration item is a tuple of the property name (in the original
lexical case) and the property value.
The order of properties is preserved.
"""
for key, val in self... |
java | @Override
public RTMPConnection getConnection(int clientId) {
log.trace("Getting connection by client id: {}", clientId);
for (RTMPConnection conn : connMap.values()) {
if (conn.getId() == clientId) {
return connMap.get(conn.getSessionId());
}
}
... |
python | def verify(self, **kwargs):
"""Authorization Request parameters that are OPTIONAL in the OAuth 2.0
specification MAY be included in the OpenID Request Object without also
passing them as OAuth 2.0 Authorization Request parameters, with one
exception: The scope parameter MUST always be pr... |
java | public static String mergeToSingleUnderscore(String s) {
StringBuffer buffer = new StringBuffer();
boolean inMerge = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ' || c == '_') {
if (!inMerge) {
buffer.... |
java | public List<NodeTypeData> getAllNodeTypes()
{
try
{
return this.nodeTypeRepository.getAllNodeTypes();
}
catch (RepositoryException e)
{
LOG.error(e.getLocalizedMessage());
}
return new ArrayList<NodeTypeData>();
} |
java | @Override public void init(ProcessingEnvironment procEnv) {
super.init(procEnv);
if (System.getProperty("lombok.disable") != null) {
lombokDisabled = true;
return;
}
this.processingEnv = procEnv;
this.javacProcessingEnv = getJavacProcessingEnvironment(procEnv);
this.javacFiler = getJavacFiler(procEnv... |
java | public void setFQNType(Integer newFQNType) {
Integer oldFQNType = fqnType;
fqnType = newFQNType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FULLY_QUALIFIED_NAME__FQN_TYPE, oldFQNType, fqnType));
} |
python | def datetime_from_timestamp(n, epoch=datetime.datetime.fromordinal(693594)):
"""Return datetime object from timestamp in Excel serial format.
Examples
--------
>>> datetime_from_timestamp(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
"""
return epoch + datetime.time... |
python | def check_valid(line0, line1):
"""
Check :func:`word_embedding_loader.loader.glove.check_valid` for the API.
"""
data0 = line0.split(b' ')
if len(data0) != 2:
return False
# check if data0 is int values
try:
map(int, data0)
_parse_line(line1, float)
except:
... |
python | def delete_version(self, version_id=None):
"""
Deletes this draft version (revert to published)
:raises NotAllowed: if this version is already published.
:raises Conflict: if this version is already deleted.
"""
if not version_id:
version_id = self.version.id... |
python | def write_input(self, atoms=None, properties=['energy'], system_changes=all_changes):
'''Write input file(s).'''
with work_dir(self.directory):
self.calc.write_input(self, atoms, properties, system_changes)
self.write_pbs_in(properties)
subprocess.call(self.copy_out_c... |
python | def get_bytes(self, *args, **kwargs):
""" no string decoding performed """
return super(XClient, self).get(*args, **kwargs) |
python | def run(self, args):
"""
Lists project names.
:param args Namespace arguments parsed from the command line
"""
long_format = args.long_format
# project_name and auth_role args are mutually exclusive
if args.project_name or args.project_id:
project = se... |
python | def get_dates_in_range(start_date, end_date):
""" Get all dates within input start and end date in ISO 8601 format
:param start_date: start date in ISO 8601 format
:type start_date: str
:param end_date: end date in ISO 8601 format
:type end_date: str
:return: list of dates between start_date an... |
java | private float[] generateParticleTimeStamps(float totalTime)
{
float timeStamps[] = new float[mEmitRate * 2];
if ( burstMode ) {
for (int i = 0; i < mEmitRate * 2; i += 2) {
timeStamps[i] = totalTime;
timeStamps[i + 1] = 0;
}
}
... |
java | public synchronized void add(Resource subject, URI predicate, Value object, Resource... contexts) throws MarkLogicSesameException {
cache.add(subject,predicate,object,contexts);
if( cache.size() > cacheSize - 1){
forceRun();
}
} |
java | public List<DynamoDBMapper.FailedBatch> batchDelete(Iterable<T> objectsToDelete) {
return mapper.batchWrite((Iterable<T>)Collections.<T>emptyList(), objectsToDelete);
} |
python | def _process_block_arch_specific(self, addr, irsb, func_addr): # pylint: disable=unused-argument
"""
According to arch types ['ARMEL', 'ARMHF', 'MIPS32'] does different
fixes
For ARM deals with link register on the stack
(see _arm_track_lr_on_stack)
For MIPS32 simulates... |
java | private <T> void publishToCacheWriter(Consumer<T> action, Supplier<T> data) {
if (!configuration.isWriteThrough()) {
return;
}
try {
action.accept(data.get());
} catch (CacheWriterException e) {
throw e;
} catch (RuntimeException e) {
throw new CacheWriterException("Exception... |
python | def go():
"""Make the magic happen."""
parser = argparse.ArgumentParser(prog='PROG', epilog=help_epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-V', '--version', action='store_true',
help="show version and info ... |
java | public static Protos.Resource scalar(String name, String role, double value) {
checkNotNull(name);
checkNotNull(role);
checkNotNull(value);
return Protos.Resource.newBuilder()
.setName(name)
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(value))
.setRole(role... |
java | public ApiResponse<Info> versionInfoWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = versionInfoValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<Info>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} |
python | def decompress(chunks, compression):
"""Decompress
:param __generator[bytes] chunks: compressed body chunks.
:param str compression: compression constant.
:rtype: __generator[bytes]
:return: decompressed chunks.
:raise: TypeError, DecompressError
"""
if compression not in SUPPORTED_C... |
java | public List iterateObjectsToList() {
List result = new ArrayList();
Iterator iterator = iterateObjects();
for (; iterator.hasNext(); ) {
result.add(iterator.next());
}
return result;
} |
java | private static File getFax4jInternalTemporaryDirectoryImpl()
{
File temporaryFile=null;
try
{
//create temporary file
temporaryFile=File.createTempFile("temp_",".temp");
}
catch(IOException exception)
{
throw new FaxException("Unabl... |
java | private void tryStartingKbMode(int keyCode) {
if (mTimePicker.trySettingInputEnabled(false) &&
(keyCode == -1 || addKeyIfLegal(keyCode))) {
mInKbMode = true;
mDoneButton.setEnabled(false);
updateDisplay(false);
}
} |
java | public void marshall(Layer layer, ProtocolMarshaller protocolMarshaller) {
if (layer == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(layer.getLayerDigest(), LAYERDIGEST_BINDING);
protoc... |
python | def moveToNextRow(vs, func, reverse=False):
'Move cursor to next (prev if reverse) row for which func returns True. Returns False if no row meets the criteria.'
rng = range(vs.cursorRowIndex-1, -1, -1) if reverse else range(vs.cursorRowIndex+1, vs.nRows)
for i in rng:
try:
if func(vs.r... |
python | def GetPlaylists(self, start, max_count, order, reversed):
"""Gets a set of playlists.
:param int start: The index of the first playlist to be fetched
(according to the ordering).
:param int max_count: The maximum number of playlists to fetch.
:param str order... |
python | def getUserSid(username):
'''
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy
'''
if six.PY2:
username = _t... |
java | protected void configureSession(Session session) {
if(! session.getProperties().contains(MAIL_SMTP_ALLOW8BITMIME)) {
session.getProperties().put(MAIL_SMTP_ALLOW8BITMIME, "true");
}
} |
java | private static ImmutableList<Node> paramNamesOf(Node paramList) {
checkArgument(paramList.isParamList(), paramList);
ImmutableList.Builder<Node> builder = ImmutableList.builder();
paramNamesOf(paramList, builder);
return builder.build();
} |
python | def labels(self, nodeids=None):
"""
Return the list of labels for *nodeids*, or all labels.
Args:
nodeids: an iterable of nodeids for predications to get
labels from; if `None`, return labels for all
predications
Note:
This returns... |
python | def user_exists(name, runas=None):
'''
Return whether the user exists based on rabbitmqctl list_users.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.user_exists rabbit_user
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
... |
java | public final AntlrDatatypeRuleToken ruleValidID() throws RecognitionException {
AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken();
Token this_ID_0=null;
Token kw=null;
enterRule();
try {
// InternalXtext.g:2138:2: ( (this_ID_0= RULE_ID | kw= 'true' | ... |
java | @Override
public List<WSStepThreadExecutionAggregate> getStepExecutionAggregatesFromJobExecutionId(
long jobExecutionId) throws NoSuchJobExecutionException {
// Optimize for programming ease rather than a single tri... |
java | private static void appendKeyValue(StringBuffer str, String key, String value) {
str.append(key);
if (value == IS_USED) {
str.append(";");
} else {
str.append("=(");
str.append(value);
str.append(");");
}
} |
java | private static void attemptRetryOnException(String logPrefix, Request<?> request,
JusError exception) throws JusError {
RetryPolicy retryPolicy = request.getRetryPolicy();
if (retryPolicy == null) {
throw exception;
}
try {
... |
python | def delete_policy_version(policy_name, version_id,
region=None, key=None, keyid=None, profile=None):
'''
Delete a policy version.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_policy_version mypolicy v1
'''
conn = _get_conn(region=region, key=key, k... |
python | def load(self, carddict):
"""
Takes a carddict as produced by ``Card.save`` and sets this card
instances information to the previously saved cards information.
"""
self.code = carddict["code"]
if isinstance(self.code, text_type):
self.code = eval(self.code)
... |
java | public static MethodNode addDelegateInstanceMethod(ClassNode classNode, Expression delegate, MethodNode declaredMethod, AnnotationNode markerAnnotation, boolean thisAsFirstArgument, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) {
Parameter[] parameterTypes = thisAsFirstArgument ? getRemainin... |
python | def add_patch(ax, color, pts_per_edge, *edges):
"""Add a polygonal surface patch to a plot.
Args:
ax (matplotlib.artist.Artist): A matplotlib axis.
color (Tuple[float, float, float]): Color as RGB profile.
pts_per_edge (int): Number of points to use in polygonal
approximatio... |
java | public static Message.Builder addDefaultInstanceToRepeatedField(final Descriptors.FieldDescriptor repeatedFieldDescriptor, final Message.Builder builder) throws CouldNotPerformException {
if (repeatedFieldDescriptor == null) {
throw new NotAvailableException("repeatedFieldDescriptor");
}
... |
python | def maxwellian(E: np.ndarray, E0: np.ndarray, Q0: np.ndarray) -> Tuple[np.ndarray, float]:
"""
input:
------
E: 1-D vector of energy bins [eV]
E0: characteristic energy (scalar or vector) [eV]
Q0: flux coefficient (scalar or vector) (to yield overall flux Q)
output:
-------
Phi: dif... |
python | def get_tu(source, lang='c', all_warnings=False, flags=None):
"""Obtain a translation unit from source and language.
By default, the translation unit is created from source file "t.<ext>"
where <ext> is the default file extension for the specified language. By
default it is C, so "t.c" is the default f... |
python | def p_const_vector_elem_list_list(p):
""" const_number_list : const_number_list COMMA expr
"""
if p[1] is None or p[3] is None:
return
if not is_static(p[3]):
if isinstance(p[3], symbols.UNARY):
tmp = make_constexpr(p.lineno(2), p[3])
else:
api.errmsg.syn... |
python | def localize(self, name, **kwargs):
"""Find the best-fit position of a source. Localization is
performed in two steps. First a TS map is computed centered
on the source with half-width set by ``dtheta_max``. A fit is
then performed to the maximum TS peak in this map. The source
... |
java | private Transactional readAnnotation(MethodInvocation invocation)
{
final Method method = invocation.getMethod();
if (method.isAnnotationPresent(Transactional.class))
{
return method.getAnnotation(Transactional.class);
}
else
{
throw new RuntimeException("Could not find Transactional annotation");
... |
java | private Long performCommit(JPACommit commit) throws EDBException {
synchronized (entityManager) {
long timestamp = System.currentTimeMillis();
try {
beginTransaction();
persistCommitChanges(commit, timestamp);
commitTransaction();
... |
python | def clean(self):
""" Removes any Units that are not applicable given the current semantic or phonetic category.
Modifies:
- self.unit_list: Removes Units from this list that do not fit into the clustering category.
it does by by either combining units to make compound words,... |
python | def get_brain(brain_or_object):
"""Return a ZCatalog brain for the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: True if the object is a catalog brain
:rtype: bool
"""
if is_brain(brai... |
java | public static void printStackTrace(SQLException e, PrintWriter pw) {
SQLException next = e;
while (next != null) {
next.printStackTrace(pw);
next = next.getNextException();
if (next != null) {
pw.println("Next SQLException:");
}
}
... |
java | static double pow(final double a, final double b) {
long tmp = Double.doubleToLongBits(a);
long tmp2 = (long) (b * (tmp - 4606921280493453312L)) + 4606921280493453312L;
return Double.longBitsToDouble(tmp2);
} |
java | public static <TimeInstantT extends TimeInstant> TimePickerFragment newInstance(int pickerId, TimeInstantT selectedInstant) {
TimePickerFragment f = new TimePickerFragment();
Bundle args = new Bundle();
args.putInt(ARG_PICKER_ID, pickerId);
args.putParcelable(ARG_SELECTED_INSTANT, selec... |
java | @Override
public void onUpdateBusinessLogicTime(boolean taskOrKeyPresent, boolean externalTaskPresent, long businessLogicTime) {
loops.recordEvent();
if (taskOrKeyPresent) {
this.businessLogicTime.recordValue((int) businessLogicTime);
} else {
if (!externalTaskPresent) {
idleLoops.recordEvent();
} e... |
java | public <T> List<T> query(String query, Class<T> classOfT) {
InputStream instream = null;
List<T> result = new ArrayList<T>();
try {
Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
JsonObject json = new JsonParser().parse(reader).getA... |
java | public void marshall(SubmitTaskStateChangeRequest submitTaskStateChangeRequest, ProtocolMarshaller protocolMarshaller) {
if (submitTaskStateChangeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.mars... |
python | def FindMessageTypeByName(self, full_name):
"""Loads the named descriptor from the pool.
Args:
full_name: The full name of the descriptor to load.
Returns:
The descriptor for the named type.
Raises:
KeyError: if the message cannot be found in the pool.
"""
full_name = _Norm... |
java | protected void configureParser(LSParser parser) {
for (Map.Entry<String, Object> setting : parseSettings.entrySet()) {
setParserConfigParameter(parser, setting.getKey(), setting.getValue());
}
} |
java | public void paintSliderThumbBackground(SynthContext context, Graphics g, int x, int y, int w, int h, int orientation) {
if (context.getComponent().getClientProperty("Slider.paintThumbArrowShape") == Boolean.TRUE) {
if (orientation == JSlider.HORIZONTAL) {
orientation = JSlider.VERTI... |
python | def crossvalidate_model(self, classifier, data, num_folds, rnd, output=None):
"""
Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data:... |
java | private String trackKindToString(final Track.Kind kind) {
if (kind == null) {
return null;
}
switch (kind) {
case SUBTITLES:
return "subtitles";
case CAPTIONS:
return "captions";
case DESCRIPTIONS:
return "descriptions";
case CHAPTERS:
return "chapters";
case METADATA:
r... |
python | def hsig(self, es):
"""return "OK-signal" for rank-one update, `True` (OK) or `False`
(stall rank-one update), based on the length of an evolution path
"""
self._update_ps(es)
if self.ps is None:
return True
squared_sum = sum(self.ps**2) / (1 - (1 - self.cs)*... |
python | def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
... |
python | def plot_curvature(self, curv_type='mean', **kwargs):
"""
Plots the curvature of the external surface of the grid
Parameters
----------
curv_type : str, optional
One of the following strings indicating curvature types
- mean
- gaussian
... |
java | public static void traceMessageId(TraceComponent callersTrace, String action, SIBusMessage message)
{
if (light_tc.isDebugEnabled() || callersTrace.isDebugEnabled()) {
_traceMessageId(callersTrace, action, msgToString(message));
}
} |
java | public static void addEarToServerDropins(LibertyServer server, String earName, boolean addEarResources,
String warName, boolean addWarResources, String jarName, boolean addJarResources, String... packageNames) throws Exception {
addEarToServer(server, DIR_DROPINS, ea... |
java | @Override
public UpdateTemplateResult updateTemplate(UpdateTemplateRequest request) {
request = beforeClientExecution(request);
return executeUpdateTemplate(request);
} |
java | public void setRemoteSeparator(final String value) {
if (value != null && value.length() != 1) {
throw new BuildException("remote separator must be a single character");
}
this.remoteSeparator = value.charAt(0);
} |
java | public void setReadOnly(final boolean readOnly) throws SQLException {
try {
logger.debug("conn={}({}) - set read-only to value {} {}",
protocol.getServerThreadId(),
protocol.isMasterConnection() ? "M" : "S",
readOnly);
stateFlag |= ConnectionState.STATE_READ_ONLY;
pro... |
java | public void store(String path, Class<?> clazz) {
this.store(FileUtil.getAbsolutePath(path, clazz));
} |
python | def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
... |
java | public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
if (map == null) {
throw new NullPointerException(StringUtils.simpleFormat(message, values));
}
if (map.isEmpty()) {
throw new IllegalArgumentException(StringUtils.... |
java | public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
if (mAdapter instanceof SectionIndexerAdapterWrapper) {
((SectionIndexerAdapterWrapper) mAdapter).mSectionIndexerDelegate = null;
}
if (mAdapter != null) {
mAdapt... |
java | @Override
public int filterCountByCompanyId(long companyId) {
if (!InlineSQLHelperUtil.isEnabled(companyId, 0)) {
return countByCompanyId(companyId);
}
StringBundler query = new StringBundler(2);
query.append(_FILTER_SQL_COUNT_COMMERCEACCOUNT_WHERE);
query.append(_FINDER_COLUMN_COMPANYID_COMPANYID_2);
... |
java | public void setSystemPropertyName (@Nullable final String systemPropertyName)
{
m_sSystemPropertyName = systemPropertyName == null ? SYSTEM_PROPERTY : systemPropertyName.trim ();
} |
java | public int getIntField(String name)
throws NumberFormatException
{
String val = valueParameters(get(name),null);
if (val!=null)
return Integer.parseInt(val);
return -1;
} |
java | public T get(int index) {
final int size = size();
int normalisedIndex = normaliseIndex(index, size);
if (normalisedIndex < 0) {
throw new IndexOutOfBoundsException("Negative index [" + normalisedIndex + "] too large for list size " + size);
}
// either index >= siz... |
java | public static CellPosition of(final String address) {
ArgUtils.notEmpty(address, "address");
if(!matchedCellAddress(address)) {
throw new IllegalArgumentException(address + " is wrong cell address pattern.");
}
return of(new CellReference(address));
} |
java | public void marshall(CreateGroupRequest createGroupRequest, ProtocolMarshaller protocolMarshaller) {
if (createGroupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createGroupRequest.getNam... |
python | def _compile_int(self):
"""Time Domain Simulation routine execution"""
string = '"""\n'
# evaluate the algebraic equations g
string += 'system.dae.init_fg(resetz=False)\n'
for gcall, call in zip(self.gcall, self.gcalls):
if gcall:
string += call
... |
python | def get_variable(self, key, per_reference=None, access_key=None, default=None):
"""Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:par... |
java | public EClass getFullyQualifiedName() {
if (fullyQualifiedNameEClass == null) {
fullyQualifiedNameEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(356);
}
return fullyQualifiedNameEClass;
} |
java | public void addWeightParam(@NonNull String paramKey, @NonNull long... paramShape) {
Preconditions.checkArgument(paramShape.length > 0, "Provided weight parameter shape is"
+ " invalid: length 0 provided for shape. Parameter: " + paramKey);
weightParams.put(paramKey, paramShape);
... |
java | public void throwException(String errorString) {
ResourceBundle rb = ResourceBundle.getBundle(LoggingUtil.SESSION_LOGGER_CORE.getResourceBundleName());
String msg = (String) rb.getObject(errorString);
RuntimeException re = new RuntimeException(msg);
throw re;
} |
java | static WorkClassLoader createWorkClassLoader(final ClassBundle cb)
{
return AccessController.doPrivileged(new PrivilegedAction<WorkClassLoader>()
{
public WorkClassLoader run()
{
return new WorkClassLoader(cb);
}
});
} |
python | def get(self, request, *args, **kwargs):
"""
Return a HTTPResponse either of a PDF file or HTML.
:rtype: HttpResponse
"""
if 'html' in request.GET:
# Output HTML
content = self.render_html(*args, **kwargs)
return HttpResponse(content)
... |
python | def get_type_item(self, value, map_name=None, instances=None):
"""
Converts the input to a InputConfigId tuple. It can be from a single string, list, or tuple. Single values
(also single-element lists or tuples) are considered to be a container configuration on the default map. A string
... |
python | def get_max(self, field=None):
"""
Create a max aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods
"""
if not field:
... |
java | public boolean alsoShow(Object filter){
switch(this.defaultState){
case HIDE_ALL:
return this.deltaPool.add(filter);
case SHOW_ALL:
return this.deltaPool.remove(filter);
default:
throw new IllegalStateException("Unknown default state setting: " + this.defaultState);
}
} |
java | private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
JsonGenerator generator = createJsonGenerator(byteStream, Charsets.UTF_8);
if (pretty) {
generator.enablePrettyPrint();
}
generator.seria... |
java | protected static Kernel1D_F32 derivative1D_F32(int order, double sigma, int radius, boolean normalize) {
Kernel1D_F32 ret = new Kernel1D_F32(radius * 2 + 1);
float[] gaussian = ret.data;
int index = 0;
switch( order ) {
case 1:
for (int i = radius; i >= -radius; i--) {
gaussian[index++] = (float) U... |
java | @SuppressWarnings("unchecked")
public <T> T toProxyBean(Class<T> interfaceClass) {
return (T) Proxy.newProxyInstance(ClassLoaderUtil.getClassLoader(), new Class<?>[]{interfaceClass}, this);
} |
python | def update(self, role_sid=values.unset, attributes=values.unset,
friendly_name=values.unset):
"""
Update the UserInstance
:param unicode role_sid: The SID id of the Role assigned to this user
:param unicode attributes: A valid JSON string that contains application-specifi... |
java | public static String getIconClasses(CmsExplorerTypeSettings typeSettings, String resourceName, boolean small) {
String result = null;
if (typeSettings == null) {
typeSettings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(
(resourceName != null) && CmsResource.isFold... |
python | def _add_variants(self, key, value, schema):
''' also possible to define some function that takes
current value and creates a new value from it
'''
variants = schema.get('variants')
obj = {}
if variants:
for _key, func in variants.iteritems():
... |
python | def run(self):
""" Run the receiver thread """
dataOut = array.array('B', [0xFF])
waitTime = 0
emptyCtr = 0
# Try up to 10 times to enable the safelink mode
with self._radio_manager as cradio:
for _ in range(10):
resp = cradio.send_packet((0xf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.