language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if isinstance(frame, FrameGetAllNodesInformationConfirmation):
self.number_of_nodes = frame.number_of_nodes
# We are still waiting for FrameGetAllNodesInformationNoti... |
python | def generate_template(context, config, cloudformation):
"""call cloudformation to generate the template (json format).
:param context:
:param config:
:param cloudformation:
:return:
"""
spec = inspect.getargspec(cloudformation.generate_template)[0]
if len(spec) == 0:
return clou... |
java | public static List<ActionRef> imports(Xml root)
{
Check.notNull(root);
if (!root.hasChild(NODE_ACTIONS))
{
return Collections.emptyList();
}
final Xml node = root.getChild(NODE_ACTIONS);
return getRefs(node);
} |
python | def load_from_string(self, content, container, **opts):
"""
Load config from XML snippet (a string 'content').
:param content:
XML snippet string of str (python 2) or bytes (python 3) type
:param container: callble to make a container object
:param opts: optional key... |
python | def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with ... |
python | def download(cls):
"""Downloads all the views from server for the registered model
documents into the defined :attr:`VIEW_PATHS` directory.
This method **removes** previous views directory if exist.
"""
cls._check_folder()
os.chdir(cls.VIEWS_PATH)
# iterate docum... |
python | def getsize(store, path=None):
"""Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1."""
path = normalize_storage_path(path)
if hasattr(store, 'getsize'):
# pass through
return store.getsize(path)
elif ... |
python | def create_image_plugin(filename, image, parent_plugin, **kwargs):
"""
Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.
"""
from cmsplugin_filer_image.models import FilerImage
... |
java | public static <T> void moveList(List<T> fromList, List<T> toList) {
for (Iterator<T> iter = fromList.iterator(); iter.hasNext(); ) {
T elem = iter.next();
iter.remove();
toList.add(elem);
}
} |
java | @Override
public DescribeSchemasResult describeSchemas(DescribeSchemasRequest request) {
request = beforeClientExecution(request);
return executeDescribeSchemas(request);
} |
python | def get_candidates(self, obj):
"""
CandidateElections.
"""
return CandidateElectionSerializer(
obj.candidate_elections.all(), many=True
).data |
python | def unused(self, _dict):
"""
Remove empty parameters from the dict
"""
for key, value in _dict.items():
if value is None:
del _dict[key]
return _dict |
java | public boolean addChangedFile(final File changedFile) {
if (null != changedFile) {
return addChangedFile(new ChangedFile(changedFile));
} else {
log.warn("The changedFile parameter was unexpectedly null. Ignored.");
return false;
}
} |
java | private SessionTicketKey deriveKeyFromSeed(String seed) {
byte[] seedBin = decodeHex(seed);
byte[] keyName = hkdf(seedBin, salt, NAME_BYTES, SessionTicketKey.NAME_SIZE);
byte[] aesKey = hkdf(seedBin, salt, AES_BYTES, SessionTicketKey.AES_KEY_SIZE);
byte[] hmacKey = hkdf(seedBin, salt, HM... |
python | def cmd_show(docid):
"""
Arguments: <doc_id>
Show document information (but not its content, see 'dump').
See 'search' for the document id.
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args": "(xxxx, )"
}
... |
java | public static String computePasswordHash(final String password, final byte[] salt) {
if (StringMan.isEmpty(password))
return (StringMan.encodeBytesToString(salt));
final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 2048, 160);
SecretKeyFactory f;
try {
f = SecretKeyFactory.get... |
java | public BasicBlock lookupBlockByLabel(int blockLabel) {
for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
BasicBlock basicBlock = i.next();
if (basicBlock.getLabel() == blockLabel) {
return basicBlock;
}
}
return null;
} |
java | public static DiseasePanel load(InputStream diseasePanelInputStream) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(diseasePanelInputStream, DiseasePanel.class);
} |
python | def collect_analysis(using):
"""
generate the analysis settings from Python land
"""
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) |
python | def cdk_module_matches_env(env_name, env_config, env_vars):
"""Return bool on whether cdk command should continue in current env."""
if env_config.get(env_name):
current_env_config = env_config[env_name]
if isinstance(current_env_config, type(True)) and current_env_config:
return Tru... |
python | def peekline(self):
"""
Peeks a line into the FIFO.
Perfroms the same function as readline() without removing data from the
FIFO. See readline() for further information.
"""
self.__append()
i = self.buf.find(self.eol, self.pos)
if i < 0:
retu... |
java | public ServiceFuture<VirtualNetworkPeeringInner> createOrUpdateAsync(String resourceGroupName, String virtualNetworkName, String virtualNetworkPeeringName, VirtualNetworkPeeringInner virtualNetworkPeeringParameters, final ServiceCallback<VirtualNetworkPeeringInner> serviceCallback) {
return ServiceFuture.fromRe... |
java | @Override
public CreateLocationEfsResult createLocationEfs(CreateLocationEfsRequest request) {
request = beforeClientExecution(request);
return executeCreateLocationEfs(request);
} |
java | public ServiceFuture<Void> updateAsync(String resourceGroupName, String accountName, String storageAccountName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, storageAccountName), serviceCallback);
} |
java | private void updateFilter()
{
List<RowFilter<TableModel, Integer>> regexFilters =
new ArrayList<RowFilter<TableModel, Integer>>();
for (int i = 0; i < textFields.size(); i++)
{
JTextField textField = textFields.get(i);
if (textField == null)
... |
python | def mk_definition(defn):
"""Instantiates a struct or SBP message specification from a parsed
"AST" of a struct or message.
Parameters
----------
defn : dict
Returns
----------
A Definition or a specialization of a definition, like a Struct
"""
assert len(defn) == 1
identifier, contents = next(i... |
java | public static CommerceWishList findByG_U_Last(long groupId, long userId,
OrderByComparator<CommerceWishList> orderByComparator)
throws com.liferay.commerce.wish.list.exception.NoSuchWishListException {
return getPersistence()
.findByG_U_Last(groupId, userId, orderByComparator);
} |
java | public List<Assignment> enumerateAllModels(final BDD bdd, final Collection<Variable> variables) {
final Set<Assignment> res = new HashSet<>();
final List<byte[]> models = this.kernel.allSat(bdd.index());
final SortedSet<Integer> temp;
if (variables == null)
temp = new TreeSet<>(this.var2idx.values... |
python | def _inherited_panel(panel, base_panels_from_pillar, ret):
'''Return a panel with properties from parents.'''
base_panels = []
for base_panel_from_pillar in base_panels_from_pillar:
base_panel = __salt__['pillar.get'](base_panel_from_pillar)
if base_panel:
base_panels.append(base... |
java | public static String cleanSequence(String sequence) {
assert sequence != null;
final Matcher m = SequenceUtil.WHITE_SPACE.matcher(sequence);
sequence = m.replaceAll("").toUpperCase();
return sequence;
} |
python | def cart2polar(x, y, center=np.array([0, 0])):
"""
transforms cartesian coords [x,y] into polar coords [r,phi] in the frame of the lense center
:param coord: set of coordinates
:type coord: array of size (n,2)
:param center: rotation point
:type center: array of size (2)
:returns: array of... |
java | public Observable<Void> cancelSyncAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName) {
return cancelSyncWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
... |
java | private boolean imageRequiresPull(boolean hasImage, ImagePullPolicy pullPolicy, String imageName)
throws MojoExecutionException {
// The logic here is like this (see also #96):
// otherwise: don't pull
if (pullPolicy == ImagePullPolicy.Never) {
if (!hasImage) {
... |
python | def is_subtype (type, base):
""" Same as is_derived. Should be removed.
"""
assert isinstance(type, basestring)
assert isinstance(base, basestring)
# TODO: remove this method
return is_derived (type, base) |
python | def action_verb(self):
"""
The host portion of the `ppaction://` URL contained in the action
attribute. For example 'customshow' in
'ppaction://customshow?id=0&return=true'. Returns |None| if no action
attribute is present.
"""
url = self.action
if url is... |
java | int run(String[] args) {
try {
handleOptions(args);
// the following gives consistent behavior with javac
if (classes == null || classes.size() == 0) {
if (options.help || options.version || options.fullVersion)
return EXIT_OK;
... |
java | private boolean equivFields(JSField one, JSField two) {
if (one instanceof JSDynamic) {
return two instanceof JSDynamic;
}
else if (one instanceof JSEnum) {
return two instanceof JSEnum;
}
else if (one instanceof JSPrimitive) {
return (two instanceof JSPrimitive)
&& ((JSPri... |
python | def to_geojson(self, filename, proj, metadata=None):
"""
Output the data in the STObject to a geoJSON file.
Args:
filename: Name of the file
proj: PyProj object for converting the x and y coordinates back to latitude and longitue values.
metadata: Metadata de... |
python | def extract_table_names(query):
""" Extract table names from an SQL query. """
# a good old fashioned regex. turns out this worked better than actually parsing the code
tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE)
tables = [tbl
for block in tabl... |
python | def _prepare_for_training(self, records, mini_batch_size=None, job_name=None):
"""Set hyperparameters needed for training.
Args:
* records (:class:`~RecordSet`): The records to train this ``Estimator`` on.
* mini_batch_size (int or None): The size of each mini-batch to use when ... |
java | public static void printQuotedSymbol(Appendable out, CharSequence text)
throws IOException
{
if (text == null)
{
out.append("null.symbol");
}
else
{
out.append('\'');
printCodePoints(out, text, EscapeMode.ION_SYMBOL);
ou... |
java | @Override
public final IConverterByName<IRecordSet<RS>, ?> lazyGet(
final Map<String, Object> pAddParam,
final String pBeanName) throws Exception {
IConverterByName<IRecordSet<RS>, ?> convrt =
this.convertersMap.get(pBeanName);
if (convrt == null) {
// locking:
synchronized (this.c... |
java | private boolean matches6004( ApiDifference apiDiff )
{
throwIfMissing( true, false, true, true );
if ( !SelectorUtils.matchPath( field, apiDiff.getAffectedField() ) )
{
return false;
}
String[] args = getArgs( apiDiff );
String diffFrom = args[0];
... |
java | public void println(float f) throws IOException
{
String value = Float.toString(f);
this.output.write(value.getBytes(), 0, value.length());
this.output.write(CRLF, 0, 2);
} |
java | private static Feature parseLine(String s) {
//FIXME update to use regex split on tabs
//FIXME better errors on parse failures
String[] line = p.split(s);
String seqname =line[0].trim();
String source =line[1].trim();
String type =line[2].trim();
String locStart =line[3].trim();
String locEnd =line... |
java | private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)
{
if (m_writeTimphasedData && mpx.getHasTimephasedData())
{
List<TimephasedDataType> list = xml.getTimephasedData();
ProjectCalendar calendar = mpx.getCalendar();
BigInteger a... |
java | private void printBand(GroupCache gc, Band staticBand, boolean hasFunction, boolean usePrevious)
throws QueryException {
Band band;
List<FunctionCache> fCache = null;
isDetail = false;
boolean isPageHeaderFooter = false;
if (gc == null) {
if (staticBand !... |
python | def auth_required(self):
"""
If any ancestor required an authentication, this node needs it too.
"""
if self._auth:
return self._auth, self
return self.__parent__.auth_required() |
java | public static void main(String[] args) throws Exception {
boolean usage = false;
int serverPort = 0;
int driverPort = 0;
for (String arg : args) {
if (!arg.startsWith("--")) {
System.err.println("All arguments must start with '--': " + arg);
usage = true;
break;
}
... |
java | protected void close() {
this.authenticating = false;
// cancel pending futures
for (Future future : pendingFutures) {
future.cancel(false);
CancellableRunnable runnable = cancellables.get(future);
if (runnable != null) {
runnable.cancel();
... |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case XbasePackage.XCOLLECTION_LITERAL__ELEMENTS:
getElements().clear();
getElements().addAll((Collection<? extends XExpression>)newValue);
return;
}
super.eSet(featureID, newValue);... |
python | def _trim_whitespace(self, char): # For loading text assets only
"""
Internal. Trims white space pixels from the front and back of loaded
text characters
"""
psum = lambda x: sum(sum(x, []))
if psum(char) > 0:
is_empty = True
while is_empty: # F... |
python | def adapt(self, other: 'BinningBase'):
"""Adapt this binning so that it contains all bins of another binning.
Parameters
----------
other: BinningBase
"""
# TODO: in-place arg
if np.array_equal(self.bins, other.bins):
return None, None
elif no... |
python | def show_key(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.e... |
python | def get_state_change_with_balance_proof_by_locksroot(
storage: sqlite.SQLiteStorage,
canonical_identifier: CanonicalIdentifier,
locksroot: Locksroot,
sender: Address,
) -> sqlite.StateChangeRecord:
""" Returns the state change which contains the corresponding balance
proof.
... |
python | def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True):
"""
Create a new interval based on the current one and the provided values.
If current interval is not atomic, it is extended or restricted such that
its enclosure satisfies the new bounds. In other words... |
python | async def copy_context_with(ctx: commands.Context, *, author=None, channel=None, **kwargs):
"""
Makes a new :class:`Context` with changed message properties.
"""
# copy the message and update the attributes
alt_message: discord.Message = copy.copy(ctx.message)
alt_message._update(channel or alt... |
java | public void setCustomHttpHeader(String headerName, String headerValue) {
if(CONTENT_TYPE.equals(headerName) || HOST.equals(headerName)
|| CONTENT_LENGTH.equals(headerName)) {
throw new XMLRPCRuntimeException("You cannot modify the Host, Content-Type or Content-Length header.");
}
httpParameters.put(headerN... |
java | public static ParameterizedAnalyticsQuery parameterized(final String statement,
final JsonArray positionalParams, final AnalyticsParams params) {
return new ParameterizedAnalyticsQuery(statement, positionalParams, null, params);
} |
python | def getLocalElasticityByTime(self, bp, frameGap, helical=False, unit='kT', outFile=None):
r"""Calculate local elastic properties as a function of time for convergence check
It can be used to obtained elastic properties as a function of time.
.. note:: Elastic properties cannot be calculated us... |
python | def main():
"""Provide the program's entry point when directly executed."""
if len(sys.argv) != 2:
print("Usage: {} USERNAME".format(sys.argv[0]))
return 1
authenticator = prawcore.TrustedAuthenticator(
prawcore.Requestor("prawcore_read_only_example"),
os.environ["PRAWCORE_C... |
python | def reftrack_task_data(rt, role):
"""Return the data for the task that is loaded by the reftrack
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data fo... |
java | @Override
public ListTagsForDeliveryStreamResult listTagsForDeliveryStream(ListTagsForDeliveryStreamRequest request) {
request = beforeClientExecution(request);
return executeListTagsForDeliveryStream(request);
} |
python | def create_app():
"""Flask application factory function."""
app = Flask(__name__)
app.config_from_envvar = app.config.from_envvar
app.config_from_object = app.config.from_object
configure_app(app)
init_core(app)
register_blueprints(app)
return app |
java | @SafeVarargs
public static <T extends Tree> Matcher<T> allOf(final Matcher<? super T>... matchers) {
return new Matcher<T>() {
@Override
public boolean matches(T t, VisitorState state) {
for (Matcher<? super T> matcher : matchers) {
if (!matcher.matches(t, state)) {
retur... |
java | public DescribeGameSessionDetailsResult withGameSessionDetails(GameSessionDetail... gameSessionDetails) {
if (this.gameSessionDetails == null) {
setGameSessionDetails(new java.util.ArrayList<GameSessionDetail>(gameSessionDetails.length));
}
for (GameSessionDetail ele : gameSessionDet... |
java | public void setUseGlobalState(boolean enableGlobalState) {
if (enableGlobalState) {
checkState();
} else {
client.setState(new HttpState());
clientViaProxy.setState(new HttpState());
setClientsCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
}
} |
java | private IoBuffer encodeClientBW(ClientBW clientBW) {
final IoBuffer out = IoBuffer.allocate(5);
out.putInt(clientBW.getBandwidth());
out.put(clientBW.getLimitType());
return out;
} |
java | public synchronized Set<Vulnerability> getSuppressedVulnerabilities(boolean sorted) {
final Set<Vulnerability> vulnerabilitySet;
if (sorted) {
vulnerabilitySet = new TreeSet<>(suppressedVulnerabilities);
} else {
vulnerabilitySet = suppressedVulnerabilities;
}
... |
java | public FieldConstraintsBuilder withShiftedStringMapping(final int shiftSize) {
if (shiftSize > 0 || endRange < stringMapping.size()) {
for (final Entry<String, Integer> entry : stringMapping.entrySet()) {
int value = entry.getValue();
value += shiftSize;
... |
python | def iterate_dictionary(d, path, squash_single = False):
"""
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS.
The word "leaf" hereby refers to an item at the se... |
python | def viterbi(self,observations):
""" The probability of occurence of the observation sequence
**Arguments**:
:param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object.
:type observations: A list or tuple
... |
java | public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest,
HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) {
HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine());
result.setEntity(httpClientResponse.getEntity());
... |
java | @PrefMetadata(type = CmsHiddenBuiltinPreference.class)
public String getExplorerFileEntryOptions() {
if (m_settings.getExplorerFileEntryOptions() == null) {
return "";
} else {
return "" + m_settings.getExplorerFileEntryOptions();
}
} |
python | def _newRemoteException(ErrorType):
'''create a new RemoteExceptionType from a given errortype'''
RemoteErrorBaseType = _RemoteExceptionMeta('', (ErrorType,), {})
class RemoteException(RemoteErrorBaseType):
BaseExceptionType = ErrorType
def __init__(self, thrownError, tracebackString):
... |
python | def parse_args(argv):
"""
Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: ``list``
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
p = argparse.ArgumentParser(
description='pypi-download-st... |
python | def make_file_exist(self, filename=None):
"""Make the directory exist, then touch the file
If the filename is None, then use self.name as filename
"""
if filename is None:
path_to_file = FilePath(self)
path_to_file.make_file_exist()
return path_to_fil... |
python | def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True):
""" Merge node n1 into node n2, with the option to specify relative
polarity.
Args:
n1
n2
same_polarity
"""
for p in self.predecessors(n1):
for st in self[p][n1]... |
python | def contains_peroxide(structure, relative_cutoff=1.1):
"""
Determines if a structure contains peroxide anions.
Args:
structure (Structure): Input structure.
relative_cutoff: The peroxide bond distance is 1.49 Angstrom.
Relative_cutoff * 1.49 stipulates the maximum distance two O... |
python | def get_text(self):
"""Return all joined text from each subtree"""
if self.__fulltext:
return self.__fulltext
else:
self.__fulltext = "\n\n".join(text.get_text()
for text in self.__subtrees)
return self.__fullte... |
python | def get_new_working_set(self):
"""
Get a new list of IPs to work with from the queue.
This returns None if there is no update.
Read all the messages from the queue on which we get the IP addresses
that we have to monitor. We will ignore all of them, except the last
one,... |
java | private static ThreadFactory getThreadFactory(final String nameFormat) {
final ThreadFactory defaultThreadFactory = Executors.privilegedThreadFactory();
return new ThreadFactory() {
final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
@Override
p... |
python | def type_to_interface(event_type):
"""Return the event interface object that corresponds to the event type
enumeration"""
global _lookup
if not isinstance(event_type, library.VBoxEventType):
raise TypeError("event_type was not of VBoxEventType")
if not _lookup:
for attr in dir(librar... |
java | public Runner safeRunnerForClass(Class<?> testClass) {
try {
Runner runner = runnerForClass(testClass);
if (runner != null) {
configureRunner(runner);
}
return runner;
} catch (Throwable e) {
return new ErrorReportingRunner(test... |
java | public Connector copy()
{
XsdString newResourceadapterVersion = CopyUtil.clone(this.resourceadapterVersion);
XsdString newEisType = XsdString.isNull(this.eisType) ? null : (XsdString) this.eisType.copy();
List<XsdString> newRequiredWorkContexts = CopyUtil.cloneList(this.requiredWorkContexts);
... |
java | public ServiceFuture<SyncAgentInner> getAsync(String resourceGroupName, String serverName, String syncAgentName, final ServiceCallback<SyncAgentInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, serverName, syncAgentName), serviceCallback);
} |
python | def search_meta_tag(html_doc, prefix, code):
"""
Checks whether the html_doc contains a meta matching the prefix & code
"""
regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code)
meta = re.compile(regex, flags=re.MUL... |
python | def eigenvectors_nrev(T, k, right=True, ncv=None):
r"""Compute eigenvectors of transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix (stochastic matrix)
k : int
Number of eigenvalues to compute
right : bool, optional
If True compute ri... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "domainSet")
public JAXBElement<DomainSetType> createDomainSet(DomainSetType value) {
return new JAXBElement<DomainSetType>(_DomainSet_QNAME, DomainSetType.class, null, value);
} |
python | def p_instance_port_arg(self, p):
'instance_port_arg : DOT ID LPAREN identifier RPAREN'
p[0] = PortArg(p[2], p[4], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
java | @Override
public void usageDetail(
final char commandPrefix,
final ICmdLineArg<?> arg,
final int _indentLevel)
{
nameIt(commandPrefix, arg);
allign(29);
final String help = ((AbstractCLA<?>) arg).getHelp();
if (help != null && help.trim().leng... |
python | def on_channel_closed(self, channel, reply_code, reply_text):
"""
Invoked by pika when RabbitMQ unexpectedly closes the channel.
Channels are usually closed if you attempt to do something that
violates the protocol, such as re-declare an exchange or queue with
different parameter... |
python | def wait_for_job(self, job, interval=5, timeout=60):
"""
Waits until the job indicated by job_resource is done or has failed
Parameters
----------
job : Union[dict, str]
``dict`` representing a BigQuery job resource, or a ``str``
representing the BigQuery... |
java | private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns)
{
Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>();
for (ColumnDefinition def : columns)
{
map.put(def.getName(), def);
}
return map;
} |
python | def update(self, **kwargs):
"""
Mass-assign the attributes in +kwargs+ to the object, preventing
attributes not in __attributes__ from being set.
"""
for attr, val in kwargs.items():
if attr in (list(self.__class__.__attributes__) + \
list(asso... |
java | public static Object buildProxy(RemoteInstance remoteInstance, ConnectionHandler connectionHandler)
throws ClassNotFoundException {
Class<?> clazz = Class.forName(remoteInstance.getClassName());
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new CallProxy(connec... |
python | def str_def(self):
"""
:term:`string`: The exception as a string in a Python definition-style
format, e.g. for parsing by scripts:
.. code-block:: text
classname={}; line={}; column={}; message={};
"""
return "classname={!r}; line={!r}; column={!r}; message=... |
java | public HSSFWorkbook toExcel(Collection<Object[]> datas, String propertyShowKeys) throws Exception {
// 建立新HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
return toExcel(wb, "export data", datas, propertyShowKeys);
} |
java | public static HashId createHashId(String string) throws IOException {
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
string.getBytes(Charset.defaultCharset()))) {
return createHashId(byteArrayInputStream);
}
} |
python | def _layer_norm(self, name, x):
"""Layer normalization."""
if self.init_layers:
bn = LayerNorm()
bn.name = name
self.layers += [bn]
else:
bn = self.layers[self.layer_idx]
self.layer_idx += 1
bn.device_name = self.device_name
bn.set_training(self.training)
x = bn.fpr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.