language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public final void setInstructionObserverThreshold(int threshold)
{
if (sealed) onSealedMutation();
if (threshold < 0) throw new IllegalArgumentException();
instructionThreshold = threshold;
setGenerateObserverCount(threshold > 0);
} |
java | @SuppressWarnings("resource")
public static Table getTableMeta(DataSource ds, String tableName) {
final Table table = Table.create(tableName);
Connection conn = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
final DatabaseMetaData metaData = conn.getMetaData();
// 获得主键
rs = me... |
java | private SherdogBaseObject getEvent(Element td) {
Element link = td.select("a").get(0);
SherdogBaseObject event = new SherdogBaseObject();
event.setName(link.html().replaceAll("<span itemprop=\"award\">|</span>", ""));
event.setSherdogUrl(link.attr("abs:href"));
return event;
... |
java | protected static LazyNode readFromBuffer(byte[] raw){
ByteBuffer buf=ByteBuffer.wrap(raw);
return readFromBuffer(buf);
} |
java | public static void addDatatablesResourceIfNecessary(String defaultFilename, String type) {
boolean loadDatatables = shouldLibraryBeLoaded(P_GET_DATATABLE_FROM_CDN, true);
// Do we have to add datatables.min.{css|js}, or are the resources already there?
FacesContext context = FacesContext.getCurrentInstance();
U... |
java | public static Map<String, Object> parseModelConfig(String modelJson, String modelYaml)
throws IOException, InvalidKerasConfigurationException {
Map<String, Object> modelConfig;
if (modelJson != null)
modelConfig = parseJsonString(modelJson);
else if (modelYaml != null)
... |
python | def setup(self):
"""Initialize filter just before it will be used."""
super(CleanCSSFilter, self).setup()
self.root = current_app.config.get('COLLECT_STATIC_ROOT') |
java | public static nsmode get(nitro_service service) throws Exception{
nsmode obj = new nsmode();
nsmode[] response = (nsmode[])obj.get_resources(service);
return response[0];
} |
python | def extend(self, expire=None):
"""Extends expiration time of the lock.
:param expire:
New expiration time. If ``None`` - `expire` provided during
lock initialization will be taken.
"""
if expire is None:
if self._expire is not None:
ex... |
java | public void writeTo(WritableByteChannel channel) throws IOException {
for (ByteBuffer buffer : toDirectByteBuffers()) {
channel.write(buffer);
}
} |
java | public FluentSelect deselectByValue(final String value) {
executeAndWrapReThrowIfNeeded(new DeselectByValue(value), Context.singular(context, "deselectByValue", null, value), true);
return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundExceptio... |
python | def cpu_load_send(self, sensLoad, ctrlLoad, batVolt, force_mavlink1=False):
'''
Sensor and DSC control loads.
sensLoad : Sensor DSC Load (uint8_t)
ctrlLoad : Control DSC Load (uint8_t)
batVolt ... |
python | def upload_image(request):
"""
Вюха, яка зберігає завантажений файл.
Структура запиту:
FILES
images[]: файли зображеннь
POST DATA
profile: назва профілю (для визначення налаштувань збреження) (опціонально)
label: додаток до назви файлу при збереженні (опці... |
java | public CloseableReference<Bitmap> createBitmap(
DisplayMetrics display,
int width,
int height,
Bitmap.Config config) {
return createBitmap(display, width, height, config, null);
} |
python | async def upload_file(self, Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None):
"""Upload a file to an S3 object.
Usage::
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
Similar behavior as S3Transfer's u... |
java | public static String getAdiVarna(String str)
{
if (str.length() == 0) return null;
String adiVarna = String.valueOf(str.charAt(0));
if (str.length() > 1 && str.charAt(1) == '3') // for pluta
{
adiVarna += String.valueOf(str.charAt(1));
}
return adiVarna;... |
java | private void deleteFile(File file, String vfsName) {
try {
if (file.exists() && file.canWrite()) {
file.delete();
// write log message
if (LOG.isInfoEnabled()) {
LOG.info(Messages.get().getBundle().key(Messages.LOG_FILE_DELETED_1, ... |
java | @Override
public final Class<? extends T> enhanceClass(Class<T> baseClass) {
logger.info("Enhancing {}", baseClass);
CtClass original = null;
try {
original = pool.get(baseClass.getName());
TemplateHelper templateHelper = new TemplateHelper(pool);
Veloc... |
java | public void setDefault(boolean newDefault)
{
boolean oldDefault = default_;
default_ = newDefault;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, TypesPackage.JVM_OPERATION__DEFAULT, oldDefault, default_));
} |
python | def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0,
cloud_fraction=0, split=False):
"""
Calculate potential shortwave radiation for a specific location and time.
This routine calculates global radiation as described in:
Liston, G. E... |
java | @JmxGetter(name = "avgSlopUpdateNetworkTimeMs", description = "average time spent on network, for streaming operations")
public double getAvgSlopUpdateNetworkTimeMs() {
return networkTimeCounterMap.get(Operation.SLOP_UPDATE).getAvgEventValue() / Time.NS_PER_MS;
} |
python | def write_generator_cost_data(self, file):
""" Writes generator cost data to file.
"""
file.write("\n%%%% generator cost data\n")
file.write("%%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n")
file.write("%%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\n")
file.write("%sge... |
java | public long copy(InputStream in, Node dest) throws IOException {
long result;
try (OutputStream out = dest.newOutputStream()) {
result = copy(in, out);
}
return result;
} |
python | def _get_galaxy_data_table(name, dt_config_file):
"""Parse data table config file for details on tool *.loc location and columns.
"""
out = {}
if os.path.exists(dt_config_file):
tdtc = ElementTree.parse(dt_config_file)
for t in tdtc.getiterator("table"):
if t.attrib.get("name... |
python | def _try_to_get_extension(obj):
"""
Try to get file extension from given path or file object.
:param obj: a file, file-like object or something
:return: File extension or None
>>> _try_to_get_extension("a.py")
'py'
"""
if is_path(obj):
path = obj
elif is_path_obj(obj):
... |
java | public static SecapiPayProfitsharingResult secapiPayProfitsharing(SecapiPayProfitsharing secapiPayProfitsharing,String key){
Map<String,String> map = MapUtil.objectToMap(secapiPayProfitsharing, "receivers");
if(secapiPayProfitsharing.getReceivers() != null){
map.put("receivers", JsonUtil.toJSONString(secapiPayPr... |
python | def html_to_rgb(html):
"""Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither... |
python | def residual_conv(x, repeat, k, hparams, name, reuse=None):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name, reuse=reuse):
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
for i in range(repeat):
with tf.variable_scope("repeat_%d" % i):
y = com... |
java | public static Map<double[], int[]> getTransformMap(BioAssemblyInfo bioassemblyInfo, Map<String, Integer> chainIdToIndexMap) {
Map<Matrix4d, List<Integer>> matMap = new LinkedHashMap<>();
List<BiologicalAssemblyTransformation> transforms = bioassemblyInfo.getTransforms();
for (BiologicalAssemblyTransformation t... |
java | public void addFilePart(final String fieldName, final URL urlToUploadFile)
throws IOException
{
//
// Maybe try and extract a filename from the last part of the url?
// Or have the user pass it in?
// Or just leave it blank as I have already done?
//
addFilePa... |
java | private void handleBindStat(long elapsedTime) {
String METHODNAME = "handleBindStat(long)";
if (elapsedTime < LDAP_CONNECT_TIMEOUT_TRACE) {
QUICK_LDAP_BIND.getAndIncrement();
}
long now = System.currentTimeMillis();
/*
* Print out at most every 30 minutes t... |
java | @Override
public boolean containsKey(Object key) {
return key != null ? getProperty(key.toString(), _scope) != null : false;
} |
java | private InputStream getDefault(String fileName) {
InputStream result = null;
try {
result = new BufferedInputStream(new FileInputStream(fileName));
} catch (IOException ignore) {
}
return result;
} |
java | @Deprecated
public static <K, V> Function<K, V> map(java.util.Map<K, V> m) {
return m::get;
} |
java | public static KeyStore loadKeyStore(InputStream keyStore, String password)
throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
try {
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(keyStore, password.toCharArray());
... |
python | def get(self, name):
"""Get the set of compatible packages given a resolvable name."""
resolvable, packages, parent, constraint_only = self._collapse().get(
self.normalize(name), _ResolvedPackages.empty())
return packages |
python | def to_dict(self):
'''Return a dict of the attributes.'''
return dict(
raw=self.raw,
scheme=self.scheme,
authority=self.authority,
netloc=self.authority,
path=self.path,
query=self.query,
fragment=self.fragment,
... |
java | public <T extends Evaluation> T evaluate(JavaRDD<DataSet> data, List<String> labelsList, int evalBatchSize) {
Evaluation e = new org.deeplearning4j.eval.Evaluation();
e = doEvaluation(data, e, evalBatchSize);
if (labelsList != null) {
e.setLabelsList(labelsList);
}
re... |
python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N... |
java | public static FileInfo parseFileName(File file)
{
// Owned filenames have the form:
// dbname/CURRENT
// dbname/LOCK
// dbname/LOG
// dbname/LOG.old
// dbname/MANIFEST-[0-9]+
// dbname/[0-9]+.(log|sst|dbtmp)
String fileName = file.get... |
java | private boolean delete(final File f) throws IOException {
if (f.isDirectory()) {
final File[] files = f.listFiles();
if (files != null) {
for (File file : files) {
final boolean del = delete(file);
if (!del) {
return false;
}
}
}
} else {
return f.delete();
}
// Now di... |
python | def logical_not(f): # function factory
'''Logical not from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
'''
def f(value):
return np.logical_not(... |
java | @Nonnull
public static <T> ObjDoubleConsumerBuilder<T> objDblConsumer(Consumer<ObjDoubleConsumer<T>> consumer) {
return new ObjDoubleConsumerBuilder(consumer);
} |
python | def closed(self, reason):
"""Callback performed when the transport is closed."""
self.server.remove_connection(self)
self.protocol.connection_lost(reason)
if not isinstance(reason, ConnectionClosed):
logger.warn("connection closed, reason: %s" % str(reason))
else:
... |
python | def _get_port_range(range_str):
""" Given a string with a port or port range: '80', '80-120'
Returns tuple with range start and end ports: (80, 80), (80, 120)
"""
if range_str == '*':
return PortsRangeHelper.PortsRange(start=0, end=65535)
s = range_str.split('-')... |
java | public void stop() {
releaseWakeLock();
if (null != recorder && prepared && recording) {
try {
recorder.stop();
recorder.reset();
recorder.release();
prepared = false;
recording = false;
recorder ... |
python | def putResult(self, result):
"""Register the *result* by putting it on all the output tubes."""
self._lock_prev_output.acquire()
for tube in self._tubes_result_output:
tube.put((result, 0))
self._lock_next_output.release() |
python | def set_prbs(self, rx_ports=None, tx_ports=None):
""" Set TX ports and RX streams for stream statistics.
:param ports: list of ports to set RX PRBS. If empty set for all ports.
:type ports: list[ixexplorer.ixe_port.IxePort]
:param tx_ports: list of streams to set TX PRBS. If empty set f... |
java | public List<Long> getIds(final int count) throws SnowizardClientException {
for (final String host : hosts) {
try {
final SnowizardResponse snowizard = executeRequest(host, count);
if (snowizard != null) {
return snowizard.getIdList();
... |
java | public static PathAddress transformAddress(final PathAddress original, final TransformationTarget target) {
return TransformersImpl.transformAddress(original, target);
} |
python | def estimate_shift(signal, genome=None, windowsize=5000, thresh=None,
nwindows=1000, maxlag=500, array_kwargs=None,
verbose=False):
"""
Experimental: cross-correlation to estimate the shift width of ChIP-seq
data
This can be interpreted as the binding site footprin... |
java | private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
try {
if (timeout > 0) {
return task.get(timeout, timeUnit);
} else {
return task.get();
}
} catch (InterruptedException e) {
return e; // caller will ... |
python | def run_file(self, path, all_errors_exit=True):
"""Execute a Python file."""
path = fixpath(path)
with self.handling_errors(all_errors_exit):
module_vars = run_file(path)
self.vars.update(module_vars)
self.store("from " + splitname(path)[1] + " import *") |
python | def generateVariant(self, referenceName, position, randomNumberGenerator):
"""
Generate a random variant for the specified position using the
specified random number generator. This generator should be seeded
with a value that is unique to this position so that the same variant
w... |
python | def camel_2_snake(name):
"Converts CamelCase to camel_case"
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
java | @SuppressWarnings("unchecked")
<K, E extends PoolableObject<V>> E flagOwner() {
this.owner = Thread.currentThread();
return (E) this;
} |
python | def parser(rules=None, **kwargs):
"""Instantiate a parser with the default Splunk command rules."""
rules = RULES_SPLUNK if rules is None else dict(RULES_SPLUNK, **rules)
return Parser(rules, **kwargs) |
python | def conv_precip_frac(precip_largescale, precip_convective):
"""Fraction of total precip that is from convection parameterization.
Parameters
----------
precip_largescale, precip_convective : xarray.DataArrays
Precipitation from grid-scale condensation and from convective
parameterizatio... |
python | def modify_target_group(TargetGroupArn=None, HealthCheckProtocol=None, HealthCheckPort=None, HealthCheckPath=None, HealthCheckIntervalSeconds=None, HealthCheckTimeoutSeconds=None, HealthyThresholdCount=None, UnhealthyThresholdCount=None, Matcher=None):
"""
Modifies the health checks used when evaluating the hea... |
python | def add_embedding(self, tag, embedding, labels=None, images=None, global_step=None):
"""Adds embedding projector data to the event file. It will also create a config file
used by the embedding projector in TensorBoard. The folder containing the embedding
data is named using the formula:
... |
python | def get_feature_from_key(self, feature_key):
""" Get feature for the provided feature key.
Args:
feature_key: Feature key for which feature is to be fetched.
Returns:
Feature corresponding to the provided feature key.
"""
feature = self.feature_key_map.get(feature_key)
if feature:... |
python | def get_supports(self):
"""Returns set of extension support strings referenced in this Registry
:return: set of extension support strings
"""
out = set()
for ext in self.extensions.values():
out.update(ext.get_supports())
return out |
python | def mean_absolute_error(df, col_true, col_pred=None):
"""
Compute mean absolute error of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str... |
java | public String radio (String name, String value, String defaultValue)
{
StringBuilder buf = new StringBuilder();
buf.append("<input type=\"radio\"");
buf.append(" name=\"").append(name).append("\"");
buf.append(" value=\"").append(value).append("\"");
String selectedValue = ge... |
python | def close(self):
"""Release libpci resources."""
if self._access is not None:
_logger.debug("Cleaning up")
pci_cleanup(self._access)
self._access = None |
python | def enqueue(self, func, *args, **kwargs):
"""Enqueue a function call or a :doc:`job <job>`.
:param func: Function or a :doc:`job <job>` object. Must be
serializable and available to :doc:`workers <worker>`.
:type func: callable | :doc:`kq.Job <job>`
:param args: Positional a... |
python | def setdoc(self,newdoc):
"""Set a different document. Usually no need to call this directly, invoked implicitly by :meth:`copy`"""
self.doc = newdoc
if self.doc and self.id:
self.doc.index[self.id] = self
for c in self:
if isinstance(c, AbstractElement):
... |
python | def create_ip_cert_links(ssl_dir, custom_hostname_link=None):
"""Create symlinks for SAN records
:param ssl_dir: str Directory to create symlinks in
:param custom_hostname_link: str Additional link to be created
"""
hostname = get_hostname(unit_get('private-address'))
hostname_cert = os.path.jo... |
java | private PExp getImpliesExists(ASetCompSetExp exp, ILexNameToken finmap,
ILexNameToken findex)
{
AExistsExp exists = new AExistsExp();
AMapDomainUnaryExp domExp = new AMapDomainUnaryExp();
domExp.setType(new ABooleanBasicType());
domExp.setExp(getVarExp(finmap));
List<PMultipleBind> bindList = getMultiple... |
python | def copy(self):
"""Create a copy of a BinaryQuadraticModel.
Returns:
:class:`.BinaryQuadraticModel`
Examples:
>>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)
>>> bqm2 = bqm.copy()
"""
# new objects are co... |
java | protected void activeStatusChanged(boolean newActiveState) throws PushStateException {
active = newActiveState;
log.debugf("changed mode %s", this);
if (active && singletonConfiguration.pushStateWhenCoordinator())
doPushState();
} |
python | def _open_ok(self, args):
"""
signal that the connection is ready
This method signals to the client that the connection is ready
for use.
PARAMETERS:
known_hosts: shortstr
"""
self.known_hosts = args.read_shortstr()
AMQP_LOGGER.debug('Open O... |
python | def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot):
""" 2D or 3D scatter plot.
:param axes ax: matplotlib axes (use Axes3D if 3D data)
:param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotte... |
java | public static BigDecimal strToAmount(@CurrencyAmountStr final String amount) {
if (amount == null) {
return null;
}
final int dot = amount.indexOf('.');
final int scale;
final String unscaledStr;
if (dot == -1) {
scale = 0;
uns... |
java | @Override
protected boolean isContentType(String schemaId, String schemaVersion, String systemId, String publicId) {
return (this.publicId != null && this.publicId.equalsIgnoreCase(publicId))
|| (this.systemId != null && this.systemId.equalsIgnoreCase(systemId));
} |
java | public static ntp_sync update(nitro_service client, ntp_sync resource) throws Exception
{
resource.validate("modify");
return ((ntp_sync[]) resource.update_resource(client))[0];
} |
python | def _cs_disassemble_one(self, data, address):
"""Disassemble the data into an instruction in string form.
"""
asm, size = "", 0
disasm = list(self._disassembler.disasm_lite(bytes(data), address))
if len(disasm) > 0:
address, size, mnemonic, op_str = disasm[0]
... |
python | def log_in(self):
"""Perform the `log_in` task to setup the API session for future data requests."""
if not self.password:
# Password wasn't give, ask for it now
self.password = getpass.getpass('Password: ')
utils.pending_message('Performing login...')
login_res... |
python | def start_traffic(self, blocking=False, *ports):
""" Start traffic on list of ports.
:param blocking: True - start traffic and wait until traffic ends, False - start traffic and return.
:param ports: list of ports to start traffic on. Default - all session ports.
"""
for chassi... |
java | public List<O> getItems(int count, int offset) {
return getDatastore().find(clazz).offset(offset).limit(count).asList();
} |
python | def then(self, success=None, failure=None):
"""
This method takes two optional arguments. The first argument
is used if the "self promise" is fulfilled and the other is
used if the "self promise" is rejected. In either case, this
method returns another promise that effectively ... |
python | def run(self, *args, **kwargs) -> Callable:
"""Return wrapped function.
Haskell: runReader :: Reader r a -> r -> a
This is the inverse of unit and returns the wrapped function.
"""
return self.fn(*args, **kwargs) if args or kwargs else self.fn |
python | def _execute(self, stmt, *values):
"""
Gets a cursor, executes `stmt` and closes the cursor,
fetching one row afterwards and returning its result.
"""
c = self._cursor()
try:
return c.execute(stmt, values).fetchone()
finally:
c.close() |
java | public static void addGpsLogDataPoint( Connection connection, OmsGeopaparazziProject3To4Converter.GpsPoint point,
long gpslogId ) throws Exception {
Date timestamp = ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.parse(point.utctime);
String insertSQL = "INSERT INTO " + TableDescriptions.TABL... |
python | def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
f = F... |
java | static boolean killProcess(final String processName, int id) {
int pid;
try {
pid = processUtils.resolveProcessId(processName, id);
if(pid > 0) {
try {
Runtime.getRuntime().exec(processUtils.getKillCommand(pid));
return true... |
python | def download(url, file_name):
r = requests.get(url, stream=True)
file_size = int(r.headers['Content-length'])
'''
if py3:
file_size = int(u.getheader("Content-Length")[0])
else:
file_size = int(u.info().getheaders("Content-Length")[0])
'''
file_exists = False
if... |
java | public static base_response update(nitro_service client, csparameter resource) throws Exception {
csparameter updateresource = new csparameter();
updateresource.stateupdate = resource.stateupdate;
return updateresource.update_resource(client);
} |
java | public Object evaluate(Task k, TaskRequest req, TaskResponse res) {
ReturnValueImpl rslt = new ReturnValueImpl();
RuntimeRequestResponse tr = new RuntimeRequestResponse();
tr.enclose(req);
tr.setAttribute(Attributes.RETURN_VALUE, rslt);
run(k, tr, res);
... |
java | public void onServletInit (@Nonnull final Class <? extends GenericServlet> aServletClass)
{
if (LOGGER.isDebugEnabled ())
LOGGER.debug ("onServletInit: " + aServletClass);
_updateStatus (aServletClass, EServletStatus.INITED);
} |
python | def get_level(self):
"""Gets the ``Grade`` corresponding to the assessment difficulty.
return: (osid.grading.Grade) - the level
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from templa... |
python | def append_query_param(self, key, value):
"""
Append a query parameter
:param string key: The query param key
:param string value: The new value
"""
values = self.query_param(key, as_list=True, default=[])
values.append(value)
return self.query_param(key,... |
python | def change_state_id(self, state_id=None):
"""
Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all
data flows and transitions.
:param state_id: The new state if of the state
"""
old_state_id = self.state_id
... |
python | def verify_signature(message, key, signature):
"""
This function will verify the authenticity of a digital signature.
For security purposes, Nylas includes a digital signature in the headers
of every webhook notification, so that clients can verify that the
webhook request came from Nylas and no one... |
java | public void setAlias(String alias)
{
m_alias = alias;
String attributePath = (String)getAttribute();
boolean allPathsAliased = true;
m_userAlias = new UserAlias(alias, attributePath, allPathsAliased);
} |
python | def feature (name, values, attributes = []):
""" Declares a new feature with the given name, values, and attributes.
name: the feature name
values: a sequence of the allowable values - may be extended later with feature.extend
attributes: a sequence of the feature's attributes (e.g. implicit... |
python | def betweenness_bin(G):
'''
Node betweenness centrality is the fraction of all shortest paths in
the network that contain a given node. Nodes with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary d... |
java | @Override
public String extractClassNameIfProvide(Node node, Node parent) {
String namespace = extractClassNameIfGoog(node, parent, "goog.provide");
if (namespace == null) {
namespace = extractClassNameIfGoog(node, parent, "goog.module");
}
return namespace;
} |
python | def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
"""
result = self._wait_incrementing_start + (self.... |
java | public static byte[] hex2bin(final String s)
{
String m = s;
if (s == null)
{
// Allow empty input string.
m = "";
}
else if (s.length() % 2 != 0)
{
// Assume leading zero for odd string length
m = "0" + s;
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.