language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_client(provider, token=''):
"Return the API client for the given provider."
cls = OAuth2Client
if provider.request_token_url:
cls = OAuthClient
return cls(provider, token) |
python | def plot_violin(
data,
var_names=None,
quartiles=True,
credible_interval=0.94,
shade=0.35,
bw=4.5,
sharey=True,
figsize=None,
textsize=None,
ax=None,
kwargs_shade=None,
):
"""Plot posterior of traces as violin plot.
Notes
-----
If multiple chains are provided... |
java | public <E extends Exception> boolean allMatch(Try.IntPredicate<E> filter) throws E {
return allMatch(0, size(), filter);
} |
python | def get_os_version_codename_swift(codename):
'''Determine OpenStack version number of swift from codename.'''
for k, v in six.iteritems(SWIFT_CODENAMES):
if k == codename:
return v[-1]
e = 'Could not derive swift version for '\
'codename: %s' % codename
error_out(e) |
java | public ContiguousIntervalUsageInArrear build(final boolean closedInterval) {
Preconditions.checkState(!isBuilt.get(), "!isBuilt");
Preconditions.checkState((!closedInterval && billingEvents.size() >= 1) ||
(closedInterval && billingEvents.size() >= 2),
... |
java | public FilterLogEventsRequest withLogStreamNames(String... logStreamNames) {
if (this.logStreamNames == null) {
setLogStreamNames(new com.amazonaws.internal.SdkInternalList<String>(logStreamNames.length));
}
for (String ele : logStreamNames) {
this.logStreamNames.add(ele)... |
python | def check_ports_on_br(self, bridge='br-ex', ports=['eth3']):
"""Check ports exist on bridge.
ovs-vsctl list-ports bridge
"""
LOG.info("RPC: check_ports_on_br bridge: %s, ports: %s" %
(bridge, ports))
cmd = ['ovs-vsctl', 'list-ports', bridge]
stdcode, std... |
python | def _smb3kdf(self, ki, label, context):
"""
See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to t... |
python | def append(self, item):
"""Add an item to the Tree"""
if not isinstance(item, Tree):
return ValueError("Can only append items of type Tree")
if not self.children: self.children = []
item.parent = self
self.children.append(item) |
java | private void doLoad() throws IOException {
final String libName = getName();
try {
System.loadLibrary(libName);
} catch (UnsatisfiedLinkError e) {
try {
extractAndLoad(getPlatformLibraryPath(), getSimpleLibraryPath());
} catch (IOException ioe) {
logger.warn("Failed to load... |
python | def _spec_fw_pointers_aware(symbol, version, from_index=None, to_index=None):
"""
This method updates the find query filter spec used to read the segment for a version.
It chooses whether to query via forward pointers or not based on the version details and current mode of operation.
"""
spec = {'sy... |
python | def import_file(filename):
"""
Imports the commodity prices from the given .csv file.
"""
#file_path = os.path.relpath(filename)
file_path = os.path.abspath(filename)
log(DEBUG, "Loading prices from %s", file_path)
prices = __read_prices_from_file(file_path)
with BookAggregate(for_writi... |
java | private static void sort1(Quicksortable q, int off, int k, int len) {
// we don't care about anything >= to k
if (off >= k)
return;
// Insertion sort on smallest arrays
if (len < 7) {
for (int i = off; i < len + off; i++)
for (int j = i; j > off &&... |
java | public java.util.List<ECSService> getEcsServices() {
if (ecsServices == null) {
ecsServices = new com.amazonaws.internal.SdkInternalList<ECSService>();
}
return ecsServices;
} |
java | public DataStore createDataStore(Collection<String> columns) {
DataStore b = new DataStore(columns);
trackDataStore(b);
return b;
} |
python | def setup_link(self, interface, cidr):
"""Setup a link.
ip addr add dev interface
ip link set dev interface up
"""
# clear old ipaddr in interface
cmd = ['ip', 'addr', 'flush', 'dev', interface]
agent_utils.execute(cmd, root=True)
ip = IPNetwork(cidr)
... |
java | @Nullable
public File getFile(@NotNull final String key) {
final String file = getString(key);
if (file == null) {
return null;
}
return new File(file);
} |
java | public Optional<OffsetRange<OffsetType>> clipToBounds(OffsetRange<OffsetType> bounds) {
if (bounds.contains(this)) {
return Optional.of(this);
}
if (!bounds.overlaps(this)) {
return Optional.absent();
}
final OffsetType newLowerBound;
final OffsetType newUpperBound;
if (bounds.st... |
java | public final Instruction getInstruction(String name) {
INSTRUCTION_PATH_TEMPLATE.validate(name, "getInstruction");
GetInstructionRequest request = GetInstructionRequest.newBuilder().setName(name).build();
return getInstruction(request);
} |
python | def to_dict_hook(obj):
"""Convert internal objects to a serializable representation.
During serialization if the object has the hook method `to_dict` it will be
automatically called and metadata for decoding will be added. This allows
for the translation of objects trees of arbitrary depth. E.g.:
... |
java | public boolean learn(Sentence sentence)
{
CharTable.normalize(sentence);
if (!getPerceptronSegmenter().learn(sentence)) return false;
if (posTagger != null && !getPerceptronPOSTagger().learn(sentence)) return false;
if (neRecognizer != null && !getPerceptionNERecognizer().learn(sente... |
python | def difference(self,other):
"""
Return a new IntervalSet with the difference of the two sets, i.e.
all elements that are in self but not in other.
:param IntervalSet other: Set to subtract
:rtype: IntervalSet
"""
res = IntervalSet.everything()
for j in ot... |
python | def accept(self, offer_ids, operations, filters=Filters()):
"""Accepts the given offers and performs a sequence of operations
on those accepted offers.
See Offer.Operation in mesos.proto for the set of available operations.
Available resources are aggregated when multiple offers are ... |
java | public void processFailure(QueryBatchException queryBatch) {
boolean isHostUnavailableException = processException(queryBatch.getBatcher(), queryBatch, queryBatch.getClient().getHost());
if ( isHostUnavailableException == true ) {
try {
logger.warn("Retrying failed batch: {}, results so far: {}, f... |
python | def log_backend_action(action=None):
""" Logging for backend method.
Expects django model instance as first argument.
"""
def decorator(func):
@functools.wraps(func)
def wrapped(self, instance, *args, **kwargs):
action_name = func.func_name.replace('_', ' ') if action is Non... |
java | private void initServlet(Servlet servlet, ServletConfig config)
throws ServletException
{
Principal user=null;
try
{
// Handle run as
if (_runAs!=null && _realm!=null)
user=_realm.pushRole(null,_runAs);
servlet.init(config);
}... |
python | def create_zone(self, zone, serial=None):
"""Create a zone for the specified zone.
:param zone: the zone name to create
:param serial: serial value on the zone (default: strftime(%Y%m%d01))
"""
return self.service.createObject({
'name': zone,
'serial': s... |
java | public Boolean onClick(AppCompatActivity act, IItem item) {
//if we are current in CAB mode, and we remove the last selection, we want to finish the actionMode
if (mActionMode != null && (mSelectExtension.getSelectedItems().size() == 1) && item.isSelected()) {
mActionMode.finish();
... |
java | @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube_sample);
ButterKnife.inject(this);
initializeYoutubeFragment();
initializeDraggablePanel();
hookDraggablePanelListeners();
} |
java | @Override
public synchronized void close() throws IOException {
try {
if (bbr != null) {
bbr.close();
}
} finally {
if (decompressor != null) {
CodecPool.returnDecompressor(decompressor);
decompressor = null;
}
}
} |
python | def get_namedtuple_factory(cls, field_mappings, name="Record"):
"""Gets a method that will convert a dictionary to a namedtuple, as defined by
get_namedtuple(field_mappings).
"""
ntup = cls.get_namedtuple(field_mappings, name)
return lambda data: ntup(**data) |
java | @SuppressWarnings("unchecked")
public static <BASE, FROM extends BASE, TO extends BASE> Class<TO> uglyCrossCast(Class<FROM> cls, Class<BASE> base) {
if(!base.isAssignableFrom(cls)) {
throw cls == null ? new ClassCastException("Attempted to use 'null' as class.") : new ClassCastException(cls.getName() + " is... |
python | def update(self, table, rowupdate, where):
"""
Update matching records.
- rowupdate is a dict with updated fields, e.g. {'name': 'John'}.
- See `sqlwhere` for where clause.
Returns the number of rows updated.
>>> import getpass
>>> s = DB(dbname='test', user=get... |
java | private boolean nodeOk( GridNode node ) {
return node != null && !assignedFlowsMap.isMarked(node.col, node.row);
} |
java | public static String getDigits(String value) {
StringBuilder digits = new StringBuilder(value.length());
for (char chr : value.toCharArray()) {
if (Character.isDigit(chr)) {
digits.append(chr);
}
}
return digits.toString();
} |
python | def with_descriptor(self, descriptor):
'''
Returns any entities with the specified descriptor
'''
res = {}
desc = "%s_descriptor" % descriptor
for eid, ent in self.items():
if desc in ent:
res[eid] = ent
return res |
python | def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result |
python | def get_report(report=None):
"""Returns details of a specific report
"""
if not report:
report = list_reports()[-1:][0]
report_path = _get_reports_path(report)
report_dict = {"report": report}
for filename in os.listdir(report_path):
with open(os.path.join(report_path, filename),... |
python | def check_section_unaligned(self):
''' Checking if any of the sections are unaligned '''
file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment
unaligned_sections = []
for section in self.pefile_handle.sections:
if section.PointerToRawData % file_alignment:
... |
java | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
... |
java | public static JSONArray toJsonArray(byte[] bytes) {
String json;
try {
json = new String(bytes, Const.UTF8);
return new JSONArray(json);
} catch (UnsupportedEncodingException e) {
throw new WebbException(e);
} catch (JSONException e) {
thro... |
java | public void extractCamera( DMatrixRMaj P2 , DMatrixRMaj P3 ) {
// temp1 = [e3*e3^T -I]
for( int i = 0; i < 3; i++ ) {
for( int j = 0; j < 3; j++ ) {
temp1.set(i,j,e3.getIdx(i)*e3.getIdx(j));
}
temp1.set(i,i , temp1.get(i,i) - 1);
}
// compute the camera matrices one column at a time
for( int i =... |
python | def evaluate(self):
"""Get the result of evaluating the computation graph at this node."""
if DEVELOP:
internal_assert(not self.been_called, "inefficient reevaluation of action " + self.name + " with tokens", self.tokens)
self.been_called = True
evaluated_toks = evaluate_... |
python | def checksum(sin):
"""
Determine validity of a Canadian Social Insurance Number.
Validation is performed using a modified Luhn Algorithm. To check
the Every second digit of the SIN is doubled and the result is
summed. If the result is a multiple of ten, the Social Insurance
Number is considere... |
python | def sum(self, callback=None):
"""
Get the sum of the given values.
:param callback: The callback
:type callback: callable or string or None
:rtype: mixed
"""
if callback is None:
return sum(self.items)
callback = self._value_retriever(callba... |
python | def _filter(self):
"""
delete the punctuation
"""
pattern = u"[\s+\.\!\-\/_,$%^*(+\"\']+|[+——!】【,。??:、:~@#¥%……&*“”()]+"
self.m = re.sub(pattern, "", self.m) |
python | def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
... |
python | def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example::
>>> parse_url('http://google.com/mail/')
Url(scheme='http... |
python | def fix_trustdb(cls, trustdb=None):
"""Attempt to repair a broken trustdb.gpg file.
GnuPG>=2.0.x has this magical-seeming flag: `--fix-trustdb`. You'd think
it would fix the the trustdb. Hah! It doesn't. Here's what it does
instead::
(gpg)~/code/python-gnupg $ gpg2 --fix-trustdb
gpg: You m... |
python | def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False):
"""Converts a variable to a tensor."""
# pylint: disable=protected-access
if _enclosing_tpu_context() is None:
if hasattr(self._primary_var, '_dense_var_to_tensor'):
return self._primary_var._dense_var_to_tensor(dtype, name, ... |
python | def get_contents(self, origin):
"""
Try to load the origin.
"""
try:
path = self.get_app_template_path(
origin.app_name, origin.template_name)
with io.open(path, encoding=self.engine.file_charset) as fp:
return fp.read()
exc... |
python | def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None):
"""Creates a timeline slider.
Parameters
----------
text : str, optional
The text to display for the slider. Defaults to 'Time'
ax : matplotlib.axes.Axes, optional
The matplotlib ax... |
python | def identify_link_type(filename):
'''Return link type guessed by filename extension.
Returns:
str: A value from :class:`.item.LinkType`.
'''
mime_type = mimetypes.guess_type(filename)[0]
if not mime_type:
return
if mime_type == 'text/css':
return LinkType.css
elif ... |
python | def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('... |
java | @SuppressWarnings("unchecked")
public void init(FilterConfig c) throws ServletException {
Properties p = new Properties();
ServletContext sc = c.getServletContext();
for (Enumeration e = sc.getInitParameterNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
p.put(key, sc.getInitParamet... |
python | def buildParser():
''' Builds the parser for reading the command line arguments'''
parser = argparse.ArgumentParser(description='Bagfile reader')
parser.add_argument('-b', '--bag', help='Bag file to read',
required=True, type=str)
parser.add_argument('-s', '--series',
... |
python | def acked(err, msg):
"""Delivery report callback called (from flush()) on successful or failed delivery of the message."""
if err is not None:
print("failed to deliver message: {}".format(err.str()))
else:
print("produced to: {} [{}] @ {}".format(msg.topic(), msg.partition(), msg.offset())) |
python | def _expand_for_carryover(max_vol, plan, **kwargs):
"""
Divide volumes larger than maximum volume into separate transfers
"""
max_vol = float(max_vol)
carryover = kwargs.get('carryover', True)
if not carryover:
return plan
new_transfer_plan = []
for p in plan:
source = p[... |
python | def _summarize_peaks(peaks):
"""
merge peaks position if closer than 10
"""
previous = peaks[0]
new_peaks = [previous]
for pos in peaks:
if pos > previous + 10:
new_peaks.add(pos)
previous = pos
return new_peaks |
python | def exchangebill(self):
"""
默认提供最近30天的交割单, 通常只能返回查询日期内最新的 90 天数据。
:return:
"""
# TODO 目前仅在 华泰子类 中实现
start_date, end_date = helpers.get_30_date()
return self.get_exchangebill(start_date, end_date) |
python | def is_bool_matrix(l):
r"""Checks if l is a 2D numpy array of bools
"""
if isinstance(l, np.ndarray):
if l.ndim == 2 and (l.dtype == bool):
return True
return False |
java | protected void closeConnection(final String meUuid, boolean alreadyClosed) {
final String methodName = "closeConnection";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, methodName, meUuid);
}
synchronized (_sessionsByMeUuid) {... |
java | private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) {
final int ordering = getOrdering(categoryOrder);
final MenuItemImpl item = new MenuItemImpl(this, group, id, categoryOrder,
ordering, title, mDefaultShowAsAction);
if (mCurrentMenuInfo != n... |
python | def assign_to_a_queue(self, action):
"""Take an action and put it to a worker actions queue
:param action: action to put
:type action: alignak.action.Action
:return: None
"""
(worker_id, queue) = self._get_queue_for_the_action(action)
if not worker_id:
... |
java | @Override
public int compareTo(HelpSearchHit hit) {
int result = -NumUtil.compare(confidence, hit.confidence);
return result != 0 ? result : topic.compareTo(hit.topic);
} |
python | def build(self, text, size=1):
"""
:param text: Text of the widget
:param size: Size of the text (Higher size = smaller title)
"""
super(Title, self).build()
self.content = text
self.size = size |
python | def uniqify(func):
"""Make sure that a method returns a unique name."""
@six.wraps(func)
def unique(self, *args, **kwargs):
return self.unique(func(self, *args, **kwargs))
return unique |
java | @Override
public String withdrawFunds(Currency currency, BigDecimal amount, String address)
throws IOException {
try {
// determine withdrawal type
String type = BitfinexUtils.convertToBitfinexWithdrawalType(currency.toString());
// Bitfinex withdeawal can be from different type of wallets... |
python | def update(self, statement):
"""
Update the provided statement.
"""
Statement = self.get_model('statement')
Tag = self.get_model('tag')
if hasattr(statement, 'id'):
statement.save()
else:
statement = Statement.objects.create(
... |
python | def update(gandi, ip, reverse, background):
"""Update an ip."""
if not reverse:
return
return gandi.ip.update(ip, {'reverse': reverse}, background) |
python | def register_blueprints(app):
"""Register blueprints to application.
Currently, Rio registered:
* /api/1
* /dashboard
"""
from .blueprints.event import bp as event_bp
app.register_blueprint(event_bp, url_prefix='/event')
from .blueprints.api_1 import bp as api_1_bp
app.register_b... |
python | def Graph(self):
"""Return the graph definition, if there is one.
If the graph is stored directly, return that. If no graph is stored
directly but a metagraph is stored containing a graph, return that.
Raises:
ValueError: If there is no graph for this run.
Returns:
The `graph_def` pr... |
python | def delete_account_metadata(self, prefix=None):
"""
Removes all metadata matching the specified prefix from the account.
By default, the standard account metadata prefix ('X-Account-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must i... |
python | def process_species(self, limit):
"""
Loop through the xml file and process the species.
We add elements to the graph, and store the
id-to-label in the label_hash dict.
:param limit:
:return:
"""
myfile = '/'.join((self.rawdir, self.files['data']['file']))... |
python | def request_will_echo(self):
"""
Tell the DE that we would like to echo their text. See RFC 857.
"""
self._iac_will(ECHO)
self._note_reply_pending(ECHO, True)
self.telnet_echo = True |
java | public int precision(int recall) {
int optimum = 0;
for (int right = 0; right <= recall; right++) {
int candidate = numpositive[right] + numnegative[recall - right];
if (candidate > optimum) {
optimum = candidate;
}
}
return optimum;
} |
java | public final <T> void addOption(Class<T> cls, String name, String description, String exclusiveGroup)
{
addOption(cls, name, description, exclusiveGroup, true);
} |
java | @Override
public Short fromString(Class targetClass, String s)
{
try
{
if (s == null)
{
return null;
}
Short sh = new Short(s);
return sh;
}
catch (NumberFormatException e)
{
log.erro... |
java | private HostFailoverPolicy getFailoverPolicy(String failoverOption)
{
if (failoverOption != null)
{
if (Constants.FAIL_FAST.equals(failoverOption))
{
return HostFailoverPolicy.FAIL_FAST;
}
else if (Constants.ON_FAIL_TRY_ALL_AVAILABLE.eq... |
python | def screenshot(
width=None,
height=None,
format="png",
fig=None,
timeout_seconds=10,
output_widget=None,
headless=False,
devmode=False,
):
"""Save the figure to a PIL.Image object.
:param int width: the width of the image in pixels
:param int height: the height of the image ... |
python | def get_dev_asset_details(ipaddress, auth, url):
"""Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:p... |
python | def recoverURL(self, url):
"""
Public method to recover a resource.
Args:
-----
url: The URL to be collected.
Returns:
--------
Returns a resource that has to be read, for instance, with html = self.br.read()
"""
# Configuring use... |
python | def make_handlers(base_url, server_processes):
"""
Get tornado handlers for registered server_processes
"""
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
... |
python | def _create_compositional_array_(expanded_chemical_formaula_string):
"""
Splits an expanded chemical formula string into an array of dictionaries containing information about each element
:param expanded_chemical_formaula_string: a clean (not necessarily emperical, but without any special characters) chemi... |
python | def list_files(path):
"""Recursively collects a list of files at a path."""
files = []
if os.path.isdir(path):
for stats in os.walk(path):
for f in stats[2]:
files.append(os.path.join(stats[0], f))
elif os.path.isfile(path):
files = [path]
return files |
java | public void printXmlNavMenu(PrintWriter out, ResourceBundle reg)
throws DBException
{
String strNavMenu = reg.getString("xmlNavMenu");
if ((strNavMenu == null) || (strNavMenu.length() == 0))
strNavMenu =
" <navigation-menu>" +
" <navigation-item>... |
java | public void setOutputFormatClass(Class<? extends OutputFormat> cls
) throws IllegalStateException {
ensureState(JobState.DEFINE);
conf.setClass(OUTPUT_FORMAT_CLASS_ATTR, cls, OutputFormat.class);
} |
java | public void end(Xid xid, int flags) throws XAException
{
long l1 = System.currentTimeMillis();
try
{
super.end(xid, flags);
}
finally
{
xastat.deltaEnd(System.currentTimeMillis() - l1);
}
} |
java | public static Gson createGson() {
GsonBuilder builder = new GsonBuilder();
builder.setExclusionStrategies(exclusionStrategy);
builder.registerTypeAdapter(Date.class, new DateTypeAdapter());
builder.registerTypeAdapterFactory(MailChimpObjectTypeAdapter.FACTORY);
return builder.create();
} |
java | static ReferenceTypeSignature parseReferenceTypeSignature(final Parser parser, final String definingClassName)
throws ParseException {
final ClassRefTypeSignature classTypeSignature = ClassRefTypeSignature.parse(parser, definingClassName);
if (classTypeSignature != null) {
return... |
java | public void onMessage(final byte[] message, final Session session) {
final SynchronizeFXWebsocketChannel channel = getChannelOrFail(session);
channel.newMessage(message, session);
} |
python | def formulas_iter(self):
"""
Iterates over all variable-clauses in the logical network
Yields
------
tuple[str,frozenset[caspo.core.clause.Clause]]
The next tuple of the form (variable, set of clauses) in the logical network.
"""
for var in it.ifilter... |
java | public com.google.api.ads.admanager.axis.v201805.ReportQueryAdUnitView getAdUnitView() {
return adUnitView;
} |
python | def doxygenLanguageToPygmentsLexer(location, language):
'''
Given an input location and language specification, acquire the Pygments lexer to
use for this file.
1. If :data:`configs.lexerMapping <exhale.configs.lexerMapping>` has been specified,
then :data:`configs._compiled_lexer_mapping <exhal... |
python | def more_mem_per_proc(self, factor=1):
"""
Method to increase the amount of memory asked for, by factor.
Return: new memory if success, 0 if memory cannot be increased.
"""
base_increase = 2000
old_mem = self.mem_per_proc
new_mem = old_mem + factor*base_increase
... |
java | public boolean contains(LCMSDataSubset other) {
// compare ms levels
Set<Integer> msLvlsThis = getMsLvls();
Set<Integer> msLvlsThat = other.getMsLvls();
// if ms levels are null, this definitely matches any other subset
// so we need to check msLevelsThis frist!
if (msLvlsThis != null && msLvls... |
java | public JsonNode parse(String src) {
synchronized (lock) {
try {
return mapper.readValue(src, JsonNode.class);
} catch (Exception t) {
throw new RuntimeException(t);
}
}
} |
python | def gaussian_kernel(gstd):
"""Generate odd sized truncated Gaussian
The generated filter kernel has a cutoff at $3\sigma$
and is normalized to sum to 1
Parameters
-------------
gstd : float
Standard deviation of filter
Returns
-------------
g : ndarray
Arra... |
java | private void mainTableInsert(ESSyncConfig config, Dml dml, Map<String, Object> data) {
ESMapping mapping = config.getEsMapping();
String sql = mapping.getSql();
String condition = ESSyncUtil.pkConditionSql(mapping, data);
sql = ESSyncUtil.appendCondition(sql, condition);
DataSour... |
java | @Override
public List<CommerceCurrency> findByG_P(long groupId, boolean primary) {
return findByG_P(groupId, primary, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.