language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private List<List<EventData>> split(List<EventData> datas) {
List<List<EventData>> result = new ArrayList<List<EventData>>();
if (datas == null || datas.size() == 0) {
return result;
} else {
int[] bits = new int[datas.size()];// 初始化一个标记,用于标明对应的记录是否已分入某个batch
... |
python | def apply(self, func, applyto='measurement', noneval=nan, setdata=False):
"""
Apply func either to self or to associated data.
If data is not already parsed, try and read it.
Parameters
----------
func : callable
The function either accepts a measurement obje... |
java | public void add(TagLibTag libTag, Tag tag, FunctionLib[] flibs, SourceCode cfml) {
tags.add(new TagData(libTag, tag, flibs, cfml));
} |
java | public Object getGetterOrSetter(String name, int index, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
Slot slot = slotMap.query(name, index);
if (slot == null)
return null;
if (slot instanceof GetterSlot) {
... |
python | def wait(self) -> None:
"""Wait for the process to finish"""
if self._out_thread.is_alive():
self._out_thread.join()
if self._err_thread.is_alive():
self._err_thread.join()
# Handle case where the process ended before the last read could be done.
# This w... |
python | def get_arp_output_arp_entry_entry_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_arp = ET.Element("get_arp")
config = get_arp
output = ET.SubElement(get_arp, "output")
arp_entry = ET.SubElement(output, "arp-entry")
ip_a... |
java | @SuppressWarnings("nls")
public static SSLSessionStrategy buildMutual(TLSOptions optionsMap)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
Args.notNull(optionsMap.getKeyStore(), "KeyStore");
... |
python | def post(self, request):
'''Create a token, given an email and password. Removes all other
tokens for that user.'''
serializer = CreateTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data.get('email')
password = s... |
python | def run():
"""Run cpp coverage."""
import json
import os
import sys
from . import coverage, report
args = coverage.create_args(sys.argv[1:])
if args.verbose:
print('encodings: {}'.format(args.encodings))
yml = parse_yaml_config(args)
if not args.repo_token:
# try ... |
java | public Observable<Page<SasTokenInfoInner>> listSasTokensAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final String containerName) {
return listSasTokensWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName, containerName)
.map(... |
python | def get_runner(worker_type, max_workers=None, workers_window=None):
"""returns a runner callable.
:param str worker_type: one of `simple` or `thread`.
:param int max_workers: max workers the runner can spawn in parallel.
:param in workers_window: max number of jobs waiting to be done by the
worke... |
python | def min(self):
"""Return the minimum of ``self``.
See Also
--------
numpy.amin
max
"""
results = [x.ufuncs.min() for x in self.elem]
return np.min(results) |
python | def hex_to_rgb(color):
"""
Converts from hex to rgb
Parameters:
-----------
color : string
Color representation on hex or rgb
Example:
hex_to_rgb('#E1E5ED')
hex_to_rgb('#f03')
"""
color = normalize(color)
color = color[1:]
# r... |
python | def read(self, addr, size):
'''Read access.
:param addr: i2c slave address
:type addr: char
:param size: size of transfer
:type size: int
:returns: data byte array
:rtype: array.array('B')
'''
self.set_addr(addr | 0x01)
self.s... |
java | public static Specification<JpaTarget> hasInstalledOrAssignedDistributionSet(@NotNull final Long distributionId) {
return (targetRoot, query, cb) -> cb.or(
cb.equal(targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id),
distributionId),
... |
python | def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]):
"""
Stop a running scene. If there's a scene on the stack, it resumes.
"""
self.stop_scene()
if self.current_scene is not None:
signal(events.SceneContinued())
else:
s... |
python | def bokeh_tree(name, rawtext, text, lineno, inliner, options=None, content=None):
''' Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags
for releases, or to master otherwise.
The link text is simply the URL path supplied, so typical usage might
look like:
.. code-block:: none
... |
python | def extract(fileobj, keywords, comment_tags, options):
"""Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, wri... |
python | def process_direct_map(self, root, state) -> List[Dict]:
"""Handles tags that are mapped directly from xml to IR with no
additional processing other than recursive translation of any child
nodes."""
val = {"tag": root.tag, "args": []}
for node in root:
val["args"] +=... |
java | public static int getPid(Process process) {
if (!process.getClass().getName().equals("java.lang.UNIXProcess"))
throw new UnsupportedOperationException("This operation is only supported in POSIX environments (Linux/Unix/MacOS");
if (pidField == null) { // benign race
try {
... |
java | public static void openDialogInWindow(final I_Callback callback, String windowCaption) {
final Window window = CmsBasicDialog.prepareWindow();
window.setCaption(windowCaption);
CmsSiteSelectDialog dialog = new CmsSiteSelectDialog();
window.setContent(dialog);
dialog.setCallback(... |
python | def _serialize_value(self, value):
"""
Serialize values like date and time. Respect other values:
:return:
"""
if isinstance(value, datetime.datetime):
return value.strftime(self.datetime_format)
elif isinstance(value, datetime.date):
return value... |
python | def download(url, output_file=None, open_file=True, allow_overwrite=False):
'''Download a file from URL.
Args:
url (str): URL.
output_file (str, optional): If given, the downloaded file is written to the given path.
open_file (bool): If True, it returns an opened file stream of the down... |
python | def square(left, top, length, filled=False, thickness=1):
"""Returns a generator that produces (x, y) tuples for a square.
This function is an alias for the rectangle() function, with `length` passed for both the
`width` and `height` parameters.
The `left` and `top` arguments are the x and y coordinate... |
java | @Override
public final Object retrieve(int handle) throws DataStoreException
{
if (SAFE_MODE) checkHandle(handle);
// Compute total size
int totalSize = computeSize(handle);
// Retrieve all blocks
byte[] data = new byte[totalSize];
int offset = 0;
... |
python | def show_idle_pc_prop(self):
"""
Dumps the idle PC proposals (previously generated).
:returns: list of idle PC proposal
"""
is_running = yield from self.is_running()
if not is_running:
# router is not running
raise DynamipsError('Router "{name}" ... |
python | def list_devices():
""" List devices via HTTP GET. """
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) |
python | def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) |
java | public void disablePresence(String privateKey, String channel,
OnDisablePresence callback) throws OrtcNotConnectedException {
if (!this.isConnected) {
throw new OrtcNotConnectedException();
} else {
String presenceUrl = this.isCluster ? this.clusterUrl : this.url;
Ortc.disablePresence(presenceUrl, this... |
java | public void findUnsafeOperatorsForDDL(UnsafeOperatorsForDDL ops) {
if ( ! m_type.isSafeForDDL()) {
ops.add(m_type.symbol());
}
if (m_left != null) {
m_left.findUnsafeOperatorsForDDL(ops);
}
if (m_right != null) {
m_right.findUnsafeOperatorsForD... |
python | def load_map(map, src_file, output_dir, scale=1, cache_dir=None, datasources_cfg=None, user_styles=[], verbose=False):
""" Apply a stylesheet source file to a given mapnik Map instance, like mapnik.load_map().
Parameters:
map:
Instance of mapnik.Map.
sr... |
python | def _read_object(self, correlation_id, parameters):
"""
Reads configuration file, parameterizes its content and converts it into JSON object.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param parameters: values to parameters the configuratio... |
java | public void mapInPlace(Function<Double, Double> fn) {
for (int i = 0; i < pointers.length; i++) {
if (pointers[i] == null) continue;
if (copyOnWrite[i]) {
copyOnWrite[i] = false;
pointers[i] = pointers[i].clone();
}
if (sparse[i]) {
for (int j = 0; j < pointers[i].l... |
java | public DiagnosticCategoryInner getSiteDiagnosticCategorySlot(String resourceGroupName, String siteName, String diagnosticCategory, String slot) {
return getSiteDiagnosticCategorySlotWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory, slot).toBlocking().single().body();
} |
java | private static String toCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
Validate.notNull(className, "className must not be null.");
if (className.endsWith("[]")) {
final StringBuilder classNameBuffer = new StringBuilder();
while (cla... |
java | private Remote getRemoteAnnotation(Annotated annotated) {
Remote remote = annotated.getAnnotation(Remote.class);
if (remote == null) {
remote = getMetaAnnotation(annotated, Remote.class);
}
return remote;
} |
java | static Matcher zeroOrMoreFalse(Matcher matcher) {
if (matcher instanceof ZeroOrMoreMatcher) {
ZeroOrMoreMatcher zm = matcher.as();
if (zm.repeated() instanceof FalseMatcher || zm.next() instanceof FalseMatcher) {
return zm.next();
}
}
return matcher;
} |
java | @Private
static StringBuilder read(Readable from) throws IOException {
StringBuilder builder = new StringBuilder();
CharBuffer buf = CharBuffer.allocate(2048);
for (; ; ) {
int r = from.read(buf);
if (r == -1) break;
buf.flip();
builder.append(buf, 0, r);
}
return builder;
... |
java | private boolean executeGitHasUncommitted() throws MojoFailureException,
CommandLineException {
boolean uncommited = false;
// 1 if there were differences and 0 means no differences
// git diff --no-ext-diff --ignore-submodules --quiet --exit-code
final CommandResult diffCom... |
java | public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
if (localName.equalsIgnoreCase(TABLE))
{
if (startTable)
if (m_record.getEditMode() == DBConstants.EDIT_ADD)
{
try {
... |
python | def create_connection(dest_pair, proxy_type=None, proxy_addr=None,
proxy_port=None, proxy_rdns=True,
proxy_username=None, proxy_password=None,
timeout=None, source_address=None,
socket_options=None):
"""create_connection(dest_pa... |
python | def get_user(self, username):
"""Retrieve information about a user
Returns:
dict: User information
None: If no user or failure occurred
"""
response = self._get(self.rest_url + "/user",
params={"username": username,
... |
java | public Observable<ServiceResponse<BackupLongTermRetentionVaultInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String serverName, String recoveryServicesVaultResourceId) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.su... |
java | public static void join(SAXSymbol left, SAXSymbol right) {
// System.out.println(" performing the join of " + getPayload(left) + " and "
// + getPayload(right));
// check for an OLD digram existence - i.e. left must have a next symbol
// if .n exists then we are joining TERMINAL symbols within t... |
java | protected Long performCommitLogic(EDBCommit commit) throws EDBException {
if (!(commit instanceof JPACommit)) {
throw new EDBException("The given commit type is not supported.");
}
if (commit.isCommitted()) {
throw new EDBException("EDBCommit is already commitet.");
... |
java | private long[] refine(long[] invariants, boolean[] hydrogens) {
int ord = g.length;
InvariantRanker ranker = new InvariantRanker(ord);
// current/next vertices, these only hold the vertices which are
// equivalent
int[] currVs = new int[ord];
int[] nextVs = new int[ord... |
python | def _get_wmi_properties(self, instance_key, metrics, tag_queries):
"""
Create and cache a (metric name, metric type) by WMI property map and a property list.
"""
if instance_key not in self.wmi_props:
metric_name_by_property = dict(
(wmi_property.lower(), (met... |
java | public void writeXml(String path, XMLOutputter doc) throws IOException {
doc.startTag(RemoteException.class.getSimpleName());
doc.attribute("path", path);
doc.attribute("class", getClassName());
String msg = getLocalizedMessage();
int i = msg.indexOf("\n");
if (i >= 0) {
msg = msg.substrin... |
java | public static JSONArray monitorForHA() {
Map<String, Cache> CACHE = Redis.unmodifiableCache();
JSONArray monitors = new JSONArray();
if (CACHE == null || CACHE.isEmpty())
return monitors;
JSONObject monitor = new JSONObject();
monitor.put("application", EnvUtil.get... |
python | def determine_context(device_ids: List[int],
use_cpu: bool,
disable_device_locking: bool,
lock_dir: str,
exit_stack: ExitStack) -> List[mx.Context]:
"""
Determine the MXNet context to run on (CPU or GPU).
:param device_... |
java | private static Object generateKey(final Object[] args) {
if (args == null) return Collections.emptyList();
Object[] copyOfArgs = copyOf(args, args.length);
return asList(copyOfArgs);
} |
python | def get_ancestors_through_subont(self, go_term, relations):
"""
Returns the ancestors from the relation filtered GO subontology of go_term's ancestors.
subontology() primarily used here for speed when specifying relations to traverse. Point of this is to first get
a smaller graph (all a... |
java | public void stop( BundleContext bundleContext )
throws Exception
{
LOG.debug( "Unbinding " + RemoteBundleContext.class.getSimpleName() );
m_registry.unbind( RemoteBundleContext.class.getName() );
UnicastRemoteObject.unexportObject( m_remoteBundleContext, true );
m_registry = ... |
java | public double sim(List<String> sentence, int index)
{
double score = 0;
for (String word : sentence)
{
if (!f[index].containsKey(word)) continue;
int d = docs.get(index).size();
Integer tf = f[index].get(word);
score += (idf.get(word) * tf * (k... |
java | public String getString( String key ) {
verifyIsNull();
Object o = get( key );
if( o != null ){
return o.toString();
}
throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] not found." );
} |
python | def checkModelIndex( self, modelIndex ):
"""
Sets the current index as the checked index.
:param modelIndex | <QModelIndex>
"""
self.checkablePopup().hide()
if not self.isCheckable():
return
self.setCheckedIndexes([model... |
python | def get_model_index(cls, model, default=True):
'''
Returns the default model index for the given model, or the list of indices if default is False.
:param model: model name as a string.
:raise KeyError: If the provided model does not have any index associated.
'''
try:
... |
java | public UnsignedTransaction createUnsignedTransaction(List<UnspentTransactionOutput> unspent, Address changeAddress,
PublicKeyRing keyRing, NetworkParameters network) throws InsufficientFundsException {
long fee = MIN_MINER_FEE;
while (true) {
UnsignedTransaction unsigned;
try {
... |
java | @Override
public synchronized RecordAlert write(int scanId, int pluginId, String alert,
int risk, int confidence, String description, String uri, String param, String attack,
String otherInfo, String solution, String reference, String evidence, int cweId, int wascId, int historyId,
... |
python | def confd_state_internal_cdb_client_subscription_twophase(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal"... |
python | def dump_bulk(cls, parent=None, keep_ids=True):
"""Dumps a tree branch to a python data structure."""
cls = get_result_class(cls)
# Because of fix_tree, this method assumes that the depth
# and numchild properties in the nodes can be incorrect,
# so no helper methods are used
... |
java | final void updateDelayInMillisecondsFrom(HttpResponse httpPollResponse) {
final Long parsedDelayInMilliseconds = delayInMillisecondsFrom(httpPollResponse);
if (parsedDelayInMilliseconds != null) {
delayInMilliseconds = parsedDelayInMilliseconds;
}
} |
python | def _get_deltas(self, rake):
"""
Return the value of deltas (delta_R, delta_S, delta_V, delta_I),
as defined in "Table 5: Model 1" pag 198
"""
# All deltas = 0 for DowrickRhoades2005SSlab Model 3: Deep Region,
# pag 198
delta_R, delta_S = 0, 0
delta_V, de... |
java | public void unmarshalling(Xdr xdr) throws RpcException {
super.unmarshalling(xdr);
unmarshallingAttributes(xdr);
if (stateIsOk()) {
_attributes = new NfsPosixAttributes();
_attributes.unmarshalling(xdr);
}
} |
python | def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = s... |
java | public byte[] getBytes() throws IOException {
if(cachedData == null){
if(getReader().available() > 0) {
cachedData = getReader().read();
}
else{
cachedData = new byte[0];
}
}
return cachedData;
} |
java | public DoubleMatrix1D solve(DoubleMatrix1D b) {
// if (b.size() != Math.max(m, n)) {
// throw new
// IllegalArgumentException("The size b must be equal to max(A.rows(), A.columns()).");
// }
if (!this.hasFullRank()) {
log.error("Matrix is rank deficient: "
+ ArrayUtils.toString(this.A.toArray()... |
python | def prepare_call_state(self, calling_state, initial_state=None,
preserve_registers=(), preserve_memory=()):
"""
This function prepares a state that is executing a call instruction.
If given an initial_state, it copies over all of the critical registers to it from the
... |
java | JournalSegmentDescriptor copyTo(ByteBuffer buffer) {
buffer.putInt(version);
buffer.putLong(id);
buffer.putLong(index);
buffer.putInt(maxSegmentSize);
buffer.putInt(maxEntries);
buffer.putLong(updated);
buffer.put(locked ? (byte) 1 : (byte) 0);
return this;
} |
python | def show_portindex_interface_info_output_show_portindex_interface_portsgroup_rbridgeid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_portindex_interface_info = ET.Element("show_portindex_interface_info")
config = show_portindex_interface_info
... |
python | def _downsample(self, how, **kwargs):
"""
Downsample the cython defined function.
Parameters
----------
how : string / cython mapped function
**kwargs : kw args passed to how function
"""
self._set_binner()
how = self._is_cython_func(how) or how
... |
java | static long getFiveBytesLong(byte[] buffer, int offset) {
return (buffer[offset] & 0xffL) << 32 | (buffer[offset + 1] & 0xffL) << 24 | (buffer[offset + 2] & 0xffL) << 16
| (buffer[offset + 3] & 0xffL) << 8 | (buffer[offset + 4] & 0xffL);
} |
python | def acquire(self):
"""Acquire the lock."""
self.lease = self.client.lease(self.ttl)
base64_key = _encode(self.key)
base64_value = _encode(self._uuid)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target':... |
python | def filter_like(self, **filters):
''' Filter query using re.compile().
**Examples**: ``query.filter_like(Name="andi")``
'''
Query = {}
for name, value in filters.items():
name = resolve_name(self.type, name)
Query[name] = re_compile(value, IGNORECASE)... |
python | def get_ldap_groups(self):
"""Retrieve groups from LDAP server."""
if (not self.conf_LDAP_SYNC_GROUP):
return (None, None)
uri_groups_server, groups = self.ldap_search(self.conf_LDAP_SYNC_GROUP_FILTER, self.conf_LDAP_SYNC_GROUP_ATTRIBUTES.keys(), self.conf_LDAP_SYNC_GROUP_INCREMENTAL... |
python | def get_size(data, default_width=0, default_height=0):
"""
Get image size
:param data: A buffer with image content
:return: Tuple (width, height, filetype)
"""
height = default_height
width = default_width
filetype = None
# Original version:
# https://github.com/shibukawa/image... |
java | public static boolean isSymbol(final char ch) {
return '(' == ch || ')' == ch || '[' == ch || ']' == ch || '{' == ch || '}' == ch || '+' == ch || '-' == ch || '*' == ch || '/' == ch || '%' == ch || '^' == ch || '=' == ch
|| '>' == ch || '<' == ch || '~' == ch || '!' == ch || '?' == ch || '&' == ... |
python | def swo_start(self, baudrate):
"""! @brief Start receiving SWO data at the given baudrate."""
try:
self._link.swo_configure(True, baudrate)
self._link.swo_control(True)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) |
java | @Override
public boolean satisfies(Match match, int... ind)
{
BioPAXElement ele0 = match.get(ind[0]);
BioPAXElement ele1 = match.get(ind[1]);
if (ele1 == null) return false;
Set vals = pa.getValueFromBean(ele0);
return vals.contains(ele1);
} |
python | def read_struct_file(struct_file,return_type=GeoStruct):
"""read an existing PEST-type structure file into a GeoStruct instance
Parameters
----------
struct_file : (str)
existing pest-type structure file
return_type : (object)
the instance type to return. Default is GeoStruct
... |
python | def version(self, path, postmap=None, **params):
"""
Return the taskforce version.
Supports standard options.
"""
q = httpd.merge_query(path, postmap)
ans = {
'taskforce': taskforce_version,
'python': '.'.join(str(x) for x in sys.version_info[:3]),
... |
java | private String makeHash(String request) throws CacheException {
RequestCtx reqCtx = null;
try {
reqCtx = m_contextUtil.makeRequestCtx(request);
} catch (MelcoeXacmlException pe) {
throw new CacheException("Error converting request", pe);
}
byte[] hash = nu... |
python | def get_cfcompliant_units(units, prefix='', suffix=''):
"""
Get equivalent units that are compatible with the udunits2 library
(thus CF-compliant).
Parameters
----------
units : string
A string representation of the units.
prefix : string
Will be added at the beginning of th... |
java | public double[] getColumn(int column) {
checkIndices(0, column);
rowReadLock.lock();
double[] values = new double[rows.get()];
for (int row = 0; row < rows.get(); ++row)
values[row] = get(row, column);
rowReadLock.unlock();
return values;
} |
java | public ClassGraph blacklistPackages(final String... packageNames) {
enableClassInfo();
for (final String packageName : packageNames) {
final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName);
if (packageNameNormalized.isEmpty()) {
... |
java | public synchronized Future<?> addIndexedColumn(ColumnDefinition cdef)
{
if (indexesByColumn.containsKey(cdef.name.bytes))
return null;
assert cdef.getIndexType() != null;
SecondaryIndex index;
try
{
index = SecondaryIndex.createInstance(baseCfs, cdef... |
python | def expand_expression(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
# pylint: disable=too-many-locals
"""Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: ... |
python | async def load_tuple(self, elem_type, params=None, elem=None, obj=None):
"""
Loads tuple of elements from the reader. Supports the tuple ref.
Returns loaded tuple.
:param elem_type:
:param params:
:param elem:
:param obj:
:return:
"""
if o... |
python | def analyze(self, file, filename):
"""
:param file: The File object itself.
:param filename: string; filename of File object, used for creating
PotentialSecret objects
:returns dictionary representation of set (for random access by hash)
... |
java | @Override
public boolean matches(Object item) {
int count = 0;
for (Matcher<?> m: matchers) {
if (m.matches(item)) {
count++;
}
}
return countMatcher.matches(count);
} |
python | def is_within(self, query, subject):
"""Accessory function to check if a range is fully within another range"""
if self.pt_within(query[0], subject) and self.pt_within(query[1], subject):
return True
return False |
python | def _delete_line(self, count=1):
"""
Deletes count lines, starting at line with cursor. As lines are
deleted, lines displayed below cursor move up. Lines added to bottom of
screen have spaces with same character attributes as last line moved
up.
"""
self.display... |
python | def import_users(self):
""" save users to local DB """
self.message('saving users into local DB')
saved_users = self.saved_admins
# loop over all extracted unique email addresses
for email in self.email_set:
owner = self.users_dict[email].get('owner')
#... |
python | def do_debug(self, args, arguments):
"""
::
Usage:
debug on
debug off
Turns the debug log level on and off.
"""
filename = path_expand("~/.cloudmesh/cmd3.yaml")
config = ConfigDict(filename=filename)
if arguments['on']:... |
java | public void setPreferredEditor(String resourceType, String editorUri) {
if (editorUri == null) {
m_editorSettings.remove(resourceType);
} else {
m_editorSettings.put(resourceType, editorUri);
}
} |
python | def run_tpm(system, steps, blackbox):
"""Iterate the TPM for the given number of timesteps.
Returns:
np.ndarray: tpm * (noise_tpm^(t-1))
"""
# Generate noised TPM
# Noise the connections from every output element to elements in other
# boxes.
node_tpms = []
for node in system.no... |
java | public void eventProcessingFailed(ActivityHandle activityHandle, FireableEventType fireableEventType,
Object object, Address address, ReceivableService receivableService, int integer,
FailureReason failureReason) {
// not used
} |
java | private void uploadPart() throws IOException {
if (mFile == null) {
return;
}
mLocalOutputStream.close();
int partNumber = mPartNumber.getAndIncrement();
File newFileToUpload = new File(mFile.getPath());
mFile = null;
mLocalOutputStream = null;
UploadPartRequest uploadRequest = new... |
python | def from_euler(self, roll, pitch, yaw):
'''fill the matrix from Euler angles in radians'''
cp = cos(pitch)
sp = sin(pitch)
sr = sin(roll)
cr = cos(roll)
sy = sin(yaw)
cy = cos(yaw)
self.a.x = cp * cy
self.a.y = (sr * sp * cy) - (cr * sy)
s... |
java | public Mapper createMapperToSubflowState(final List<DefaultMapping> mappings) {
val inputMapper = new DefaultMapper();
mappings.forEach(inputMapper::addMapping);
return inputMapper;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.