language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def clean(self):
"""
>>> import django.forms
>>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
... some_field = django.forms.CharField()
>>>
>>> form = MyForm({'some_field': ' a weird value '})
>>> assert form.is_valid()
>>> assert form.cl... |
python | def select2_modelform_meta(model,
meta_fields=None,
widgets=None,
attrs=None,
**kwargs):
"""
Return `Meta` class with Select2-enabled widgets for fields
with choices (e.g. ForeignKey, CharField, etc)... |
java | @SuppressWarnings("rawtypes")
protected PojoPathFunction getFunction(String functionName, PojoPathContext context) throws ObjectNotFoundException {
PojoPathFunction function = null;
// context overrides functions...
PojoPathFunctionManager manager = context.getAdditionalFunctionManager();
if (manager... |
python | def handle_qbytearray(obj, encoding):
"""Qt/Python2/3 compatibility helper."""
if isinstance(obj, QByteArray):
obj = obj.data()
return to_text_string(obj, encoding=encoding) |
python | def unique_iter(seq):
"""
See http://www.peterbe.com/plog/uniqifiers-benchmark
Originally f8 written by Dave Kirby
"""
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] |
python | def karma(nick, rest):
"Return or change the karma value for some(one|thing)"
karmee = rest.strip('++').strip('--').strip('~~')
if '++' in rest:
Karma.store.change(karmee, 1)
elif '--' in rest:
Karma.store.change(karmee, -1)
elif '~~' in rest:
change = random.choice([-1, 0, 1])
Karma.store.change(karmee, c... |
python | def relation(x_start, x_end, y_start, y_end):
"""
Returns the relation between two intervals.
:param int x_start: The start point of the first interval.
:param int x_end: The end point of the first interval.
:param int y_start: The start point of the second interval.
:pa... |
python | def dict_merge(a, b):
"""
Recursively merge dicts.
recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
@see http://www.xormedia.com/rec... |
java | public static boolean isEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(value.charAt(i)) == false)) {
return false;
}
}
return true;
} |
python | def GE(classical_reg1, classical_reg2, classical_reg3):
"""
Produce an GE instruction.
:param classical_reg1: Memory address to which to store the comparison result.
:param classical_reg2: Left comparison operand.
:param classical_reg3: Right comparison operand.
:return: A ClassicalGreaterEqual... |
java | public void setLicenseType(com.google.api.ads.admanager.axis.v201811.LicenseType licenseType) {
this.licenseType = licenseType;
} |
python | def close(self):
"""Close all connections
"""
keys = set(self._conns.keys())
for key in keys:
self.stop_socket(key)
self._conns = {} |
python | def calc_csd(self):
""" Sum all the CSD contributions from every layer.
"""
CSDarray = np.array([])
CSDdict = {}
i = 0
for y in self.y:
fil = os.path.join(self.populations_path,
self.output_file.format(y, 'CSD.h5'))
... |
java | void set_composite_vector()
{
composite_.clear();
for (Document<K> document : documents_)
{
composite_.add_vector(document.feature());
}
} |
python | def get_reserved_resources(role=None):
""" resource types from state summary include: reserved_resources
:param role: the name of the role if for reserved and if None all reserved
:type role: str
:return: resources(cpu,mem)
:rtype: Resources
"""
rtype = 'reserved_resources'
cpus = 0.0
... |
java | @Override
public List<IScan> parse(LCMSDataSubset subset) throws FileParsingException {
I idx = fetchIndex(); // make sure, that the index is parsed
if (idx.getMapByNum().isEmpty()) {
// if the index was empty - there's nothing to parse
return Collections.emptyList();
}
LCMSRunInfo inf = f... |
java | @PostConstruct
public void initialize() {
final IRI root = rdf.createIRI(TRELLIS_DATA_PREFIX);
final IRI rootAuth = rdf.createIRI(TRELLIS_DATA_PREFIX + "#auth");
try (final TrellisDataset dataset = TrellisDataset.createDataset()) {
dataset.add(rdf.createQuad(Trellis.PreferAccessC... |
python | def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
show_link_info = E... |
java | private void addClickHandlerToCheckBox(final CmsCheckBox check, final Widget unzipWidget, final CmsFileInfo file) {
check.addClickHandler(new ClickHandler() {
/**
* @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)
*/
... |
java | public void syntaxError(String state, String event, List<String> legalEvents, String uri, Integer line) {
formatter.syntaxError(state, event, legalEvents, uri, line);
} |
python | def to_ipv6(key):
"""Get IPv6 address from a public key."""
if key[-2:] != '.k':
raise ValueError('Key does not end with .k')
key_bytes = base32.decode(key[:-2])
hash_one = sha512(key_bytes).digest()
hash_two = sha512(hash_one).hexdigest()
return ':'.join([hash_two[i:i+4] for i in ran... |
python | def generate_categories():
"""Generates the categories JSON data file from the unicode specification.
:return: True for success, raises otherwise.
:rtype: bool
"""
# inspired by https://gist.github.com/anonymous/2204527
code_points_ranges = []
iso_15924_aliases = []
categories = []
... |
python | def importFile(self, srcUrl, sharedFileName=None, hardlink=False):
"""
Imports the file at the given URL into job store. The ID of the newly imported file is
returned. If the name of a shared file name is provided, the file will be imported as
such and None is returned.
Currentl... |
python | def save(self, *args, **kwargs):
"""
BUG: Django save-the-change, which all oTree models inherit from,
doesn't recognize changes to JSONField properties. So saving the model
won't trigger a database save. This is a hack, but fixes it so any
JSONFields get updated every save. oTre... |
java | public void addCondition( Condition condition, String transitionName ){
conditions.add( Pair.of( condition, transitionName ) );
} |
java | @Override
public void close() throws IOException
{
if (!_closed) {
_closed = true;
_nodeCursor = null;
_currToken = null;
}
} |
python | def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]):
'''
PLots C/O surface number fraction
'''
if len(t0_model)==0:
t0_model = len(self.runs_H5_surf)*[0]
plt.figure(fig)
... |
python | def to_next_bank(self):
"""
Change the current :class:`Bank` for the next bank. If the current
bank is the last, the current bank is will be the first bank.
The current pedalboard will be the first pedalboard of the new current bank
**if it contains any pedalboard**, else will b... |
java | private static <X extends CopyableValue<X>> CopyableValueSerializer<X> createCopyableValueSerializer(Class<X> clazz) {
return new CopyableValueSerializer<X>(clazz);
} |
java | public boolean recordConstancy() {
if (!currentInfo.hasConstAnnotation()) {
currentInfo.setConstant(true);
populated = true;
return true;
} else {
return false;
}
} |
java | @SuppressWarnings("unchecked")
protected Map<String, Collection<AttributeBean>> getAttributeMap(EvaluationCtx eval) throws URISyntaxException {
final URI defaultCategoryURI = SUBJECT_CATEGORY_DEFAULT;
Map<String, String> im = null;
Map<String, Collection<AttributeBean>> attributeMap =
... |
python | def calibrate(self, data, calibration):
"""Calibrate the data"""
tic = datetime.now()
if calibration == 'counts':
return data
if calibration in ['radiance', 'reflectance', 'brightness_temperature']:
data = self.convert_to_radiance(data)
if calibration ==... |
python | def list_nodes_full(**kwargs):
'''
Return all data on nodes
'''
nodes = _query('server/list')
ret = {}
for node in nodes:
name = nodes[node]['label']
ret[name] = nodes[node].copy()
ret[name]['id'] = node
ret[name]['image'] = nodes[node]['os']
ret[name]['s... |
python | def user(name, id='', user='', priv='', password='', status='active'):
'''
Ensures that a user is configured on the device. Due to being unable to
verify the user password. This is a forced operation.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
id(int): The us... |
java | @Override
public java.util.concurrent.Future<SetQueueAttributesResult> setQueueAttributesAsync(String queueUrl, java.util.Map<String, String> attributes,
com.amazonaws.handlers.AsyncHandler<SetQueueAttributesRequest, SetQueueAttributesResult> asyncHandler) {
return setQueueAttributesAsync(new S... |
python | def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None,
drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None,
pad_idx:int=1) -> nn.Module:
"Create a text classifier from `arch` and it... |
python | def table(self, table):
"""Returns the provided Spark SQL table as a L{DataFrame}
Parameters
----------
table: string
The name of the Spark SQL table to turn into a L{DataFrame}
Returns
-------
Sparkling Pandas DataFrame.
"""
return Dat... |
java | public int getIntHeader(String name)
{
if (_header != null)
{
int headerVal = _header.getIntHeader(name);
if (headerVal != -1)
return headerVal;
}
if (this.headerTable != null)
{
int i = 0;
for (Object obj : headerTable[0])
{
String strVal = (String) o... |
python | def endSubscription(self, subscriber):
"""
Unregister a live subscription.
"""
self._reqId2Contract.pop(subscriber.reqId, None)
self.reqId2Subscriber.pop(subscriber.reqId, None) |
java | private static StackTraceElement normalizeClassName(final StackTraceElement element) {
String className = element.getClassName();
int dollarIndex = className.indexOf("$");
if (dollarIndex == -1) {
return element;
} else {
className = stripAnonymousPart(className);
return new StackTraceElement(className... |
java | public int dimensions(Type t) {
int result = 0;
while (t.hasTag(ARRAY)) {
result++;
t = elemtype(t);
}
return result;
} |
java | public int compareTo(TextIntWritable o) {
int c = t.compareTo(o.t);
if (c != 0)
return c;
return position - o.position;
} |
java | public void saveTo(File propertyFile) throws IOException {
Properties props = new Properties();
props.put("username", username);
props.put("key", accessKey);
FileOutputStream out = new FileOutputStream(propertyFile);
try {
props.store(out, "Sauce OnDemand access crede... |
python | def from_json(json_data):
"""
Returns a pyalveo.OAuth2 given a json string built from the oauth.to_json() method.
"""
#If we have a string, then decode it, otherwise assume it's already decoded
if isinstance(json_data, str):
data = json.loads(json_data)
el... |
java | @Override
protected List<Resource> prepareTreeItems(ResourceHandle resource, List<Resource> items) {
if (!nodesConfig.getOrderableNodesFilter().accept(resource)) {
Collections.sort(items, new Comparator<Resource>() {
@Override
public int compare(Resource r1, Resou... |
java | public static HashMap<String, String> resolveIds(final TSDB tsdb,
final ArrayList<byte[]> tags)
throws NoSuchUniqueId {
try {
return resolveIdsAsync(tsdb, tags).joinUninterruptibly();
} catch (NoSuchUniqueId e) {
throw e;
} catch (DeferredGroupExce... |
python | async def Prune(self, max_history_mb, max_history_time):
'''
max_history_mb : int
max_history_time : int
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='ActionPruner',
request='Prune',
... |
java | public FieldPresenceEnvelope getFieldPresence(Long startDate, Long endDate, String interval, String sdid, String fieldPresence) throws ApiException {
ApiResponse<FieldPresenceEnvelope> resp = getFieldPresenceWithHttpInfo(startDate, endDate, interval, sdid, fieldPresence);
return resp.getData();
} |
java | @Override
public IssueResponse issue(String CorpNum, MgtKeyType KeyType, String MgtKey,
String Memo) throws PopbillException {
return issue(CorpNum, KeyType, MgtKey, Memo, null);
} |
python | def enable_directory_service(self, check_peer=False):
"""Enable the directory service.
:param check_peer: If True, enables server authenticity
enforcement. If False, enables directory
service integration.
:type check_peer: bool, optional
... |
python | def sort(self):
"""
Sort the tribe, sorts by template name.
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... Template(name='a')])
>>> tribe.sort()
Tribe of 3 templates
>>> tribe[0] # do... |
python | def filter_that(self, criteria, data):
'''
this method just use the module 're' to check if the data contain
the string to find
'''
import re
prog = re.compile(criteria)
return True if prog.match(data) else False |
java | List<Expression> parseArrayValueList( IType componentType )
{
while( componentType instanceof TypeVariableType )
{
componentType = ((TypeVariableType)componentType).getBoundingType();
}
List<Expression> valueExpressions = new ArrayList<>();
do
{
parseExpression( new ContextType( co... |
python | def _PrintEnums(proto_printer, enum_types):
"""Print all enums to the given proto_printer."""
enum_types = sorted(enum_types, key=operator.attrgetter('name'))
for enum_type in enum_types:
proto_printer.PrintEnum(enum_type) |
java | public double[] map( Map<String, Double> row, double data[] ) {
String[] colNames = getNames();
for( int i=0; i<colNames.length-1; i++ ) {
Double d = row.get(colNames[i]);
data[i] = d==null ? Double.NaN : d;
}
return data;
} |
java | public int[] getSelectedComponents ()
{
int[] values = new int[_selected.size()];
Iterator<Integer> iter = _selected.values().iterator();
for (int ii = 0; iter.hasNext(); ii++) {
values[ii] = iter.next().intValue();
}
return values;
} |
java | private DefiningClassLoader getQueryClassLoader(CubeClassLoaderCache.Key key) {
if (classLoaderCache == null)
return classLoader;
return classLoaderCache.getOrCreate(key);
} |
python | def new_transfer_transaction(self, asset: str, b58_from_address: str, b58_to_address: str, amount: int,
b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction:
"""
This interface is used to generate a Transaction object for transfer.
:param asset... |
python | def _order_antisense_column(cov_file, min_reads):
"""
Move counts to score columns in bed file
"""
new_cov = op.join(op.dirname(cov_file), 'feat_antisense.txt')
with open(cov_file) as in_handle:
with open(new_cov, 'w') as out_handle:
print("name\tantisense", file=out_handle, end=... |
java | public void addImplicitHydrogens(IAtomContainer container, IAtom atom) throws CDKException {
if (atom.getAtomTypeName() == null) throw new CDKException("IAtom is not typed! " + atom.getSymbol());
if ("X".equals(atom.getAtomTypeName())) {
if (atom.getImplicitHydrogenCount() == null) atom.set... |
java | public static String ipV6Address() {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535)));
sb.append(":");
sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535)));
sb.append(":");... |
java | public static byte[] longToBytes(long rmid)
{
return new byte[] { (byte)(rmid>>56), (byte)(rmid>>48), (byte)(rmid>>40), (byte)(rmid>>32),
(byte)(rmid>>24), (byte)(rmid>>16), (byte)(rmid>>8), (byte)(rmid)};
} |
python | def create_cfg_segment(filename, filecontent, description, auth, url):
"""
Takes a str into var filecontent which represents the entire content of a configuration
segment, or partial configuration file. Takes a str into var description which represents the
description of the configuration segment
:p... |
java | public static MavenRemoteRepository createRemoteRepository(final String id, final String url, final String layout)
throws IllegalArgumentException {
try {
return createRemoteRepository(id, new URL(url), layout);
}
catch (MalformedURLException e) {
throw new Il... |
python | def join_paths(*paths, **kwargs):
"""
Join multiple paths together and return the absolute path of them. If 'safe'
is specified, this function will 'clean' the path with the 'safe_path'
function. This will clean root decelerations from the path
after the first item.
Would like to do 'safe=False... |
java | public static String getEventDateVar(String event, String var) {
var = var.toLowerCase();
if (event == null || var.endsWith("date") || var.endsWith("dat")) return var;
if (event.equals("planting")) {
var = "pdate";
} else if (event.equals("irrigation")) {
var = "i... |
java | protected CmsAlias internalReadAlias(ResultSet resultset) throws SQLException {
String siteRoot = resultset.getString(1);
String path = resultset.getString(2);
int mode = resultset.getInt(3);
String structId = resultset.getString(4);
return new CmsAlias(new CmsUUID(structId), si... |
python | def match(tgt, opts=None):
'''
Matches based on range cluster
'''
if not opts:
opts = __opts__
if HAS_RANGE:
range_ = seco.range.Range(opts['range_server'])
try:
return opts['grains']['fqdn'] in range_.expand(tgt)
except seco.range.RangeException as exc:
... |
java | public ServiceCall<RecognitionJob> createJob(CreateJobOptions createJobOptions) {
Validator.notNull(createJobOptions, "createJobOptions cannot be null");
String[] pathSegments = { "v1/recognitions" };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));... |
python | def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False):
"""以字典形式返回分级B数据
:param fields:利率范围,形如['+3.0%', '6.0%']
:param min_volume:最小交易量,单位万元
:param min_discount:最小折价率, 单位%
:param forever: 是否选择永续品种,默认 False
"""
if fields is None:
field... |
java | @Override
public void run() throws Exception {
setActiveMigration();
try {
doRun();
} catch (Throwable t) {
logMigrationFailure(t);
failureReason = t;
} finally {
onMigrationComplete();
if (!success) {
onExe... |
java | public void marshall(PurchaseProvisionedCapacityRequest purchaseProvisionedCapacityRequest, ProtocolMarshaller protocolMarshaller) {
if (purchaseProvisionedCapacityRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
proto... |
java | protected void notifyObservers (final Name username, final boolean muted)
{
_observers.apply(new ObserverList.ObserverOp<MuteObserver>() {
public boolean apply (MuteObserver observer) {
observer.muteChanged(username, muted);
return true;
}
});
... |
python | def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False):
"""Return a dict of { name => Completions } for the given tuple node.
Enumerates all keys that are in scope in a given tuple. The node
part of the tuple may be None, in case the binding is a built-in.
"""
with util.LogTime('enu... |
java | public static OutputMapping createOutputMapping( Element outputElement ){
if( outputElement == null ){
return null;
}
switch( outputElement.getType() ) {
case VARIABLE:
return new ValueMapping( outputElement.getString( 0 ) );
case VARIABLES:
... |
java | static String countDuplicatesAndAddTypeInfo(Iterable<?> itemsIterable) {
Collection<?> items = iterableToCollection(itemsIterable);
Optional<String> homogeneousTypeName = getHomogeneousTypeName(items);
return homogeneousTypeName.isPresent()
? lenientFormat("%s (%s)", countDuplicates(items), homogen... |
java | private static int getDeterministicAssignment(double[] distribution) {
int assignment = -1;
for (int i = 0; i < distribution.length; i++) {
if (distribution[i] == 1.0) {
if (assignment == -1) assignment = i;
else return -1;
} else if (distribution[i] != 0.0) return -1;
}
retu... |
java | public boolean outgoingEdgesAreSlowerByFactor(double factor) {
double tmpSpeed = getSpeed(currentEdge);
double pathSpeed = getSpeed(prevEdge);
// Speed-Change on the path indicates, that we change road types, show instruction
if (pathSpeed != tmpSpeed || pathSpeed < 1) {
ret... |
python | def fwdl_status_output_fwdl_entries_blade_slot(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output,... |
python | def make_config(path):
"""Creates a config file.
Attempts to load data from legacy config files if they exist.
"""
apps, user = load_legacy_config()
apps = {a.instance: a._asdict() for a in apps}
users = {user_id(user): user._asdict()} if user else {}
active_user = user_id(user) if user el... |
python | def blockSignals(self, state):
"""
Sets whether or not updates will be enabled.
:param state | <bool>
"""
super(XGanttWidget, self).blockSignals(state)
self.treeWidget().blockSignals(state)
self.viewWidget().blockSignals(state) |
python | def set(self, varname, value, idx=0, units=None):
'''set a variable value'''
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
if idx >= self.mapping.vars[varname].arraylength:
raise fgFDMError('index of %s beyond end of array idx=%u a... |
java | public void expectMax(String name, double maxLength) {
expectMax(name, maxLength, messages.get(Validation.MAX_KEY.name(), name, maxLength));
} |
java | public void setDelHints(String delHints) {
if (delHints == null || delHints.isEmpty()) {
throw new IllegalArgumentException("DelHints is empty");
}
this.delHints = delHints;
} |
java | public void handleStateEvent(String callbackKey) {
if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {
((StateEventHandler) handlers.get(callbackKey)).handle();
} else {
System.err.println("Error in handle: " + callbackKey + " for st... |
python | def daisy_chain_graph(self):
""" Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self. """
g = networkx.DiGraph()
for x in self.get_monomers():
for h in x.hole:
g.add_edge(x.knob, h)
return g |
java | @Override
public ModifyVpcTenancyResult modifyVpcTenancy(ModifyVpcTenancyRequest request) {
request = beforeClientExecution(request);
return executeModifyVpcTenancy(request);
} |
python | def range_mac(mac_start, mac_end, step=1):
"""Iterate over mac addresses (given as string)."""
start = int(EUI(mac_start))
end = int(EUI(mac_end))
for i_mac in range(start, end, step):
mac = EUI(int(EUI(i_mac)) + 1)
ip = ['10'] + [str(int(i, 2)) for i in mac.bits().split('-')[-3:]]
... |
java | private List<OntologyTermSynonym> createSynonyms(OWLClass ontologyTerm) {
return loader
.getSynonyms(ontologyTerm)
.stream()
.map(this::createSynonym)
.collect(Collectors.toList());
} |
java | private String check() throws InvalidExpressionException {
expression = expression.replaceAll("\\s","");
expression = expression.toLowerCase();
String var = "";
if(expression.length() == 0) {
throw new InvalidExpressionException("Empty Expression");
}
if(!e... |
python | def formatted_str(self, format):
"""Return formatted str.
:param format: one of 'json', 'csv' are supported
"""
assert(format in ('json', 'csv'))
ret_str_list = []
for rec in self._records:
if format == 'json':
ret_str_list.append('{')
... |
python | def today(self, symbol):
"""
GET /today/:symbol
curl "https://api.bitfinex.com/v1/today/btcusd"
{"low":"550.09","high":"572.2398","volume":"7305.33119836"}
"""
data = self._get(self.url_for(PATH_TODAY, (symbol)))
# convert all values to floats
return se... |
java | public synchronized void noGuessesInStream() throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "noGuessesInStream");
if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "oldContainesGuesses:" + cont... |
java | private long getLongInternal(final String key, final long defaultValue) {
long retVal = defaultValue;
try {
synchronized (this.confData) {
if (this.confData.containsKey(key)) {
retVal = Long.parseLong(this.confData.get(key));
}
}
} catch (NumberFormatException e) {
if (LOG.isDebugEnabled... |
java | private boolean loadMore(int available)
throws IOException
{
mByteCount += (mByteBufferEnd - available);
// Bytes that need to be moved to the beginning of buffer?
if (available > 0) {
/* 11-Nov-2008, TSa: can only move if we own the buffer; otherwise
* we are stuck wit... |
python | def tournament(self,individuals,tourn_size, num_selections=None):
"""conducts tournament selection of size tourn_size"""
winners = []
locs = []
if num_selections is None:
num_selections = len(individuals)
for i in np.arange(num_selections):
# sample pool ... |
java | public final double[] getDpiSuggestions() {
if (this.dpiSuggestions == null) {
List<Double> list = new ArrayList<>();
for (double suggestion: DEFAULT_DPI_VALUES) {
if (suggestion <= this.maxDpi) {
list.add(suggestion);
}
}
... |
java | @SuppressWarnings({"deprecation", "WeakerAccess"})
protected boolean isFlagPresent(final AttributeAccess.Flag flag) {
if (flags == null) { return false; }
for (AttributeAccess.Flag f : flags) {
if (f.equals(flag)) { return true; }
}
return false;
} |
python | def frames_to_tc(self, frames):
"""Converts frames back to timecode
:returns str: the string representation of the current time code
"""
if frames == 0:
return 0, 0, 0, 0
ffps = float(self._framerate)
if self.drop_frame:
# Number of frames to d... |
java | public static <T> TypeSerializer<T> tryReadSerializer(DataInputView in, ClassLoader userCodeClassLoader) throws IOException {
return tryReadSerializer(in, userCodeClassLoader, false);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.