language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _AppendRecord(self):
"""Adds current record to result if well formed."""
# If no Values then don't output.
if not self.values:
return
cur_record = []
for value in self.values:
try:
value.OnSaveRecord()
except SkipRecord:
self._ClearRecord()
return
... |
java | private void checkInheritedRelativePaths( ClassDeclaration jclass )
throws FatalCompileTimeException
{
for ( ClassType type = jclass.getSuperclass();
type != null && CompilerUtils.isAssignableFrom( FLOWCONTROLLER_BASE_CLASS, type, getEnv() );
type = type.getSuperclass... |
python | def overlay_pdfs(top_pdf, bottom_pdf, destination):
"""
Overlay PDF objects to files
:param top_pdf: PDF object to be placed on top
:param bottom_pdf: PDF file to be placed underneath
:param destination: Desintation path
"""
drawing = PdfFileReader(top_pdf) # Create new PDF object
templ... |
python | def sign_assertion_using_xmlsec(self, statement, **kwargs):
""" Deprecated function. See sign_assertion(). """
return self.sign_statement(
statement, class_name(saml.Assertion()), **kwargs) |
java | public void update( Client client ) {
RestfulUtils.update( ClientService.PATH, client, Client.class, super.httpClient );
} |
python | def assign_value(self, comp_def, value, src_ref):
"""
Overrides other related properties
"""
super().assign_value(comp_def, value, src_ref)
if "rclr" in comp_def.properties:
del comp_def.properties["rclr"]
if "rset" in comp_def.properties:
del comp... |
java | public final void entryRuleJvmUpperBoundAnded() throws RecognitionException {
try {
// InternalXtype.g:234:1: ( ruleJvmUpperBoundAnded EOF )
// InternalXtype.g:235:1: ruleJvmUpperBoundAnded EOF
{
if ( state.backtracking==0 ) {
before(grammarAccess.g... |
java | public SmartHandle apply(String name, Object arg) {
return new SmartHandle(signature.dropArg(name), MethodHandles.insertArguments(handle, signature.argOffset(name), arg));
} |
python | def get_parents(obj, **kwargs):
"""Return the MRO of an object. Do regex on each element to remove the "<class..." bit."""
num_of_mro = kwargs.get("num_of_mro", 5)
mro = getmro(obj.__class__)
mro_string = ', '.join([extract_type(str(t)) for t in mro[:num_of_mro]])
return "Hierarchy: {}".format(mro... |
python | def extrusion(target, throat_perimeter='throat.perimeter',
throat_length='throat.length'):
r"""
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with... |
java | private Callable<S3Object> serviceCall(final PresignedUrlDownloadRequest presignedUrlDownloadRequest) {
return new Callable<S3Object>() {
@Override
public S3Object call() throws Exception {
return s3.download(presignedUrlDownloadRequest)
.getS3Obj... |
java | public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
try {
String methodName = method.getName();
Object returnValue;
if (mountPoint.length() == 0) {
if ("getContextPath".equals(methodName) ||
"get... |
java | public List<EnvEntryType<ApplicationDescriptor>> getAllEnvEntry()
{
List<EnvEntryType<ApplicationDescriptor>> list = new ArrayList<EnvEntryType<ApplicationDescriptor>>();
List<Node> nodeList = model.get("env-entry");
for(Node node: nodeList)
{
EnvEntryType<ApplicationDescriptor> typ... |
python | def _run_bookkeeping_sql_scripts(
self):
"""*run bookkeeping sql scripts*
"""
self.log.info('starting the ``_run_bookkeeping_sql_scripts`` method')
moduleDirectory = os.path.dirname(__file__)
mysqlScripts = moduleDirectory + "/mysql"
directory_script_runner(... |
java | public ListProvisionedProductPlansResult withProvisionedProductPlans(ProvisionedProductPlanSummary... provisionedProductPlans) {
if (this.provisionedProductPlans == null) {
setProvisionedProductPlans(new java.util.ArrayList<ProvisionedProductPlanSummary>(provisionedProductPlans.length));
}
... |
python | def sign_data(self, name, hash_input, key_version=None, hash_algorithm="sha2-256", context="", prehashed=False,
signature_algorithm="pss", mount_point=DEFAULT_MOUNT_POINT):
"""Return the cryptographic signature of the given data using the named key and the specified hash algorithm.
Th... |
java | public void marshall(StartImageBuilderRequest startImageBuilderRequest, ProtocolMarshaller protocolMarshaller) {
if (startImageBuilderRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startIm... |
java | @Override
public EEnum getIfcSanitaryTerminalTypeEnum() {
if (ifcSanitaryTerminalTypeEnumEEnum == null) {
ifcSanitaryTerminalTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1058);
}
return ifcSanitaryTerminalTypeEnumEEnum;
} |
python | def _collapse_root(master, current, dsn, pc):
"""
Collapse the root items of the current time series entry
:param dict master: LiPD data (so far)
:param dict current: Current time series entry
:param str dsn: Dataset name
:param str pc: paleoData or chronData (mode)
:return dict master:
... |
java | private SSLEngine getSSLEngine() throws KeyStoreException,
CertificateException,
IOException,
UnrecoverableKeyException,
KeyManagementException {
// Open the KeyStore Stream
final StreamManager streamManager = new Strea... |
java | @SuppressWarnings("unchecked")
static <T> TypeInfoImpl<T> typeInfoFor(Class<T> sourceType, InheritingConfiguration configuration) {
TypeInfoKey pair = new TypeInfoKey(sourceType, configuration);
TypeInfoImpl<T> typeInfo = (TypeInfoImpl<T>) cache.get(pair);
if (typeInfo == null) {
synchronized... |
python | def week_to_datetime(iso_year, iso_week):
"datetime instance for the start of the given ISO year and week"
gregorian = iso_to_gregorian(iso_year, iso_week, 0)
return datetime.datetime.combine(gregorian, datetime.time(0)) |
java | public boolean intersect(Line other, boolean limit, Vector2f result) {
float dx1 = end.getX() - start.getX();
float dx2 = other.end.getX() - other.start.getX();
float dy1 = end.getY() - start.getY();
float dy2 = other.end.getY() - other.start.getY();
float denom = (dy2 * dx1) - (dx2 * dy1);
if (deno... |
python | def templated_docstring(**docs):
"""
Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar'
"""
def decorator(f):
f.__doc__ = format_d... |
java | static List<GoogleToken> getGoogleTokens(AnalyzedSentence sentence, boolean addStartToken, Tokenizer wordTokenizer) {
List<GoogleToken> result = new ArrayList<>();
if (addStartToken) {
result.add(new GoogleToken(LanguageModel.GOOGLE_SENTENCE_START, 0, 0));
}
List<String> tokens = wordTokenizer.tok... |
python | def status_git(path, ignore_set, options):
"""Run git status.
Returns a 2-element tuple:
* Text lines describing the status of the repository.
* List of subrepository paths, relative to the repository itself.
"""
# Check whether current branch is dirty:
lines = [l for l in run(('git', 'stat... |
python | def __get_call_count(self, args, kwargs, args_list, kwargs_list):
"""
Args:
args: tuple, the arguments inputed by the user
kwargs: dictionary, the keyword arguments inputed by the user
args_list: list, the tuples of args from all the times this stub was called
... |
python | def get_success_url(self, obj=None):
"""
Args:
obj (object): The object whose property values are used to build the URL.
Returns:
str: The URL to which to go if the form was processed successfully.
"""
if self.success_endpoint is None:
raise A... |
java | public static SocketAddress parseSocketAddress(String value) {
if (value.startsWith(UNIX_DOMAIN_SOCKET_PREFIX)) {
// Unix Domain Socket address.
// Create the underlying file for the Unix Domain Socket.
String filePath = value.substring(UNIX_DOMAIN_SOCKET_PREFIX.length());
File file = new Fi... |
python | def summary(svc_name=''):
'''
Display a summary from monit
CLI Example:
.. code-block:: bash
salt '*' monit.summary
salt '*' monit.summary <service name>
'''
ret = {}
cmd = 'monit summary'
res = __salt__['cmd.run'](cmd).splitlines()
for line in res:
if 'dae... |
python | def get_pr(pr_num, config=None, repo=DEFAULT_REPO, raw=False):
"""
Get the payload for the given PR number. Let exceptions bubble up.
"""
response = requests.get(PR_ENDPOINT.format(repo, pr_num), auth=get_auth_info(config))
if raw:
return response
else:
response.raise_for_status... |
python | def to_rgba(color, alpha):
"""
Converts from hex|rgb to rgba
Parameters:
-----------
color : string
Color representation on hex or rgb
alpha : float
Value from 0 to 1.0 that represents the
alpha value.
Example:
... |
python | def get_expiration(self):
"""Returns the expiration date.
:returns: expiration date
:rtype: datetime object
"""
exp = self._get_int('expiration')
if exp is not None:
return datetime.datetime.fromtimestamp(
exp
)
return None |
java | public static double computeJointSegmentsCost(final DataSegment segmentA, final DataSegment segmentB)
{
final Interval intervalA = segmentA.getInterval();
final Interval intervalB = segmentB.getInterval();
final double t0 = intervalA.getStartMillis();
final double t1 = (intervalA.getEndMillis() - t0)... |
java | @Override
public ApplySecurityGroupsToClientVpnTargetNetworkResult applySecurityGroupsToClientVpnTargetNetwork(
ApplySecurityGroupsToClientVpnTargetNetworkRequest request) {
request = beforeClientExecution(request);
return executeApplySecurityGroupsToClientVpnTargetNetwork(request);
... |
python | def get_pullrequest(self, project, repository, pull_request_id):
"""
Retrieve a pull request.
The authenticated user must have REPO_READ permission
for the repository that this pull request targets to call this resource.
:param project:
:param repository:
:param p... |
java | public synchronized void bindShader(GVRScene scene, boolean isMultiview)
{
GVRRenderPass pass = mRenderPassList.get(0);
GVRShaderId shader = pass.getMaterial().getShaderType();
GVRShader template = shader.getTemplate(getGVRContext());
if (template != null)
{
templ... |
python | def _get_schema_for_field(self, obj, field):
"""Get schema and validators for field."""
mapping = self._get_default_mapping(obj)
if hasattr(field, '_jsonschema_type_mapping'):
schema = field._jsonschema_type_mapping()
elif '_jsonschema_type_mapping' in field.metadata:
... |
java | private void installLayout(JRootPane root) {
if (layoutManager == null) {
layoutManager = createLayoutManager();
}
savedOldLayout = root.getLayout();
root.setLayout(layoutManager);
} |
java | public<T> Get<T> get(Class<T> cls) throws APIException {
return new Get<T>(this,getDF(cls));
} |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'type') and self.type is not None:
_dict['type'] = self.type
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(se... |
python | def _parse_eloss(line, lines):
"""Parse Energy [eV] eloss_xx eloss_zz"""
split_line = line.split()
energy = float(split_line[0])
eloss_xx = float(split_line[1])
eloss_zz = float(split_line[2])
return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz} |
java | public static boolean call(PrintStream out, PrintStream err, String... args) {
return new Main(out, err).run(args);
} |
java | public static <T> T newInstance(final Class<T> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ClassApiException(e);
}
} |
java | public void addToBreadcrumb(String breadCrumb) {
setBreadcrumb(breadCrumb + Constants.BREADCRUMB_DELIMITER + description);
settings.forEach(setting -> setting.addToBreadcrumb(getBreadcrumb()));
} |
java | private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) {
InputStream in = new BufferedInputStream(new CloseShieldInputStream(is));
if (charset == null) {
return new ZipInputStream(in);
}
return ZipFileUtil.createZipInputStream(in, charset);
} |
java | @Override
public void onPartitionProcessBegin(Partition partition, long partitionProcessTime, long partitionUpdateTime) {
Preconditions.checkNotNull(partition);
Preconditions.checkNotNull(partition.getTable());
if (!this.expectedHighWatermarks.hasPartitionWatermarks(tableKey(partition.getTable()))) {
... |
java | public Tag getParent() {
if (!parentDetermined) {
JspTag adapteeParent = simpleTagAdaptee.getParent();
if (adapteeParent != null) {
if (adapteeParent instanceof Tag) {
this.parent = (Tag) adapteeParent;
} else {
// Must be SimpleTag - no other types defined.
this.parent = new TagAdapter... |
java | private boolean isRelated(final INode source, final INode target, final char relation) {
return relation == defautlMappings.getRelation(source, target);
} |
python | def threshold_monitor_hidden_threshold_monitor_Memory_actions(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_m... |
java | public void export( Graph pGraph, Schema pSchema, DotWriter pDotWriter, boolean pOutRefsOnly )
{
pDotWriter.printHeaderStart( pGraph.getStyleForGraph() );
if( pGraph.isCollapseSubgraphs() )
{
_writeSubgraphRecursiveCollapsed( pGraph, pSchema, pDotWriter, pOutRefsOnly );
List<Graph> lEndGraph... |
java | private MapConfiguration createMapConfiguration(ClientMapInfo mapInfo, MapPresenter mapPresenter) {
MapConfiguration configuration = mapPresenter.getConfiguration();
configuration.setCrs(mapInfo.getCrs(), mapInfo.getUnitLength());
configuration.setHintValue(MapConfiguration.INITIAL_BOUNDS, mapInfo.getInitialBound... |
java | static String extractWhereConditions(boolean updateMode, SQLiteModelMethod method) {
final One<String> whereCondition = new One<String>("");
final One<Boolean> found = new One<Boolean>(null);
JQLChecker.getInstance().replaceVariableStatements(method, method.jql.value, new JQLReplaceVariableStatementListenerImpl()... |
java | public static cmppolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{
cmppolicy_lbvserver_binding obj = new cmppolicy_lbvserver_binding();
obj.set_name(name);
cmppolicy_lbvserver_binding response[] = (cmppolicy_lbvserver_binding[]) obj.get_resources(service);
return response;
} |
python | def get_fasta_record(fasta_file, transcript_name):
"""Return a single transcript from a valid fasta file as a record.
record[transcript_name] = sequence
Keyword arguments:
fasta_file -- FASTA format file of the transcriptome
transcript_name -- Name of the transcript as in the FASTA header
"""... |
java | private Region getRegion()
{
while (true)
{
// Try to get the region
Region region = currentRegion.get();
if (region != null)
return region;
// No current region, so we want to allocate one. We race
// against other allocat... |
python | def plot_gen_diff(
networkA,
networkB,
leave_out_carriers=[
'geothermal',
'oil',
'other_non_renewable',
'reservoir',
'waste']):
"""
Plot difference in generation between two networks grouped by carrier type
Parameters
----------
networkA : PyPSA ... |
python | def company_add_user(self, email, name, password, receiver, admin):
"""Add a user to the company account.
:param email:
:param name:
:param password: Pass without storing in plain text
:param receiver: Can user receive files
:param admin:
:type email: ``str`` or ... |
java | public String substituteLinkForRootPath(CmsObject cms, String rootPath) {
String siteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);
if (siteRoot == null) {
// use current site root in case no valid site root is available
// this will also be the case if a "/system" link ... |
python | def set_category(self, category):
"""Set package category
Args:
category: String of an existing category's name, or a
Category object.
"""
# For some reason, packages only have the category name, not the
# ID.
if isinstance(category, Category)... |
java | public static Cardinality createCardinality(AtlasCardinality cardinality) {
switch(cardinality) {
case SINGLE:
return Cardinality.SINGLE;
case LIST:
return Cardinality.LIST;
case SET:
return Cardinality.SET;
default:
throw new Ille... |
python | def edit(self, **kwargs):
"""
Modify this calendar event.
:calls: `PUT /api/v1/calendar_events/:id \
<https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.update>`_
:rtype: :class:`canvasapi.calendar_event.CalendarEvent`
"""
res... |
python | def differentiate_mi(x, y):
'''
for each symbol in x, change x such that there are no more of such symbols
(replacing by a random distribution with the same proba of all other symbols)
and compute mi(new_x, y)
'''
#pdb.set_trace()
dist = Distribution(discrete.symbols_to_prob(x))
diff = ... |
java | public static hanode[] get(nitro_service service) throws Exception{
hanode obj = new hanode();
hanode[] response = (hanode[])obj.get_resources(service);
return response;
} |
java | public void marshall(GetShardIteratorRequest getShardIteratorRequest, ProtocolMarshaller protocolMarshaller) {
if (getShardIteratorRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getShardIt... |
python | def _fmtos(self):
"""An iterator over formatoption objects
Contains only the formatoption whose keys are in all plotters in this
list"""
plotters = self.plotters
if len(plotters) == 0:
return {}
p0 = plotters[0]
if len(plotters) == 1:
retu... |
java | public final AnnotatedDataset getAnnotatedDataset(String name) {
ANNOTATED_DATASET_PATH_TEMPLATE.validate(name, "getAnnotatedDataset");
GetAnnotatedDatasetRequest request =
GetAnnotatedDatasetRequest.newBuilder().setName(name).build();
return getAnnotatedDataset(request);
} |
java | public static boolean[] hexDigitToBinary(final char hexDigit) {
switch (hexDigit) {
case '0':
return new boolean[] { false, false, false, false };
case '1':
return new boolean[] { true, false, false, false };
case '2':
return new boolean[] { false, tru... |
python | def __add_frozen(self):
"""
Adds _frozen attribute to this instance and all its child configurations.
"""
setattr(self, "_frozen", False)
for attr, val in self.__dict__.items():
if isinstance(val, Config):
val.__add_frozen() |
java | private void correctMergedCell(final Sheet sheet, final RecordOperation recordOperation, final List<CellRangeAddress> mergedRegionList) {
if(recordOperation.isNotExecuteRecordOperation()) {
return;
}
// 操作をしていないセルの範囲の取得
final CellRangeAddress notOperateRange = new Ce... |
python | def main():
"""
script to setup folder structures for AIKIF
and prepare data tables.
"""
print('\n\n /------- AIKIF Installation --------\\')
print(' | s. show current setup |')
print(' | f. setup folder structures |')
print(' | c. create sample data |')
... |
python | def get_client_settings(**kwargs):
"""Parse client settings.
Parses settings from various input methods, preferring earlier values
to later ones. The settings currently come from explicit user arguments,
environmental variables and config files.
:param \\*\\*kwargs: Arguments that are passed i... |
java | protected final XObject executeRelativePathPattern(
XPathContext xctxt, DTM dtm, int currentNode)
throws javax.xml.transform.TransformerException
{
XObject score = NodeTest.SCORE_NONE;
int context = currentNode;
DTMAxisTraverser traverser;
traverser = dtm.getAxisTraverser(m_axi... |
java | private void mergeForceCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
}
} |
java | private String getPacketHeader(final long timeStamp) {
if (header) {
StringBuffer buf = new StringBuffer(dateFormat.format(new Date(timeStamp)));
// RFC 3164 says leading space, not leading zero on days 1-9
if (buf.charAt(4) == '0') {
buf.setCharAt(4, ' ');
}
buf... |
python | def update_location(self, text=''):
"""Update text of location."""
self.text_project_name.setEnabled(self.radio_new_dir.isChecked())
name = self.text_project_name.text().strip()
if name and self.radio_new_dir.isChecked():
path = osp.join(self.location, name)
... |
java | @Override
public <T> T asObject(String string, Class<T> valueType) throws BugError {
// at this point value type is guaranteed to be char or Character
if (string.length() > 1) {
throw new ConverterException("Trying to convert a larger string into a single character.");
}
return (T) (Character) string.... |
python | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image
"""
assert self.image_set_index is not No... |
java | public static final <T extends Calendar> Function<T, LocalTime> calendarToLocalTime(Chronology chronology) {
return FnLocalTime.calendarToLocalTime(chronology);
} |
python | def log(msg, **kwargs):
"""Generic log method. Will prepend timestamp.
Keyword arguments:
system - Name of the system/module
indent - Integer denoting the desired level of indentation
streams - List of streams to output to
stream - Stream to output to (singleton version of stream... |
java | @Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
ScheduledExecutorService executor = getScheduledExecutor();
long initialDelay = startTime.getTime() - System.currentTimeMillis();
try {
return executor.scheduleWithFixedDelay(e... |
python | def flatten(self, l):
"""Turn a list of lists into a list."""
if l == []:
return l
if isinstance(l[0], list):
return self.flatten(l[0]) + self.flatten(l[1:])
return l[:1] + self.flatten(l[1:]) |
python | def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n)) |
python | def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
... |
python | def evaluation_termination(population, num_generations, num_evaluations, args):
"""Return True if the number of function evaluations meets or exceeds a maximum.
This function compares the number of function evaluations that have been
generated with a specified maximum. It returns True if the maximum i... |
java | public DbAttribute[] get_device_attribute_property(String devname, String[] attnames) throws DevFailed {
return databaseDAO.get_device_attribute_property(this, devname, attnames);
} |
python | def _create_cifti_image(bold_file, label_file, annotation_files, gii_files,
volume_target, surface_target, tr):
"""
Generate CIFTI image in target space
Parameters
bold_file : 4D BOLD timeseries
label_file : label atlas
annotation_... |
java | public SimplePathEnumerator enumerate() {
Iterator<Edge> entryOut = cfg.outgoingEdgeIterator(cfg.getEntry());
if (!entryOut.hasNext()) {
throw new IllegalStateException();
}
Edge entryEdge = entryOut.next();
LinkedList<Edge> init = new LinkedList<>();
init.ad... |
java | public static void init(Context context, String apiKey) {
RaygunClient.apiKey = apiKey;
RaygunClient.context = context;
RaygunClient.appContextIdentifier = UUID.randomUUID().toString();
RaygunLogger.d("Configuring Raygun (v"+RaygunSettings.RAYGUN_CLIENT_VERSION+")");
try {
RaygunClient.versi... |
java | public static byte packParametersByte(final int registerWidth, final int registerCountLog2) {
final int widthBits = ((registerWidth - 1) & REGISTER_WIDTH_MASK);
final int countBits = (registerCountLog2 & LOG2_REGISTER_COUNT_MASK);
return (byte)((widthBits << LOG2_REGISTER_COUNT_BITS) | countBits... |
python | def get_field_values_as_list(self,field):
'''
:param str field: The name of the field for which to pull in values.
Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example::
>>> r.get_field_values_as... |
java | public static <T, V, R extends Collection<V>> R collect(
Iterable<T> iterable,
Function<? super T, V> function,
R target,
boolean allowReorderedResult)
{
return FJIterate.collect(
iterable,
function,
target,
... |
python | def file_del(self, key, paths=None):
"""
Deregister a task for file event changes. If paths is None, all
paths assoicated with the task will be deregistered.
"""
if paths is None:
paths = []
for path in self._file_event_map:
if key in self._fi... |
java | public String clean(final Reader cobolReader) throws CleanerException {
if (cobolReader == null) {
throw new CleanerException("COBOL source was null");
}
BufferedReader reader = new BufferedReader(cobolReader);
String line;
StringBuilder cleanedSource = new StringBu... |
java | public final Node pop()
{
m_firstFree--;
Node n = m_map[m_firstFree];
m_map[m_firstFree] = null;
return n;
} |
python | def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt computations or stop debugging
if not self.shellwidget._reading:
self.interrupt_kernel()
else:
self... |
java | public InputStream asInputStream() {
InputStream is = fromStreamOrBufferOrUrl();
if (is != null) return is;
String s = fromStringOrReader();
if (s != null) return streamFrom(s);
throw resourceUnaccessible();
} |
python | def unit_vector(vector, **kwargs):
"""Returns the unit vector of the vector."""
# This also works for a dataframe with columns ['x', 'y', 'z']
# However, the division operation is picky about the shapes
# So, remember input vector shape, cast all up to 2d,
# do the (ugly) conversion, then return uni... |
java | @Override
public boolean imbalanceDetected(LoadImbalance imbalance) {
long min = imbalance.minimumLoad;
long max = imbalance.maximumLoad;
if (min == Long.MIN_VALUE || max == Long.MAX_VALUE) {
return false;
}
long lowerBound = (long) (MIN_MAX_RATIO_MIGRATION_THRES... |
java | public static RectifyCalibrated rectify(GrayU8 origLeft , GrayU8 origRight ,
StereoParameters param ,
GrayU8 rectLeft , GrayU8 rectRight )
{
// Compute rectification
RectifyCalibrated rectifyAlg = RectifyImageOps.createCalibrated();
Se3_F64 leftToRight = param.getRightToLeft().invert(null);... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.