language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Deprecated
private void onStepProgress(Object source)
{
onStartStepProgress(null, source);
// if there is only one step close it and move to the next one
if (this.currentStep.getParent().getChildren().size() == 1) {
this.currentStep = this.currentStep.getParent().nextStep(n... |
java | public SimpleConfiguration orElse(SimpleConfiguration fallback) {
SimpleConfiguration copy = new SimpleConfiguration(this);
for (Map.Entry<String, String> entry : fallback.toMap().entrySet()) {
if (!copy.containsKey(entry.getKey())) {
copy.setProperty(entry.getKey(), entry.getValue());
}
... |
java | @Override
public Object create(ActionParameter argument, Context context, ParameterFactories engine) {
if (argument.getRawType().equals(Context.class)) {
return context;
}
// Check whether we have a ParameterFactory that can handle the creation.
Set<Class> handled = engi... |
python | def check_version(i):
"""
Input: {
version - your version (string)
}
Output: {
return - return code = 0
ok - if 'yes', your CK kernel version is outdated
current_version - your CK kernel version
}
... |
python | def lookup_comments(self, reverse=False):
"Implement as required by parent to lookup comments in file system."
comments = []
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
path = self.thread_id
with open(self.thread_id, 'r', newline='') as fdesc:... |
python | def make_instance(cls, data):
"""Validate the data and create a model instance from the data.
Args:
data (dict): The unserialized data to insert into the new model
instance through it's constructor.
Returns:
peewee.Model|sqlalchemy.Model: The model insta... |
java | public static WebhookEndpoint retrieve(String webhookEndpoint) throws StripeException {
return retrieve(webhookEndpoint, (Map<String, Object>) null, (RequestOptions) null);
} |
java | private String addVersionQualifierToQualifiers(String qualifiers) {
int versionQualifierApiLevel = ResBundle.getVersionQualifierApiLevel(qualifiers);
if (versionQualifierApiLevel == -1) {
if (qualifiers.length() > 0) {
qualifiers += "-";
}
qualifiers +... |
java | protected void log( Throwable t )
{
if( _logger == null )
{
t.printStackTrace();
}
else
{
_logger.warn( "Error running job.", t );
}
} |
python | def update_user_password(new_pwd_user_id, new_password,**kwargs):
"""
Update a user's password
"""
#check_perm(kwargs.get('user_id'), 'edit_user')
try:
user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one()
user_i.password = bcrypt.hashpw(str(new_password).encod... |
java | @Override
protected ObjectAdapter adapterFor(final Object targetObject) {
if(targetObject instanceof OidDto) {
final OidDto oidDto = (OidDto) targetObject;
final Bookmark bookmark = Bookmark.from(oidDto);
final RootOid rootOid = RootOid.create(bookmark);
retur... |
python | def removeSettingsGroup(groupName, settings=None):
""" Removes a group from the persistent settings
"""
logger.debug("Removing settings group: {}".format(groupName))
settings = QtCore.QSettings() if settings is None else settings
settings.remove(groupName) |
python | def create_run(cls, *args, **kwargs):
"""
:return:
a delegator function that calls the ``cls`` constructor whose arguments being
a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns
the object's ``run`` method. By default, a thread wrapping that ``run`` method
... |
java | private void addComplementaryThreadContextConfigurationsTo(ContextServiceImpl contextSvc) {
final boolean trace = TraceComponent.isAnyTracingEnabled();
lock.writeLock().lock();
try {
// Detect and stop infinite recursion from baseContextRef
if (lock.getWriteHoldCount() >... |
java | @Override
public <T> long insertObject(String name, T obj) throws CpoException {
return processUpdateGroup(obj, CpoAdapter.CREATE_GROUP, name, null, null, null);
} |
java | @NullSafe
@Override
public boolean accept(File pathname) {
return (pathname != null && pathname.canExecute() == executable);
} |
java | @Action(name = "Operating System Detector",
outputs = {
@Output(RETURN_RESULT),
@Output(RETURN_CODE),
@Output(OS_FAMILY),
@Output(OS_NAME),
@Output(OS_ARCHITECTURE),
@Output(OS_VERSION),
... |
python | def _clone(self, shallowClone):
"""Retry if clone failed"""
command = ['clone']
switchToBranch = False
if self.supportsBranch and self.branch != 'HEAD':
if self.branch.startswith('refs/'):
# we can't choose this branch from 'git clone' directly; we
... |
java | @SuppressWarnings("unchecked")
protected ResultQueueEntry<T> toResultQueueEntryForEquals(Object obj) {
if (!(obj instanceof ResultQueueEntry) || obj == null) {
return null;
}
ResultQueueEntry<T> other = (ResultQueueEntry<T>) obj;
return type == other.type && getClass() == other.getClass() ? othe... |
java | @Override
@Autowired(required = false)
public void setSamlLogger(SAMLLogger samlLogger) {
Assert.notNull(samlLogger, "SAMLLogger can't be null");
this.samlLogger = samlLogger;
} |
python | def Start(self):
"""Calls the Update() method of a given VFSFile/VFSDirectory object."""
self.Init()
fd = aff4.FACTORY.Open(self.args.vfs_file_urn, mode="rw", token=self.token)
# Account for implicit directories.
if fd.Get(fd.Schema.TYPE) is None:
fd = fd.Upgrade(standard.VFSDirectory)
s... |
java | public static Polygon buffer(Geometry geometry,
SpatialReference spatialReference, double distance) {
double bufferDistance = distance;
OperatorBuffer op = (OperatorBuffer) factory
.getOperator(Operator.Type.Buffer);
Geometry result = op.execute(geometry, spatialReference,
bufferDistance, null);
ret... |
java | public void batchSave(Object... objectsToSave) {
batchWrite(Arrays.asList(objectsToSave), Collections.emptyList(), this.config);
} |
python | def lasio_get(l,
section,
item,
attrib='value',
default=None,
remap=None,
funcs=None):
"""
Grabs, renames and transforms stuff from a lasio object.
Args:
l (lasio): a lasio instance.
section (str): The LAS s... |
java | public double[] homogeneRelativeVector(double[] v) {
assert (v.length == dim);
// TODO: this only works properly when trans[dim][dim] == 1.0, right?
double[] dv = Arrays.copyOf(v, dim + 1);
dv[dim] = 0.0;
return dv;
} |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.BDT__DOC_NAME:
return DOC_NAME_EDEFAULT == null ? docName != null : !DOC_NAME_EDEFAULT.equals(docName);
case AfplibPackage.BDT__RESERVED:
return RESERVED_EDEFAULT == null ? reserved != null : !RESERVED_EDEFAULT.equ... |
python | def split_trailing_comment(line: str) -> str:
"""Takes a line and splits it into two parts (code_part, comment_part)
where code_part is the line up to but not including any trailing
comment (the '!' comment character and subsequent characters
to the end of the line), while comment_part is the trailing c... |
java | public static CmsHistoryVersion fromString(String s) {
List<String> l = CmsStringUtil.splitAsList(s, ":");
if (l.size() == 2) {
Integer ver = null;
try {
ver = Integer.valueOf(l.get(0));
} catch (Exception e) {
//
}
... |
java | public List<ServletMappingType<WebFragmentType<T>>> getAllServletMapping()
{
List<ServletMappingType<WebFragmentType<T>>> list = new ArrayList<ServletMappingType<WebFragmentType<T>>>();
List<Node> nodeList = childNode.get("servlet-mapping");
for(Node node: nodeList)
{
ServletMappingT... |
python | def triples(self, pattern: QueryTriple):
""" Return the triples that match pattern
:param pattern: `(s, p, o)` tuple, with `None` as wild cards
:return: Generator for resulting triples
"""
self.total_calls += 1
if self.graph_name is not None:
gn = "?g" if not... |
java | public Long getToLong() {
if (m_long == null) {
try {
m_long = new Long(Long.parseLong(getToString()));
} catch (NumberFormatException e) {
LOG.info(e.getLocalizedMessage());
}
}
return m_long;
} |
java | private void printInstruction(String instruction) {
System.out.println(StringUtils.repeat("-", instruction.length()));
System.out.println(instruction);
System.out.println(StringUtils.repeat("-", instruction.length()));
} |
java | @Override
public EClass getLongAction() {
if (longActionEClass == null) {
longActionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(33);
}
return longActionEClass;
} |
python | async def close(self):
"""
Close this request, send all data. You can still run other operations in the handler.
"""
if not self._sendHeaders:
self._startResponse()
if self.inputstream is not None:
self.inputstream.close(self.connection.scheduler)
... |
java | @Override
public void write(String text, String contentType) {
assertArgumentNotNull("text", text);
assertArgumentNotNull("contentType", contentType);
doWrite(text, contentType);
} |
python | def load_data(self, pdbid):
"""Loads and parses an XML resource and saves it as a tree if successful"""
f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower())
self.doc = etree.parse(f) |
java | public double addAndGet(double amount) {
long v;
double d;
double n;
long next;
do {
v = value.get();
d = Double.longBitsToDouble(v);
n = d + amount;
next = Double.doubleToLongBits(n);
} while (!value.compareAndSet(v, next));
return n;
} |
java | private Map<String, String> getVariantMap(ResourceBundlesHandler bundlesHandler, String contextPath,
String bundlePath) {
JoinableResourceBundle bundle = bundlesHandler.resolveBundleForPath(bundlePath);
Set<String> variantTypes = bundle.getVariants().keySet();
String variantKey = getVariantKey(contextPath);
... |
java | public static String createSecret() {
Random random = new SecureRandom();
StringBuilder buffer = new StringBuilder(BYTES_SECRET);
for (int i = 0; i < BYTES_SECRET; i++) {
int value = random.nextInt(MAX_CHARACTERS);
if (value < ITERATIONS) {
buffer.append((... |
python | def validate(self, validation_instances, metrics, iteration=None):
'''
Evaluate this model on `validation_instances` during training and
output a report.
:param validation_instances: The data to use to validate the model.
:type validation_instances: list(instance.Instance)
... |
java | public void fatal( final Object message )
{
if( m_delegate.isFatalEnabled() && message != null )
{
m_delegate.fatal( message.toString(), null );
}
} |
python | def hashdata(self, subject):
_data = bytearray()
if isinstance(subject, six.string_types):
subject = subject.encode('charmap')
"""
All signatures are formed by producing a hash over the signature
data, and then using the resulting hash in the signature algorithm.
... |
java | public Object getObject() throws Exception {
if (converterConfigList==null) {
throw new FactoryBeanNotInitializedException("converterConfigList has not been set");
}
ConverterManagerImpl result = new ConverterManagerImpl();
for (ConverterConfig converterConfig : conv... |
java | public static void sendPing(final PooledByteBuffer pooledData, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(pooledData, WebSocketFrameType.PING, wsChannel, callback, null, -1);
} |
java | public static String[] getServiceName(String[] argv, String[] serviceId)
throws IllegalArgumentException {
ArrayList<String> newArgvList = new ArrayList<String>();
for (int i = 0; i < argv.length; i++) {
if ("-service".equals(argv[i])) {
if (i+1 == argv.length ) {
throw new Illega... |
java | public static String updateProperties( String propertiesContent, Map<String,String> keyToNewValue ) {
for( Map.Entry<String,String> entry : keyToNewValue.entrySet()) {
propertiesContent = propertiesContent.replaceFirst(
"(?mi)^\\s*" + entry.getKey() + "\\s*[:=][^\n]*$",
entry.getKey() + " = " + entry.ge... |
python | def get_subject_with_local_validation(jwt_bu64, cert_obj):
"""Validate the JWT and return the subject it contains.
- The JWT is validated by checking that it was signed with a CN certificate.
- The returned subject can be trusted for authz and authn operations.
- Possible validation errors include:
... |
python | def compute_classpath(cls, targets, classpath_products, extra_classpath_tuples, confs):
"""Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
As compute_classpath_entries but expects and ret... |
python | def get_valid_filename(s):
"""
Shamelessly taken from Django.
https://github.com/django/django/blob/master/django/utils/text.py
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remov... |
python | def split_files(files, split_train, split_val, use_test):
"""Splits the files along the provided indices
"""
files_train = files[:split_train]
files_val = files[split_train:split_val] if use_test else files[split_train:]
li = [(files_train, 'train'), (files_val, 'val')]
# optional test folder
... |
java | private double getDepthFromRootPathMap() throws WikiApiException {
int max = 0;
for (List<Integer> path : getRootPathMap().values()) {
if (path.size() > max) {
max = path.size();
}
}
max = max - 1; // depth is measured in nodes, not edges
... |
python | def Nasv(macs,T):
'''
Returns
-------
Na*<sigma v>
for MACS [mb] at T [K].
'''
Na = avogadro_constant
k = boltzmann_constant
vtherm=(2.*k*T/mass_H_atom)**0.5
s = macs*1.e-27
Nasv = s*vtherm*Na
return Nasv |
python | def build_genome_alignment_from_directory(d_name, ref_spec, extensions=None,
index_exts=None,
fail_no_index=False):
"""
build a genome aligment by loading all files in a directory.
Fiel without indexes are loaded immediately; tho... |
python | def run_noise_experiment(num_neurons = 1,
a = 128,
dim = 6000,
test_noise_levels = range(15, 100, 5),
num_samples = 500,
num_dendrites = 500,
dendrite_length = 30,
theta = 8,
num_trials = 100):
"""
Tests the impa... |
java | public static JsonNode getValue(JsonNode node, String dPath) {
String[] paths = splitDpath(dPath);
Object result = node;
for (String path : paths) {
result = extractValue(result, path);
}
if (result instanceof POJONode) {
result = extractValue((POJONode) r... |
python | def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
"""
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
... |
python | def modification_time(self):
"""dfdatetime.DateTimeValues: modification time or None if not available."""
timestamp = getattr(
self._cpio_archive_file_entry, 'modification_time', None)
if timestamp is None:
return None
return dfdatetime_posix_time.PosixTime(timestamp=timestamp) |
java | @Override
public boolean hasHttpsEndpoint(String serviceName) {
if (!isServiceSupported(serviceName)) return false;
return getEndpoint(serviceName).hasHttpsSupport();
} |
java | public final void putDouble(Object parent, long offset, double value) {
THE_UNSAFE.putDouble(parent, offset, value);
} |
java | public EEnum getIfcElectricCurrentEnum() {
if (ifcElectricCurrentEnumEEnum == null) {
ifcElectricCurrentEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(823);
}
return ifcElectricCurrentEnumEEnum;
} |
python | def convert_conelp(c, G, h, dims, A = None, b = None, **kwargs):
"""
Applies the clique conversion method of Fukuda et al. to the positive semidefinite blocks of a cone LP.
:param c: :py:class:`matrix`
:param G: :py:class:`spmatrix`
:param h: :py:clas... |
java | public ListParameterization addFlag(OptionID optionid) {
parameters.add(new ParameterPair(optionid, Flag.SET));
return this;
} |
java | public String getDate(Date date) {
return CmsDateUtil.getDate(date, DateFormat.SHORT, m_locale);
} |
python | def get(cls, uuid):
"""Return a `Resource` instance of this class identified by
the given code or UUID.
Only `Resource` classes with specified `member_path` attributes
can be directly requested with this method.
"""
if not uuid:
raise ValueError("get must ha... |
python | def _set_choices(self, value):
"""
Also update the widget's choices.
"""
super(LazyChoicesMixin, self)._set_choices(value)
self.widget.choices = value |
python | def comment(self, comment):
""" Add a :class:`Comment <pypump.models.comment.Comment>`
to the object.
:param comment: A :class:`Comment <pypump.models.comment.Comment>`
instance, text content is also accepted.
Example:
>>> anote.comment(pump.Comment('I agree!'))... |
python | def _get_titles(self, limit):
"""
The file processed here is of the format:
#NBK_id GR_shortname OMIM
NBK1103 trimethylaminuria 136132
NBK1103 trimethylaminuria 602079
NBK1104 cdls 122470
Where each of the rows represents a mapping between
... |
java | protected Object[] createParams(NodeId id, Object p, boolean before) {
// Create the key
List<Object> key = new ArrayList<Object>();
if (getStorageModel() == SM_BINARY_KEYS) {
key.add(id.getRawBytes());
} else {
key.add(id.getMostSignificantBits());
k... |
python | def update(self, table, data_list, matched_field=None, return_cols='id'):
"""
Create a bulk insert statement which is much faster (~2x in tests with 10k & 100k rows and 4 cols)
for inserting data then executemany()
TODO: Is there a limit of length the query can be? If so handle it.
... |
java | protected JsonDeserializer<Object> _findRootDeserializer(DeserializationConfig cfg, JavaType valueType)
throws JsonMappingException {
// Sanity check: must have actual type...
if (valueType == null) {
throw new JsonMappingException("No value type configured for ObjectReader");
... |
python | def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60,
max_fails=5):
"""
This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better c... |
python | def stringify_values(data):
"""Coerce iterable values to 'val1,val2,valN'
Example:
fields=['nickname', 'city', 'can_see_all_posts']
--> fields='nickname,city,can_see_all_posts'
:param data: dict
:return: converted values dict
"""
if not isinstance(data, dict):
raise Val... |
java | public static Resource getFile(Config config, Resource directory, String path, short type) {
path = replacePlaceholder(path, config);
if (!StringUtil.isEmpty(path, true)) {
Resource file = getFile(directory.getRealResource(path), type);
if (file != null) return file;
file = getFile(config.getResource(... |
java | public Observable<OperationStatusResponseInner> beginReimageAllAsync(String resourceGroupName, String vmScaleSetName) {
return beginReimageAllWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() {
@Ov... |
python | def get_recent_matches(self, card_type="micro_card"):
"""
Calling the Recent Matches API.
Arg:
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card.
Return:
json data
"""
recent_matches_url = self.api... |
python | def delete(self, href=None):
"""Delete an item.
When ``href`` is ``None``, delete the collection.
"""
if self.is_fake:
return
if href is None:
self.collection.delete()
return
item = self.get(href)
if item is None:
... |
python | def _find_limit_hosted_zone(self):
"""
Calculate the max recordsets and vpc associations and the current values
per hosted zone
"""
for limit_type in [self.MAX_RRSETS_BY_ZONE,
self.MAX_VPCS_ASSOCIATED_BY_ZONE]:
self.limits[limit_type["name"]... |
java | public static void main(String[] args) {
try {
TreeFactory tf = new LabeledScoredTreeFactory();
Reader r = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));
TreeReader tr = new PennTreeReader(r, tf);
Tree t = tr.readTree();
while (t != null) {
... |
python | def _set_property_dict_item(obj, prop, key, value):
''' Sets the dict item key of the attr from obj.
Basicaly it does getattr(obj, prop)[key] = value.
For the disk device we added some checks to make
device changes on the CLI saver.
'''
attr = getattr(obj, prop)
if prop == 'de... |
python | def MakeDeployableBinary(self, template_path, output_path):
"""This will add the config to the client template and create a .rpm."""
rpmbuild_binary = "/usr/bin/rpmbuild"
if not os.path.exists(rpmbuild_binary):
logging.error("rpmbuild not found, unable to repack client.")
return
with utils... |
python | def get_empty_results(self):
"""
Because the base result type is different depending on the return structure
(e.g. list for flat, dict for object), `get_result_type` initials the
`results` variable to the proper type
"""
assert self.result_type is not None, (
... |
python | def set_background_corpus(self, background):
'''
Parameters
----------
background
'''
if issubclass(type(background), TermDocMatrixWithoutCategories):
self._background_corpus = pd.DataFrame(background
.get_te... |
java | @Nonnull
public static <T1, T2> LToLongBiFunction<T1, T2> toLongBiFunctionFrom(Consumer<LToLongBiFunctionBuilder<T1, T2>> buildingFunction) {
LToLongBiFunctionBuilder builder = new LToLongBiFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
java | public static boolean delete(String tableName, String primaryKey, Record record) {
return MAIN.delete(tableName, primaryKey, record);
} |
python | def rsolve(A, b, epsilon=_epsilon):
r"""Robust solve for the linear equations.
Args:
A (array_like): Coefficient matrix.
b (array_like): Ordinate values.
Returns:
:class:`numpy.ndarray`: Solution ``x``.
"""
A = asarray(A, float)
b = asarray(b, float)
if A.shape[0] =... |
java | @Inject
public void setFreemarkerManager(FreemarkerManager mgr) {
this.freemarkerManager = mgr;
if (null != freemarkerManager) {
Configuration old = freemarkerManager.getConfig();
if (null != old) {
config = (Configuration) freemarkerManager.getConfig().clone();
config.setTemplateL... |
java | private void writeAttributeTypes(String name, FieldType[] types) throws IOException
{
m_writer.writeStartObject(name);
for (FieldType field : types)
{
m_writer.writeNameValuePair(field.name().toLowerCase(), field.getDataType().getValue());
}
m_writer.writeEndObject();
} |
python | def main():
"""Run along little fella."""
parser = ArgumentParser()
subs = parser.add_subparsers(dest='cmd')
setup_parser = subs.add_parser('setup')
setup_parser.add_argument('-r', '--region', default=PRIMARY_REGION,
help='AWS region to install all services')
setup_... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.RESOURCE_SECTION_NUMBER__RES_SNUM:
return getResSNum();
}
return super.eGet(featureID, resolve, coreType);
} |
python | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret
# Max si... |
java | public void run()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "run");
UniqueKeyGenerator generator = null;
while (_running)
{
synchronized (_asyncQ)
{
// Do we have anything to do?
while... |
python | def raw_input(prompt=""):
"""raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline befo... |
python | def _is_valid_dkim(self, value):
"""Check if value is a valid DKIM"""
validator_dict = {'h': lambda val: val in ['sha1', 'sha256'],
's': lambda val: val in ['*', 'email'],
't': lambda val: val in ['y', 's'],
'v': lambda val: v... |
python | def _get_model_fields(self, model, prefix=_field_prefix):
"""
Find all fields of given model that are not default models.
"""
fields = list()
for field_name, field in model()._ordered_fields:
# Filter the default fields
if field_name not in getattr(model, ... |
java | @Override
public void evaluate(DoubleSolution solution) {
int numberOfVariables = getNumberOfVariables() ;
double[] f = new double[getNumberOfObjectives()];
double[] x = new double[numberOfVariables] ;
for (int i = 0; i < numberOfVariables; i++) {
x[i] = solution.getVariableValue(i) ;
}
... |
java | public static void closeFileStream(InputStream inputStream, String filePath){
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
LOG.error("close file {} occur an IOExcpetion {}", filePath, e);
}
} |
java | public static void convertImplicitToExplicitHydrogens(IAtomContainer atomContainer) {
List<IAtom> hydrogens = new ArrayList<IAtom>();
List<IBond> newBonds = new ArrayList<IBond>();
// store a single explicit hydrogen of each original neighbor
Map<IAtom, IAtom> hNeighbor = Maps.newHashMa... |
python | def execute_command(self, *args, **options):
"""
Execute a command and return a parsed response.
"""
pool = self.connection_pool
command_name = args[0]
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
... |
python | def do_some_expensive_things(number):
"""
Perform one expensive computation cooperatively with any
other iterator passed into twisted's cooperate, then
use it's result to pass into the second computation.
:param number:
:return:
"""
result = yield batch_accumulate(1000, expensive(numb... |
java | @Deprecated
protected boolean isRetriableException(Throwable e) {
if (getRetryHandler() != null) {
return getRetryHandler().isRetriableException(e, true);
}
return false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.