language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public CreateTableRequest getTableSchema() {
return new CreateTableRequest()
.withTableName(tableName)
.withProvisionedThroughput(new ProvisionedThroughput(client.readCapacity(tableName),
client.writeCapacity(tableName)));
} |
java | Filter getFilterProperty(String name, Filter defaultValue) {
String val = getProperty(name);
try {
if (val != null) {
return (Filter) getClassInstance(val).newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in cr... |
java | public void initLocator() throws InterruptedException,
ServiceLocatorException {
if (locatorClient == null) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Instantiate locatorClient client for Locator Server "
+ locatorEndpoints + "...");
... |
python | def inferred_var_seqs_plus_flanks(self, ref_seq, flank_length):
'''Returns start position of first flank sequence, plus a list of sequences -
the REF, plus one for each ALT.sequence. Order same as in ALT column'''
flank_start = max(0, self.POS - flank_length)
flank_end = min(len(ref_seq)... |
python | def diffn(self, diffcol: str, name: str="Diff"):
"""
Add a diff column to the main dataframe: calculate the diff
from the next value
:param diffcol: column to diff from
:type diffcol: str
:param name: diff column name, defaults to "Diff"
:type name: str, optional... |
python | def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
super(MyStomp, self).connected(msg)
self.log.info("connected: session %s" % msg['headers']['session'])
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
r... |
python | def i18n(msg, event=None, lang='en', domain='backend'):
"""Gettext function wrapper to return a message in a specified language by domain
To use internationalization (i18n) on your messages, import it as '_' and use as usual.
Do not forget to supply the client's language setting."""
if event is not No... |
java | protected void validateAnnotationValue(T originatingElement, String annotationName, T member, String memberName, Object resolvedValue) {
final AnnotatedElementValidator elementValidator = getElementValidator();
if (elementValidator != null && !erroneousElements.contains(member)) {
final bool... |
java | public static BaseResult addvoicetorecofortext(String accessToken, String voiceId, File voice) {
return addvoicetorecofortext(accessToken, voiceId, null, voice);
} |
java | @Override
public DeleteGroupPolicyResult deleteGroupPolicy(DeleteGroupPolicyRequest request) {
request = beforeClientExecution(request);
return executeDeleteGroupPolicy(request);
} |
python | def user_group_perms_processor(request):
"""
return context variables with org permissions to the user.
"""
org = None
group = None
if hasattr(request, "user"):
if request.user.is_anonymous:
group = None
else:
group = request.user.get_org_group()
... |
python | def classFactory(iface):
"""Load Plugin class from file Plugin."""
# Try to import submodule to check if there are present.
try:
from parameters.generic_parameter import GenericParameter
except ImportError:
# Don't use safe.utilities.i18n.tr as we need to be outside of `safe`.
# ... |
java | public static KerasLayer getKerasLayerFromConfig(Map<String, Object> layerConfig,
KerasLayerConfiguration conf,
Map<String, Class<? extends KerasLayer>> customLayers,
... |
java | public static List<Dashboard> findSharedDashboardsMeta(EntityManager em, PrincipalUser owner, Integer limit, String version) {
requireArgument(em != null, "Entity manager can not be null.");
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQue... |
java | public void setBlacklist(InetAddress[] addresses) {
if (addresses == null) {
throw new NullPointerException("addresses");
}
blacklist.clear();
for (int i = 0; i < addresses.length; i++) {
InetAddress addr = addresses[i];
block(addr);
}
} |
python | def check_type(value, type_def):
"""Check if the value is in the type given in type_def.
Args:
value: the var to test.
type_def: string representing the type in swagger.
Returns:
True if the type is correct, False otherwise.
"""
if type_def =... |
python | def _wmorlet(f0, sd, sampling_rate, ns=5):
"""
adapted from nitime
returns a complex morlet wavelet in the time domain
Parameters
----------
f0 : center frequency
sd : standard deviation of frequency
sampling_rate : samplingrate
ns : window length in number of stand... |
python | def get_schema_dict(self, table):
"""
Retrieve the database schema in key, value pairs for easier
references and comparisons.
"""
# Retrieve schema in list form
schema = self.get_schema(table, with_headers=True)
# Pop headers from first item in list
heade... |
java | public static Matcher<Result> anyString() {
return new Matcher<Result>() {
@Override
public Result matches(String input, boolean isEof) {
return input.length() > 0 ? success(input, "", input) : failure(input, false);
}
@Override
public... |
python | def validate_rmq_ssl_enabled_units(self, sentry_units, port=None):
"""Check that ssl is enabled on rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:param port: optional ssl port override to validate
:returns: None if successful, otherwise return error message
... |
java | final void doWith(final MappedFieldMetaData metaData) {
if (metaData == null) {
throw new IllegalArgumentException("Method argument metaData must not be null.");
}
// Prepare the dynamic contextual data of this mapping
final FieldData fieldData = new FieldData(metaData, eval... |
java | public synchronized File startNewFile(long timestamp) {
if (debugLogger.isLoggable(Level.FINE) && LogRepositoryBaseImpl.isDebugEnabled()) {
debugLogger.logp(Level.FINE, thisClass, "startNewFile", "unsentEmpty: "+unsentFileNotifications.isEmpty()+
" tstamp: "+timestamp+" Tp: "+managedType+" subProcCommAgent: "+... |
python | def telemetry(fn):
"""
Decorator for CLI and other functions that need special Sentry client handling.
This function is only required for functions that may exit *before* we set up
the ._raven_client object on the Api instance *or* that specifically catch and re-raise
exceptions or call sys.exit dir... |
java | private boolean restartScanning() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mScanHelper.stopAndroidOBackgroundScan();
}
long scanPeriod = mScanState.getBackgroundMode() ? mScanState.getBackgroundScanPeriod() : mScanState.getForegroundScanPeriod();
long betweenSc... |
java | public boolean validate(String xmlText) throws SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// This section removes the schema hint as we have the schema docs
// otherwise exceptions may be thrown
try {
DocumentBuilder b = factory... |
python | def create_or_update_release(user, pwd, secret, repo_slug, changelog_file, doc_url, data_file, tag):
"""
Creates or updates (TODO)
a github release corresponding to git tag <TAG>.
"""
# 1- AUTHENTICATION
if user is not None and secret is None:
# using username and password
# vali... |
java | public PExp findExpression(PExp exp, int lineno)
{
try
{
return exp.apply(af.getExpExpressionFinder(), lineno);// FIXME: should we handle exceptions like this
} catch (AnalysisException e)
{
return null; // Most have none
}
} |
java | public static MetadataTemplate getMetadataTemplate(BoxAPIConnection api, String templateName) {
String scope = scopeBasedOnType(templateName);
return getMetadataTemplate(api, templateName, scope);
} |
python | def validator(ch):
"""
Update screen if necessary and release the lock so receiveThread can run
"""
global screen_needs_update
try:
if screen_needs_update:
curses.doupdate()
screen_needs_update = False
return ch
finally:
winlock.release()
s... |
java | public static List<CommerceDiscountUserSegmentRel> toModels(
CommerceDiscountUserSegmentRelSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<CommerceDiscountUserSegmentRel> models = new ArrayList<CommerceDiscountUserSegmentRel>(soapModels.length);
for (CommerceDiscountUserSegmentRelSoap ... |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
public static <K, V> V getValue(ConcurrentMap<K, CacheEntry<V>> map, K key, long timeoutMillis, Callable<V> updater, Callable<? extends CacheEntry> cacheEntryFactory, boolean returnExpiredWhileUpdating, Object cacheRequestObject) {
CacheEntry<V> cacheEntry = ma... |
java | private Token<DelegationTokenIdentifier> fetchHcatToken(final String userToProxy,
final HiveConf hiveConf, final String tokenSignatureOverwrite, final Logger logger)
throws IOException, MetaException, TException {
logger.info(HiveConf.ConfVars.METASTOREURIS.varname + ": "
+ hiveConf.get(HiveCon... |
java | public int computeDatanodeWork() throws IOException {
int workFound = 0;
int blocksToProcess = 0;
int nodesToProcess = 0;
// blocks should not be replicated or removed if safe mode is on
if (isInSafeMode()) {
updateReplicationCounts(workFound);
return workFound;
}
synchronized (h... |
python | def make_article_info_funding(self, article_info_div):
"""
Creates the element for declaring Funding in the article info.
"""
funding_group = self.article.root.xpath('./front/article-meta/funding-group')
if funding_group:
funding_div = etree.SubElement(article_info_di... |
java | public Cell<?> applySpacing (final Cell<?> cell) {
cell.space(top, left, bottom, right);
return cell;
} |
python | def t_doublequote_end(self, t):
r'"'
t.value = t.lexer.string_value
t.type = 'ID'
t.lexer.string_value = None
t.lexer.pop_state()
return t |
java | public String getUserID(String globusID) {
String [] ids = getUserIDs(globusID);
if (ids != null && ids.length > 0) {
return ids[0];
} else {
return null;
}
} |
java | void removeSuperToast(final SuperToast superToast) {
// If the SuperToast is a SuperActivityToast, remove it from the supplied ViewGroup
if (superToast instanceof SuperActivityToast) {
// If SuperActivityToast has already been dismissed, do not attempt to dismiss it again
if ... |
java | @Override
public void validateElementStart(String localName, String uri, String prefix)
throws XMLStreamException
{
// Ok, can we find the element definition?
mTmpKey.reset(prefix, localName);
DTDElement elem = mElemSpecs.get(mTmpKey);
// whether it's found or not, let's ... |
java | private void parse(DerValue val)
throws IOException, CertificateException
{
if (val.tag != DerValue.tag_Sequence) {
throw new IOException
("Sequence tag missing for X509CertificatePair");
}
while (val.data != null && val.data.available() != 0) {
... |
java | private Boolean[] asBooleans( List<Object> values ) {
ValueFactory<Boolean> factory = valueFactories.getBooleanFactory();
Boolean[] res = new Boolean[values.size()];
for (int i = 0; i < res.length; i++) {
res[i] = factory.create(values.get(i));
}
return res;
} |
python | def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever t... |
python | def format_account(service_name, data):
"""
Given profile data and the name of a
social media service, format it for
the zone file.
@serviceName: name of the service
@data: legacy profile verification
Returns the formatted account on success,
as a dict.
"""
if "username" not i... |
java | private void commonConsoleLogHandlerUpdates() {
if (consoleLogHandler != null) {
consoleLogHandler.setBasicFormatter(formatter);
consoleLogHandler.setConsoleLogLevel(consoleLogLevel.intValue());
consoleLogHandler.setCopySystemStreams(copySystemStreams);
}
} |
java | public static boolean isInternalType(Types typeUtils, TypeMirror type) {
Element element = ((TypeElement) typeUtils.asElement(type)).getEnclosingElement();
return element.getKind() != ElementKind.PACKAGE;
} |
java | public ServiceFuture<List<StorageAccountItem>> getStorageAccountsAsync(final String vaultBaseUrl, final Integer maxresults, final ListOperationCallback<StorageAccountItem> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
getStorageAccountsSinglePageAsync(vaultBaseUrl, maxresults),
... |
java | public static List<SQLProperty> extractUsedProperties(Builder methodBuilder, SQLiteModelMethod method, Class<? extends Annotation> annotationClazz) {
SQLiteEntity entity = method.getEntity();
List<SQLProperty> listPropertyInContentValue = new ArrayList<SQLProperty>();
Set<String> foundColumns = JQLChecker.getIns... |
python | def hashed_download(url, temp, digest):
"""Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``,
and return its path."""
# Based on pip 1.4.1's URLOpener but with cert verification removed
def opener():
opener = build_opener(HTTPSHandler())
# Strip out HTTPHandler to pre... |
java | public static String encode(String decoded_string, String crypto_algorithm, Map<String, String> properties)
throws InvalidPasswordEncodingException, UnsupportedCryptoAlgorithmException {
/*
* check input:
*
* -- decoded_string: any string, any length, cannot be nu... |
python | def _get_command_args(self, command, args):
'''Work out the command arguments for a given command'''
command_args = {}
command_argument_names =\
command.__code__.co_varnames[:command.__code__.co_argcount]
for varname in command_argument_names:
if varname == 'args... |
java | public void setOnKeyUp(String onKeyUp) {
_anchorState.registerAttribute(AbstractHtmlState.ATTR_JAVASCRIPT, HtmlConstants.ONKEYUP, onKeyUp);
} |
java | static void applyUriConnectionSettings(RedisURI from, RedisURI to) {
if (from.getPassword() != null && from.getPassword().length != 0) {
to.setPassword(new String(from.getPassword()));
}
to.setTimeout(from.getTimeout());
to.setSsl(from.isSsl());
to.setStartTls(from.... |
python | def tolineno(self):
"""The last line that this node appears on in the source code.
:type: int or None
"""
if not self._astroid_fields:
# can't have children
lastchild = None
else:
lastchild = self.last_child()
if lastchild is None:
... |
java | private static String hex4(char c) {
char[] r = new char[] { '0', '0', '0', '0' };
int i = 3;
while (c > 0) {
r[i] = HEX_DIGITS[c & 0xF];
c >>>= 4;
--i;
}
return new String(r);
} |
java | public String[] getColumnNames() throws RepositoryException
{
try
{
String[] propNames = new String[selectProps.length];
for (int i = 0; i < selectProps.length; i++)
{
propNames[i] = session.getLocationFactory().createJCRName(selectProps[i]).getAsString();
... |
python | def visit_USR(self, node):
""" Machine code call from basic
"""
self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t)
self.emit('call', 'USR', node.type_.size)
backend.REQUIRES.add('usr.asm') |
python | def get_pager(self, *path, **kwargs):
""" A generator for all the results a resource can provide. The pages
are lazily loaded. """
page_arg = kwargs.pop('page_size', None)
limit_arg = kwargs.pop('limit', None)
kwargs['limit'] = page_arg or limit_arg or self.default_page_size
... |
python | def transpose(self) -> 'TextDiagramDrawer':
"""Returns the same diagram, but mirrored across its diagonal."""
out = TextDiagramDrawer()
out.entries = {(y, x): _DiagramText(v.transposed_text, v.text)
for (x, y), v in self.entries.items()}
out.vertical_lines = [_Vert... |
python | def format_message_type(message_type):
"""
Get printable version for message type
:param message_type: Message type
:type message_type: int
:return: Printable version
:rtype: str
"""
if message_type == MsgType.NOT_SET:
return "NOT_SET"
elif message_type == MsgType.ACK:
... |
java | static Downloader createDefaultDownloader() {
try {
Class.forName("okhttp3.OkHttpClient");
return OkHttpDownloader.create();
} catch (ClassNotFoundException ignored) {
}
return URLDownloader.create();
} |
python | def recover_release_data(app_folder):
"""
Given the path to an app folder where an app was just built, return a
dictionary containing the data emitted from running the buildpack's release
script.
Relies on the builder.sh script storing the release data in ./.release.yaml
inside the app folder.
... |
python | def format_payload(self, api_version, data):
""" Return appropriate QualysGuard API call.
"""
# Check if payload is for API v1 or API v2.
if (api_version in (1, 2)):
# Check if string type.
if type(data) == str:
# Convert to dictionary.
... |
java | private void write(final Collection<Writer> writers, final Task task) {
try {
Writer writer = task.writer;
writer.write(task.logEntry);
if (!writers.contains(writer)) {
writers.add(writer);
}
} catch (Exception ex) {
InternalLogger.log(Level.ERROR, ex, "Failed to write log entry '" + task.logEntr... |
java | public static long highestOneBit(long i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
i |= (i >> 32);
return i - (i >>> 1);
} |
java | public long getDurationMicro() {
if (startNano != 0) {
if (running)
return ((long)(System.nanoTime() - startNano)) / 1000;
else if (stopNano != startNano)
return ((long)(stopNano - startNano)) / 1000;
}
return 0;
} |
java | public static TaggedValue newTaggedValue(Tag tag, Object value) {
if (tag == null) {
throw new IllegalArgumentException("tag must not be null");
}
return new TaggedValue(tag, value);
} |
java | @Override
public <S extends T> long count(final Example<S> example) {
final Map<String, Object> bindVars = new HashMap<>();
final String predicate = exampleConverter.convertExampleToPredicate(example, bindVars);
final String filter = predicate.length() == 0 ? "" : " FILTER " + predicate;
final String query = S... |
java | private static Set<EquivalentAddressGroup> stripAttrs(List<EquivalentAddressGroup> groupList) {
Set<EquivalentAddressGroup> addrs = new HashSet<>(groupList.size());
for (EquivalentAddressGroup group : groupList) {
addrs.add(new EquivalentAddressGroup(group.getAddresses()));
}
return addrs;
} |
java | private static void compareSets(Delta delta, Collection deltas, LinkedList stack, ID idFetcher)
{
Set srcSet = (Set) delta.srcValue;
Set targetSet = (Set) delta.targetValue;
// Create ID to Object map for target Set
Map targetIdToValue = new HashMap();
for (Object targetValu... |
python | def sign_create_cancellation(cancellation_params, key_pair):
"""
Function to sign the parameters required to create a cancellation request from the Switcheo Exchange.
Execution of this function is as follows::
sign_create_cancellation(cancellation_params=signable_params, key_pair=key_pair)
The... |
java | private Map<String, String> mergeItem(
String item,
Map<String, String> localeValues,
Map<String, String> resultLocaleValues) {
if (resultLocaleValues.get(item) != null) {
if (localeValues.get(item) != null) {
localeValues.put(item, localeValues.get(it... |
java | private String queryPlaceholder(int length) {
StringBuilder sb = new StringBuilder(length * 2 + 1);
sb.append("(?");
for (int i = 1; i < length; i++) {
sb.append(",?");
}
sb.append(")");
return sb.toString();
} |
java | public static Object setBeanProperties(MetaClass mc, Object bean, Map properties) {
for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
... |
java | public void appendUpdateEvent(final Object rowKey, final int colIndex, final Object rowData, final Object oldValue,
final Object newValue) {
updates.add(new SheetUpdate(rowKey, colIndex, rowData, oldValue, newValue));
} |
java | public static <S extends State<S, T>, T extends Transition<S, T>> void verifyModel(
StateModel<S, T> stateModel) throws StateModelException {
if (stateModel.getStartState() == null) {
throw new StateModelException("No start state is defined.");
}
if (stateModel.getStartState().getTransitions() == null) {
... |
python | def get_token(opts, tok):
'''
Fetch the token data from the store.
:param opts: Salt master config options
:param tok: Token value to get
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not os.path.isfile(t_path):
re... |
java | public static Object getPrimitiveDefaultValue(Class<?> primitiveType) {
if (boolean.class.equals(primitiveType)) {
return false;
} else if (byte.class.equals(primitiveType)) {
return (byte) 0;
} else if (char.class.equals(primitiveType)) {
return '\0';
... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/transportation/1.0", name = "Track", substitutionHeadNamespace = "http://www.opengis.net/citygml/transportation/1.0", substitutionHeadName = "TransportationComplex")
public JAXBElement<TrackType> createTrack(TrackType value) {
return new JAXBElemen... |
python | def download_caffe_model(model_name, meta_info, dst_dir='./model'):
"""Download caffe model into disk by the given meta info """
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
model_name = os.path.join(dst_dir, model_name)
assert 'prototxt' in meta_info, "missing prototxt url"
proto_url, ... |
python | def remove(self, index):
'''Return new tree with index removed.'''
newtree = LookupTree()
newtree.root = _remove_down(self.root, index, 0)
return newtree |
java | public static <A, B, C, D, E, F, G, H> Choice8<A, B, C, D, E, F, G, H> c(C c) {
return new _C<>(c);
} |
java | private void adjustOptionsColumn(
CmsMessageBundleEditorTypes.EditMode oldMode,
CmsMessageBundleEditorTypes.EditMode newMode) {
if (m_model.isShowOptionsColumn(oldMode) != m_model.isShowOptionsColumn(newMode)) {
m_table.removeGeneratedColumn(TableProperty.OPTIONS);
if (m... |
python | def delling_network():
""" Architecture according to Duelling DQN:
https://arxiv.org/abs/1511.06581
"""
@tt.model(tracker=tf.train.ExponentialMovingAverage(1 - .0005), # TODO: replace with original weight freeze
optimizer=tf.train.RMSPropOptimizer(6.25e-5, .95, .95, .01))
... |
java | public ServiceCall<InputStream> getCoreMlModel(GetCoreMlModelOptions getCoreMlModelOptions) {
Validator.notNull(getCoreMlModelOptions, "getCoreMlModelOptions cannot be null");
String[] pathSegments = { "v3/classifiers", "core_ml_model" };
String[] pathParameters = { getCoreMlModelOptions.classifierId() };
... |
python | def _add_umis_with_fastp(read_fq, umi_fq, out_fq, cores):
"""Add UMIs to reads from separate UMI file using fastp.
"""
with utils.open_gzipsafe(umi_fq) as in_handle:
in_handle.readline() # name
umi_size = len(in_handle.readline().strip())
cmd = ("fastp -Q -A -L -G -w 1 --in1 {read_fq} -... |
java | public static Properties loadProperties(final URL fileURL) {
checkNotNull("fileURL", fileURL);
final Properties props = new Properties();
try (final InputStream inStream = fileURL.openStream()) {
props.load(inStream);
} catch (final IOException ex) {
throw new Run... |
java | public Signature getSignatureFrom(SignerIdentifier signer) {
return signatures.stream()
.filter(signatureFrom(signer))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unable to find signature from this signer"));
} |
java | public void setListType(com.google.api.ads.adwords.axis.v201809.rm.UserListType listType) {
this.listType = listType;
} |
java | public static Resource getResultResource(final JavaSparkContext sparkContext,
final SparkJobContext sparkJobContext) {
final HdfsHelper hdfsHelper = new HdfsHelper(sparkContext);
URI resultPath = sparkJobContext.getResultPath();
if (resultPath == null) {
resultPath = URI... |
java | @Override
public void initModule() throws ModuleInitializationException {
// pidNamespace (required, 1-17 chars, a-z, A-Z, 0-9 '-' '.')
m_pidNamespace = getParameter("pidNamespace");
if (m_pidNamespace == null) {
throw new ModuleInitializationException(
"pidNa... |
java | public void updateUserMeta(final long userId, final String key, final String value) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = connectionSupplier.getConnection();
stmt = conn.prepareStatement(firstUserMetaIdSQL... |
java | public static String fromURI(String s, boolean preserveCase) {
Matcher m = TextUtils.getMatcher(URI_SPLITTER,s);
if(!m.matches()) {
// not an authority-based URI scheme; return unchanged
TextUtils.recycleMatcher(m);
return s;
}
// preallocate enough sp... |
java | public Object setProperty(String key, XmpArray value) {
return super.setProperty(key, value.toString());
} |
python | def connectionLost(self, reason):
"""Called when the connection is lost to the server."""
self.factory.loader.db.session.commit()
if reactor.running:
reactor.stop() |
python | def main(self, c):
"""
:type c: Complex
:rtype: Sfix
"""
conj = self.conjugate.main(c)
mult = self.complex_mult.main(c, conj)
angle = self.angle.main(mult)
self.y = self.GAIN_SFIX * angle
return self.y |
python | def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
VShadowFileEntry: file entry or None if not available.
"""
path_spec = vshadow_path_spec.VShadowPathSpec(
location=self.LOCATION_ROOT, parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) |
java | public SimpleDialog multiChoiceItems(CharSequence[] items, int... selectedIndexes){
if(mListView == null)
initListView();
mMode = MODE_MULTI_ITEMS;
mAdapter.setItems(items, selectedIndexes);
super.contentView(mListView);
return this;
} |
java | @XmlElementWrapper(name = "entries")
@XmlElement(name = "entry", nillable = true, type = Object.class)
@JsonProperty(value = "entries")
@ApiModelProperty(value = "The elements of the page.")
@Override
public List<Object> getEntries() {
return entries;
} |
python | def get_random_range(a, b, randfunc=None):
"""getRandomRange(a:int, b:int, randfunc:callable):long
Return a random number n so that a <= n < b.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
ra... |
python | def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None):
"""
This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.