language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def popenCLIExecutable(command, **kwargs):
"""Wrapper around subprocess.Popen constructor that tries to
detect Slicer CLI modules and launches them through the Slicer
launcher in order to prevent potential DLL dependency issues.
Any kwargs are passed on to subprocess.Popen().
If you ever try to us... |
python | def _remove_legacy_bootstrap():
"""Remove bootstrap projects from old path, they'd be really stale by now."""
home = os.environ['HOME']
old_base_dir = os.path.join(home, '.config', 'classpath_project_ensime')
if os.path.isdir(old_base_dir):
shutil.rmtree(old_base_dir, ignore_... |
python | def append_varint64(self, value):
"""Appends a signed 64-bit integer to the internal buffer,
encoded as a varint.
"""
if not wire_format.INT64_MIN <= value <= wire_format.INT64_MAX:
raise errors.EncodeError('Value out of range: %d' % value)
if value < 0:
v... |
python | def load_json(path: str, encoding: str = "utf-8") -> HistogramBase:
"""Load histogram from a JSON file."""
with open(path, "r", encoding=encoding) as f:
text = f.read()
return parse_json(text) |
java | public static iptunnel[] get_filtered(nitro_service service, String filter) throws Exception{
iptunnel obj = new iptunnel();
options option = new options();
option.set_filter(filter);
iptunnel[] response = (iptunnel[]) obj.getfiltered(service, option);
return response;
} |
java | public static void fireRootCause(Throwable t) {
Throwable root = t;
while (root != null) {
Throwable cause = root.getCause();
if (cause == null) {
break;
}
root = cause;
}
fire(root);
} |
java | public void fieldChanged(Field field)
{
Record record = this.getMainRecord();
if (field != null)
if (record != null)
if (field.getRecord() == record)
{
int iErrorCode= record.handleRecordChange((BaseField)field, DBConstants.FIELD_CHANGED_TYPE, DBConstants.... |
java | public void writeToJsonGenerator(final JsonGenerator gen) throws IOException
{
// writes '{eventName:<name>,payload:{<data>}}' --it's kind of silly but ultimately inconsequential to nest them like this.
gen.writeStartObject();
gen.writeStringField("eventName", eventName);
gen.writeFi... |
java | public void sendChallenge(UserRealm realm,
HttpRequest request,
HttpResponse response,
boolean stale)
throws IOException
{
response.setField(HttpFields.__WwwAuthenticate,
"Digest realm=\""+realm.getName(... |
java | @Route(method = HttpMethod.POST, uri = "/")
public Result upload(@FormParameter("upload") FileItem uploaded) {
return ok("File " + uploaded.name() + " of type " + uploaded.mimetype() +
" uploaded (" + uploaded.size() + " bytes)");
} |
java | public FileGetFromComputeNodeHeaders withOcpCreationTime(DateTime ocpCreationTime) {
if (ocpCreationTime == null) {
this.ocpCreationTime = null;
} else {
this.ocpCreationTime = new DateTimeRfc1123(ocpCreationTime);
}
return this;
} |
java | @NonNull
public static Select select(@NonNull SelectResult... results) {
if (results == null) { throw new IllegalArgumentException("results cannot be null."); }
return new Select(false, results);
} |
java | public static void parse(final String str, final ShortcodeParser.Handler handler) {
ShortcodeParser.parse(str, handler);
} |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString svm_version_validator = new MPSString();
svm_version_validator.validate(operationType, svm_version, "\"svm_version\"");
MPSString xen_version_validator = new MPSString();
xen_version_validato... |
java | @Override
public RoundedMoney multiply(Number multiplicand) {
BigDecimal bd = MoneyUtils.getBigDecimal(multiplicand);
if (isOne(bd)) {
return this;
}
MathContext mc = monetaryContext.get(MathContext.class);
if(mc==null){
mc = MathContext.DECIMAL64;
... |
java | protected void findLocalScaleSpaceMax(PyramidFloat<T> ss, int layerID) {
List<Point2D_I16> candidates = maximums;
float scale0 = (float) ss.scale[layerID - 1];
float scale1 = (float) ss.scale[layerID];
float scale2 = (float) ss.scale[layerID + 1];
float sigma0 = (float) ss.getSigma(layerID - 1);
float sig... |
java | protected static SecurityContext createSC(String user, String... roles) {
final Subject subject = new Subject();
final Principal principal = new SimplePrincipal(user);
subject.getPrincipals().add(principal);
if (roles != null) {
for (final String role : roles) {
... |
java | public boolean containsCountry (@Nullable final String sCountry)
{
if (sCountry == null)
return false;
final String sValidCountry = LocaleHelper.getValidCountryCode (sCountry);
if (sValidCountry == null)
return false;
return m_aRWLock.readLocked ( () -> m_aCountries.contains (sValidCountr... |
python | def close(self, session):
"""Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: VISAStatus
... |
java | public String[] readHeader(BufferedReader bufferedReader, ParseError parseError)
throws ParseException, IOException {
checkEntityConfig();
String header = bufferedReader.readLine();
if (header == null) {
if (parseError == null) {
throw new ParseException("no header line read", 0);
} else {
parseE... |
java | public static BigInteger gcd(BigInteger a, BigInteger b) {
return gcd(a, b, Calculator.BIG_INTEGER_CALCULATOR);
} |
java | private boolean isRandom(final String password, final List<Match> matches)
{
int matched_length = 0;
int max_matched_length = 0;
for (Match match : matches)
{
if (!(match instanceof BruteForceMatch))
{
matched_length += match.getLength();
... |
python | def _is_unindentor(self, line):
"""return true if the given line is an 'unindentor',
relative to the last 'indent' event received.
"""
# no indentation detail has been pushed on; return False
if len(self.indent_detail) == 0:
return False
indentor = self.ind... |
java | @Deprecated
void execute(String sql, Object... parameters) {
if (N.isNullOrEmpty(parameters)) {
sqliteDB.execSQL(sql);
} else {
final NamedSQL namedSQL = parseSQL(sql);
final Object[] args = prepareArguments(namedSQL, parameters);
sqliteDB.execS... |
python | def _generate_processing_blocks(start_id, min_blocks=0, max_blocks=4):
"""Generate a number of Processing Blocks"""
processing_blocks = []
num_blocks = random.randint(min_blocks, max_blocks)
for i in range(start_id, start_id + num_blocks):
_id = 'sip-pb{:03d}'.format(i)
block = dict(id=_... |
java | public Observable<Page<LabInner>> listAsync(final String resourceGroupName, final String labAccountName) {
return listWithServiceResponseAsync(resourceGroupName, labAccountName)
.map(new Func1<ServiceResponse<Page<LabInner>>, Page<LabInner>>() {
@Override
public Page<... |
java | public void marshall(DescribeMaintenanceWindowExecutionTaskInvocationsRequest describeMaintenanceWindowExecutionTaskInvocationsRequest,
ProtocolMarshaller protocolMarshaller) {
if (describeMaintenanceWindowExecutionTaskInvocationsRequest == null) {
throw new SdkClientException("Invalid ... |
python | def save(self, prepend_vault_id=''):
"""
Adds or updates a users CC to the vault.
@prepend_vault_id: any string to prepend all vault id's with in case the same braintree account is used by
multiple projects/apps.
"""
assert self.is_valid()
cc_det... |
python | def WaitUntilValid(self, timeout=None):
"""Wait until the approval is valid (i.e. - approved).
Args:
timeout: timeout in seconds. None means default timeout (1 hour).
0 means no timeout (wait forever).
Returns:
Operation object with refreshed target_file.
Raises:
PollTi... |
python | def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None):
"""
Plot boxplots
Plot the boxplots of a dataframe in time
Parameters
----------
df: Pandas Dataframe
Every collumn is a timeseries
plot_mean: bool
Wether or not to plot the means
plo... |
java | public static List<FileStatus> listFilesRecursively(FileSystem fs, Path path, PathFilter fileFilter,
boolean applyFilterToDirectories)
throws IOException {
return listFilesRecursivelyHelper(fs, Lists.newArrayList(), fs.getFileStatus(path), fileFilter,
applyFilterToDirectories, false);
} |
java | private boolean dequeueTransmissionData(WsByteBuffer bufferToFill) throws SIConnectionDroppedException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dequeueTransmissionData", bufferToFill);
boolean exhaustedTransmissionsToSend = false;
boolean dataCopied = ... |
python | def _update_indicator(self,K,L):
""" update the indicator """
_update = {'term': self.n_terms*np.ones((K,L)).T.ravel(),
'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(),
'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()}
... |
java | protected File getResourcesDirectory()
{
if ( resourcesDirectory == null )
{
resourcesDirectory = new File( getProject().getBasedir(), DEFAULT_RESOURCES_DIR );
}
return resourcesDirectory;
} |
python | def _build_new_template(self, stack, parameters):
"""Constructs the parameters & contents of a new stack and returns a
list(str) representation to be output to the user
"""
log_lines = ["New template parameters:"]
for param in sorted(parameters,
key=la... |
java | public ServiceFuture<List<LabeledUtterance>> listAsync(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter, final ServiceCallback<List<LabeledUtterance>> serviceCallback) {
return ServiceFuture.fromResponse(listWithServiceResponseAsync(appId, versionId, listOptionalParameter), serv... |
python | def load(self, filename, offset):
"""Will eventually load information for Apple_Boot volume. \
Not yet implemented"""
try:
self.offset = offset
# self.fd = open(filename, 'rb')
# self.fd.close()
except IOError:
self.logger.error('Unable to ... |
python | def overload(fn, function_to_overload=None):
'''
This function decorator allows you to overload already defined functions. The
execution of overloaded functions is done by trying the original version first
and if it fails, the variables are handed off to the overloading function.
While this does seem like a sl... |
python | def plot_ortho(image, overlay=None, reorient=True, blend=False,
# xyz arguments
xyz=None, xyz_lines=True, xyz_color='red', xyz_alpha=0.6, xyz_linewidth=2, xyz_pad=5,
orient_labels=True,
# base image arguments
alpha=1, cmap='Greys_r',
# overlay arguments
overlay_cmap='jet', overlay_alpha=0.9... |
java | private void finalizeRePattern(String name, String rePattern) {
// create correct regular expression
rePattern = rePattern.replaceFirst("\\|", "");
/* this was added to reduce the danger of getting unusable groups from user-made repattern
* files with group-producing parentheses (i.e. "(foo|bar)" while matchin... |
java | public Release rollback(String appName, String releaseUuid) {
return connection.execute(new Rollback(appName, releaseUuid), apiKey);
} |
java | @Override
protected void defineWidgets() {
super.defineWidgets();
// widgets to display
// new indexsource
if (m_indexsource.getName() == null) {
addWidget(new CmsWidgetDialogParameter(m_indexsource, "name", PAGES[0], new CmsInputWidget()));
} else {
... |
python | def render_category(category='', template=None):
""" Render a category page.
Arguments:
category -- The category to render
template -- The template to render it with
"""
# pylint:disable=too-many-return-statements
# See if this is an aliased path
redir = get_redirect()
if redir:
... |
python | def _distance_between_coords(self, lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees).
Haversine formula states that:
d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 +
cos(lat1)cos(lat2)sin^2((l... |
java | public com.google.protobuf.ByteString
getVisibleDeviceListBytes() {
java.lang.Object ref = visibleDeviceList_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
visibleDeviceL... |
java | public void shuffleColumnsAndThenRows(ArrayList<String> columns, ArrayList<String> rows) throws Exception {
doubleValues.clear();
for (String column : columns) { //shuffle all values in the column
ArrayList<Integer> rowIndex = new ArrayList<Integer>();
for (int i = 0; i < rows.size(); i++) {
rowIndex.add... |
java | public void submitHadoopDownloadTask(String URL, String id) {
Callable<ImageDownloadResult> call = new HadoopImageDownload(URL, id, followRedirects);
pool.submit(call);
numPendingTasks++;
} |
python | def heap_snapshot(self):
""" Return heap snapshot """
self.lock.acquire()
res = self.ext.mr_heap_snapshot(self.ctx)
self.lock.release()
python_value = res.contents.to_python()
self.free(res)
return python_value |
python | def folder_pre_delete(self, request, folder):
"""
Perform folder operations prior to deletions. For example, deleting all contents.
"""
for m in folder.members():
if m.__class__ == folder.__class__:
self.folder_pre_delete(request, m)
m.delete() |
java | public void appendQuerytoSQL(Collection<Match> matches, StringBuilder sb, List<Object> params) {
// 如果query为空,则直接返回
if (matches == null || matches.size() == 0) {
return;
}
sb.append(" where ");
appendMatches(matches, sb, params);
} |
java | public static <T> MonadicObservableValue<T> monadic(ObservableValue<T> o) {
if(o instanceof MonadicObservableValue) {
return (MonadicObservableValue<T>) o;
} else {
return new MonadicWrapper<>(o);
}
} |
python | def program_unit_name(line:str) -> str:
"""Given a line that starts a program unit, i.e., a program, module,
subprogram, or function, this function returns the name associated
with that program unit."""
match = RE_PGM_UNIT_START.match(line)
assert match != None
return match.group(2) |
java | protected static void initializeControlMessage(SIBUuid8 sourceME, ControlMessage msg, SIBUuid8 remoteMEId)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "initializeControlMessage", new Object[] {msg, remoteMEId});
SIMPUtils.setGuaranteedDeliveryProperties(msg,
... |
java | public ServiceFuture<Void> deleteDataLakeStoreAccountAsync(String resourceGroupName, String accountName, String dataLakeStoreAccountName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteDataLakeStoreAccountWithServiceResponseAsync(resourceGroupName, accountName, dataLakeSt... |
python | def numdiff(fun, args):
"""Vectorized numerical differentiation"""
# vectorized version
epsilon = 1e-8
args = list(args)
v0 = fun(*args)
N = v0.shape[0]
l_v = len(v0)
dvs = []
for i, a in enumerate(args):
l_a = (a).shape[1]
dv = numpy.zeros((N, l_v, l_a))
na... |
java | private void preprocess_RenameMemberShapes(String shapeName, Shape shape) {
if (shape.getListMember() != null) {
preprocess_RenameMemberShape(shape.getListMember());
}
if (shape.getMapKeyType() != null) {
preprocess_RenameMemberShape(shape.getMapKeyType());
}
... |
java | public ArrayList<String> generateBindings(String interfaceName,
String specificBindingName,
boolean
generateDisambiguatedSimpleBindingNames)
throws NameAlreadyBou... |
python | def _blackbox_time(time_scale, blackbox, system):
"""Black box the CM and TPM over the given time_scale."""
blackbox = blackbox.reindex()
tpm = run_tpm(system, time_scale, blackbox)
# Universal connectivity, for now.
n = len(system.node_indices)
cm = np.ones((n, n))
... |
python | def add_sibling(self, sibling):
"""
Designate this a multi-feature representative and add a co-feature.
Some features exist discontinuously on the sequence, and therefore
cannot be declared with a single GFF3 entry (which can encode only a
single interval). The canonical encodin... |
python | def subscribe_state_matcher(self, container, connected = True):
'''
Return a matcher to match the subscribe connection status.
:param container: a routine container. NOTICE: this method is not a routine.
:param connected: if True, the matcher matches connection up. If F... |
python | def numConnects(self, layerName):
""" Number of incoming weights, including bias. Assumes fully connected. """
count = 0
if self[layerName].active:
count += 1 # 1 = bias
for connection in self.connections:
if connection.active and connection.fromLayer.act... |
java | public void setHideFixedToolbarsIfVirtualKeyboard(int value) {
int oldVal = hideFixedToolbarsIfVirtualKeyboard;
hideFixedToolbarsIfVirtualKeyboard = value;
if (oldVal != hideFixedToolbarsIfVirtualKeyboard
&& content != null && content.isAttached()) {
processFixedToolb... |
java | @Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) {
return commercePriceEntryPersistence.findWithDynamicQuery(dynamicQuery);
} |
java | @Override
public Agreement getWsagObject(String serializedData) throws ParserException{
Agreement agreement = null;
try{
logger.info("Will parse {}", serializedData);
agreement = mapper.readValue(serializedData, Agreement.class);
logger.info("Agreement parse... |
java | private void maybeStop(long stopCheck, long now)
{
long delta = now - stopCheck;
if (delta <= 0)
{
// if stopCheck has caught up with present, we've been spinning too much, so if we can atomically
// set it to the past again, we should stop a worker
if (po... |
python | def duplicate_statements(model, oldorigin, neworigin, rfilter=None):
'''
Take links with a given origin, and create duplicate links with the same information but a new origin
:param model: Versa model to be updated
:param oldres: resource IRI to be duplicated
:param newres: origin resource IRI for ... |
python | def uninstall(self):
"""Uninstall this importer if possible and un-import any modules imported by it."""
if not self._uninstallable:
_tracer().log('Not uninstalling {}'.format(self), V=9)
return
if self in sys.meta_path:
sys.meta_path.remove(self)
maybe_exposed = frozenset(os.path.j... |
java | Object addRightMostKey(
Object new1)
{
Object old1 = null;
if (isFull()) /* Node is currently full */
{ /* We will overlay right-most key */
old1 = rightMostKey();
_nodeKey[rightMostIndex()] = new1;
}... |
java | public static boolean isSuperSenseFeatures(final TrainingParameters params) {
final String mfsFeatures = getSuperSenseFeatures(params);
return !mfsFeatures.equalsIgnoreCase(Flags.DEFAULT_FEATURE_FLAG);
} |
java | public static int getMemberDimension() throws XDocletException
{
if (getCurrentField() != null) {
return getCurrentField().getDimension();
}
else if (getCurrentMethod() != null) {
XMethod method = getCurrentMethod();
if (MethodTagsHandler.isGetter... |
python | def get_success_url(self):
"""Return the URL to redirect to after processing a valid form."""
if not self.success_url:
if self.request.GET.get("inmodal"):
return reverse("arctic:redirect_to_parent")
raise ImproperlyConfigured(
"No URL to redirect t... |
java | private static String readPrimitiveArrayValue(String ref, TypeDef source, Property property) {
StringBuilder sb = new StringBuilder();
Method getter = getterOf(source, property);
sb.append(indent(ref))
.append("Arrays.stream(")
.append("("+property.getTypeRef().t... |
java | public static GrammaticalRelation getGrammaticalRelation(TreeGraphNode gov, TreeGraphNode dep) {
GrammaticalRelation reln = GrammaticalRelation.DEPENDENT;
TreeGraphNode govH = gov.highestNodeWithSameHead();
TreeGraphNode depH = dep.highestNodeWithSameHead();
/*System.out.println("gov node " + gov);
... |
java | public static String getActivationKey(String gatewayAddress, Region activationRegion) throws AmazonClientException {
return getActivationKey(gatewayAddress,
activationRegion == null ?
null : activationRegion.getName());
} |
python | def _save(self):
"""Save the sub-resource within the parent resource"""
yield self.validate()
try:
self._parent = yield self.parent_resource.get(self.parent_id)
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resourc... |
java | public Observable<ServiceResponseWithHeaders<Page<Certificate>, CertificateListHeaders>> listSinglePageAsync() {
if (this.client.batchUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null.");
}
if (this.client.apiVersion(... |
java | private void btDetailsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btDetailsActionPerformed
{//GEN-HEADEREND:event_btDetailsActionPerformed
spDetails.setVisible(btDetails.isSelected());
pack();
validate();
} |
java | public Nfs3GetAttrResponse wrapped_getAttr(NfsGetAttrRequest request) throws IOException {
NfsResponseHandler<Nfs3GetAttrResponse> responseHandler = new NfsResponseHandler<Nfs3GetAttrResponse>() {
/* (non-Javadoc)
* @see com.emc.ecs.nfsclient.rpc.RpcResponseHandler#makeNewResponse()
... |
python | def _to_timezone(self, dt):
"""Takes a naive timezone with an utc value and return it formatted as a
local timezone."""
tz = self._get_tz()
utc_dt = pytz.utc.localize(dt)
return utc_dt.astimezone(tz) |
java | private void flushURLConnection(URLConnection conn) {
byte[] buf = new byte[1024];
try {
InputStream is = conn.getInputStream();
while (is.read(buf) >= 0) {
// Ignore
}
is.close();
} catch (IOException e) {
try {
... |
java | public static ColumnIO lookupColumnByName(GroupColumnIO groupColumnIO, String columnName)
{
ColumnIO columnIO = groupColumnIO.getChild(columnName);
if (columnIO != null) {
return columnIO;
}
for (int i = 0; i < groupColumnIO.getChildrenCount(); i++) {
if (gr... |
python | def mount(self, prefix, adapter):
"""Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
"""
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
for key in keys_to_move:
... |
python | def _reject_neg(pos_lst: List, neg_lst: List) -> List:
"""
Reject some positive matches according to negative matches
Args:
pos_lst: List
neg_lst: List
Returns: List
"""
pos_lst.sort()
neg_lst.sort()
result = []
pivot_pos ... |
python | def deleteStyle(self, name, verbose=None):
"""
Deletes the Visual Style specified by the `name` parameter.
:param name: Visual Style Name
:param verbose: print more
:returns: default: successful operation
"""
response=api(url=self.___url+'styles/'+str(name)+'',... |
java | public static byte[] i2cConfigRequest(int delayInMicroseconds) {
if (delayInMicroseconds < 0) {
throw new IllegalArgumentException("Delay cannot be less than 0 microseconds.");
}
if (delayInMicroseconds > 255) {
throw new IllegalArgumentException("Delay cannot be greater ... |
python | def retry_on_exception(num_retries, base_delay=0, exc_type=Exception):
"""If the decorated function raises exception exc_type, allow num_retries
retry attempts before raise the exception.
"""
def _retry_on_exception_inner_1(f):
def _retry_on_exception_inner_2(*args, **kwargs):
retrie... |
java | private boolean isBlankRow(String[] line)
{
boolean ret = true;
for(int i = 0; i < line.length && ret; i++)
{
if(line[i] != null && line[i].trim().length() > 0)
ret = false;
}
return ret;
} |
java | public GetPresetResponse getPreset(String presetName) {
GetPresetRequest request = new GetPresetRequest();
request.setPresetName(presetName);
return getPreset(request);
} |
java | public static void addAvroKryoSerializations(Config conf) throws ClassNotFoundException {
final Class serializerClass;
if (conf.containsKey("avro.serializer")) {
serializerClass = Class.forName((String)conf.get("avro.serializer"));
}
else {
serializerClass = Gener... |
java | @Override
public void visitDereference(Expr.Dereference expr, Boolean consumed) {
visitExpression(expr.getOperand(),false);
} |
java | @Override
protected Stream<Module> buildGuiceModules() {
return Stream.concat(Stream.concat(
super.buildGuiceModules(),
sqlConfiguration.buildGuiceModules()),
Stream.of(
new OntopMappingSQLModule(this),
n... |
python | def update(self, **kwargs):
"""Update the Account resource with specified content.
Args:
name (str): Human-readable name for the account
Returns: the updated Account object.
"""
return self.__class__(self.resource.update(kwargs),
self.cli... |
java | public String convertAccessMethodToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
java | public String getStringProperty(final String name) {
String prop = null;
try {
prop = System.getProperty(name);
} catch (final SecurityException ignored) {
// Ignore
}
return prop == null ? props.getProperty(name) : prop;
} |
java | public void bindLocal(DatagramChannel channel, int port) throws IOException {
// select port if wildcarded
if (port == PORT_ANY) {
port = localPortManager.next();
}
// try bind
IOException ex = null;
for (int q = 0; q < 100; q++) {
try {
... |
python | def _calc_odds(self):
'''Calculates the absolute probability of all posible rolls.'''
def recur(val, h, dice, combinations):
for pip in dice[0]:
tot = val + pip
if len(dice) > 1:
combinations = recur(tot, h, dice[1:], combinations)
... |
java | public List<Filter> getAllFiltersForField(String field) {
List<Filter> foundFilters = new ArrayList<>();
for (Filter filter : this.filters) {
if (filter.getField().equals(field)) {
foundFilters.add(filter);
}
}
return Collections.unmodifiableList(foundFilters);
} |
java | public Reflector call(String name, Object... args) throws ReflectException {
Class<?>[] types = getTypes(args);
try {
Method method = exactMethod(name, types);
return with(method, obj, args);
} catch (NoSuchMethodException e) {
try {
Method me... |
java | private Reference createExtensionFactoryReference(ObjectFactoryInfo extensionFactory,
ResourceInjectionBinding resourceBinding) // F48603.9
{
String className = extensionFactory.getObjectFactoryClass().getName();
Reference ref = new Reference(res... |
java | public HttpResponse doResourceBundle(StaplerRequest request) {
String baseName = request.getParameter("baseName");
if (baseName == null) {
return HttpResponses.errorJSON("Mandatory parameter 'baseName' not specified.");
}
String language = request.getParameter("language");
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.