language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def insert(self, index, value):
"""Validate item insertion to list."""
self.__field.validate_element(value)
return list.insert(self, index, value) |
java | public ServiceFuture<SubnetInner> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName, String expand, final ServiceCallback<SubnetInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName, expand), servic... |
java | public void setParameters(Map<String, String> parameters) {
if (parameters == null || parameters.isEmpty()) {
this.parameterItemRuleMap = null;
} else {
ItemRuleMap itemRuleMap = new ItemRuleMap();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
... |
java | protected void doSanityCheck() throws EXIException {
// Self-contained elements do not work with re-ordered
if (fidelityOptions.isFidelityEnabled(FidelityOptions.FEATURE_SC)
&& (codingMode == CodingMode.COMPRESSION || codingMode == CodingMode.PRE_COMPRESSION)) {
throw new EXIException(
"(Pre-)Com... |
java | @edu.umd.cs.findbugs.annotations.SuppressWarnings("OBL")
protected Reader createReader(final File file) throws FileNotFoundException {
return createReader(new FileInputStream(file));
} |
java | public static sdx_license get(nitro_service client) throws Exception
{
sdx_license resource = new sdx_license();
resource.validate("get");
return ((sdx_license[]) resource.get_resources(client))[0];
} |
python | def refresh_ip(self, si, logger, session, vcenter_data_model, resource_model, cancellation_context,
app_request_json):
"""
Refreshes IP address of virtual machine and updates Address property on the resource
:param vim.ServiceInstance si: py_vmomi service instance
:pa... |
python | def map_from_module(self, module):
"""
Map all classes the in $module with subclasses of exceptions.HTTPException
to be called as as error in with abort()
:param obj:
:return:
"""
maps = {}
for name in dir(module):
obj = getattr(module, name)
... |
java | @Nonnull
public static IRI create(@Nullable String prefix, @Nullable String suffix) {
if (prefix == null && suffix == null) {
throw new IllegalArgumentException("prefix and suffix cannot both be null");
}
if (prefix == null) {
assert suffix != null;
return... |
java | public void writeStartElement(String prefix, String localName,
String namespaceURI) throws XMLStreamException {
try {
assert (namespaceURI != null);
assert (localName != null);
// System.out.println("> SE " + localName);
checkPendingATEvents();
encoder.encodeStartElement(namespaceURI, localNa... |
java | @SuppressWarnings("unchecked")
@Override
public T inOutParamIfAbsent(final String paramName, final Object value, final SQLType sqlType) {
context().inOutParamIfAbsent(paramName, value, sqlType);
return (T) this;
} |
python | def preproc(path, sr=16000, alpha=0.95):
"""Preprocess a .wav file for later processing. Currently assumes a
16-bit PCM input. Only returns left channel of stereo files.
Parameters
----------
path : str
Full path to .wav file to load.
sr : int, optional
Sampling rate to resamp... |
python | def _ws_on_message(self, ws: websocket.WebSocketApp, raw: Union[str, bytes]):
"""Callback for receiving messages from the websocket connection
This method receives ALL events from the websocket connection, some of which
are used for the initial authentication flow, some of which are used for ma... |
python | def get_node(self, value):
"""Get node ID by value.
If a node with the specified value does not exist,
create it and return its ID.
Parameters
----------
value : `str`
Node value.
Returns
-------
`int`
Node ID.
""... |
python | def _check_id_validity(self, p_ids):
"""
Checks if there are any invalid todo IDs in p_ids list.
Returns proper error message if any ID is invalid and None otherwise.
"""
errors = []
valid_ids = self.todolist.ids()
if len(p_ids) == 0:
errors.append('... |
java | public GetVolumeResponse getVolume(GetVolumeRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getVolumeId(), "request volumeId should not be empty.");
InternalRequest internalRequest =
this.createRequest(request, HttpMethodName.G... |
python | def vector_analysis(vector, coordinates, elements_vdw, increment=1.0):
"""Analyse a sampling vector's path for window analysis purpose."""
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector ... |
python | def load_fits_catalog(self, name, **kwargs):
"""Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file.
"""
# EAC split this function to make it easier to load an existing catalog
cat = cat... |
java | public void setOEGName(String newOEGName) {
String oldOEGName = oegName;
oegName = newOEGName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BOG__OEG_NAME, oldOEGName, oegName));
} |
python | def sanitize_for_serialization(self, obj):
"""
Builds a JSON POST object.
If obj is None, return None.
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is list, sani... |
python | def signatures(ambiguous_word: str, pos: str = None, hyperhypo=True, adapted=False,
remove_stopwords=True, to_lemmatize=True, remove_numbers=True,
lowercase=True, to_stem=False, original_lesk=False, from_cache=True) -> dict:
"""
Takes an ambiguous word and optionally its Part-Of-Sp... |
python | async def _handle_telegram_response(self, response, ignore=None):
"""
Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data
"""
if ignore is None:
... |
python | def side_chain_centres(assembly, masses=False):
""" PseudoGroup containing side_chain centres of each Residue in each Polypeptide in Assembly.
Notes
-----
Each PseudoAtom is a side-chain centre.
There is one PseudoMonomer per chain in ampal (each containing len(chain) PseudoAtoms).
The PseudoGr... |
java | @Override
protected Map<String, List<Object>> mergePersonAttributes(final Map<String, List<Object>> toModify, final Map<String, List<Object>> toConsider) {
Validate.notNull(toModify, "toModify cannot be null");
Validate.notNull(toConsider, "toConsider cannot be null");
for (final Map.Entry<... |
java | @Override
public SendCustomVerificationEmailResult sendCustomVerificationEmail(SendCustomVerificationEmailRequest request) {
request = beforeClientExecution(request);
return executeSendCustomVerificationEmail(request);
} |
python | def _build_url(self):
"""Build url based on searching by date or by show."""
url_params = [
BASE_URL, self.category + ' ratings', self.day, self.year, self.month
]
return SEARCH_URL.format(*url_params) |
python | def parse_national_assembly_url(url_an):
"""Returns the slug and the legislature of an AN url
>>> # old format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/devoir_vigilance_entreprises_donneuses_ordre.asp")
(14, 'devoir_vigilance_entreprises_donneuses_ordre')
>>> #... |
python | def _lookup_parameter(self, container, key, common_type=None):
"""
Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items
... |
java | public List<Integer> searchBigBytes(byte[] srcBytes, byte[] searchBytes) {
int numOfThreadsOptimized = (srcBytes.length / analyzeByteArrayUnitSize);
if (numOfThreadsOptimized == 0) {
numOfThreadsOptimized = 1;
}
return searchBigBytes(srcBytes, searchBytes, numOfThreadsOptimized);
} |
java | public boolean createNode(String path, String value) throws ZooKeeperException {
return _create(path, value != null ? value.getBytes(UTF8) : null, CreateMode.PERSISTENT);
} |
java | @Override
public List<SingleSwapMove> getAllMoves(PermutationSolution solution) {
// initialize list
List<SingleSwapMove> moves = new ArrayList<>();
int n = solution.size();
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
moves.add(new SingleSwapMove(i, ... |
python | def read(fname):
" read the passed file "
if exists(fname):
return open(join(dirname(__file__), fname)).read() |
java | private boolean checkModulo11TaxNumber(final String ptaxNumber) {
final int checkSum = ptaxNumber.charAt(ptaxNumber.length() - 1) - '0';
int sum = 10;
for (int i = 0; i < ptaxNumber.length() - 1; i++) {
int summe = (ptaxNumber.charAt(i) - '0' + sum) % 10;
if (summe == 0) {
summe = ... |
java | public static PemObject getPemObject(final File file) throws IOException
{
PemObject pemObject;
try (PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(file))))
{
pemObject = pemReader.readPemObject();
}
return pemObject;
} |
java | public static void fillPayMap(Map<String, Object> map, String key) {
// 首先确保有随机数
map.put("nonce_str", "" + R.random(10000000, 100000000));
// 填充签名
String sign = genPaySignMD5(map, key);
map.put("sign", sign);
} |
java | public static CompletableFuture<IMessageSender> createMessageSenderFromEntityPathAsync(String namespaceName, String entityPath, ClientSettings clientSettings)
{
Utils.assertNonNull("namespaceName", namespaceName);
Utils.assertNonNull("entityPath", entityPath);
return createMessageSenderFromE... |
java | public EEnum getIfcCurrencyEnum() {
if (ifcCurrencyEnumEEnum == null) {
ifcCurrencyEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(805);
}
return ifcCurrencyEnumEEnum;
} |
java | @Override
protected String[] getRow(String[] resultRow) {
return Arrays.copyOfRange(resultRow, 1, resultRow.length);
} |
java | @Override
public void remoteInvalidate(String sessionId, boolean backendUpdate) {
super.remoteInvalidate(sessionId, backendUpdate);
if (backendUpdate) {
((CacheHashMap) _sessions).setMaxInactToZero(sessionId, getId());
}
// now clean this session out of cache -- we do t... |
java | public static TileSetBundle extractBundle (ResourceBundle bundle)
throws IOException, ClassNotFoundException
{
// unserialize the tileset bundles array
InputStream tbin = null;
try {
tbin = bundle.getResource(METADATA_PATH);
ObjectInputStream oin = new ObjectI... |
python | def Solve(self, stops=None, barriers=None, returnDirections=None,
returnRoutes=None, returnStops=None, returnBarriers=None,
outSR=None, ignoreInvalidLocations=None, outputLines=None,
findBestSequence=None, preserveFirstStop=None,
preserveLastStop=None, useTimeWind... |
java | public TreeBuilder<T> listen(Listener<T> listener, PathSelector pathSelector) {
return TreeBuilder.<T>builder(new ListenerTree<T>(build(), listener, pathSelector));
} |
java | @Override
public int compareTo(AstNode other) {
if (this.equals(other)) return 0;
int abs1 = this.getAbsolutePosition();
int abs2 = other.getAbsolutePosition();
if (abs1 < abs2) return -1;
if (abs2 < abs1) return 1;
int len1 = this.getLength();
int len2 = othe... |
python | def softmax(w, t=1.0):
"""Calculate the softmax of a list of numbers w.
Parameters
----------
w : list of numbers
Returns
-------
a list of the same length as w of non-negative numbers
Examples
--------
>>> softmax([0.1, 0.2])
array([ 0.47502081, 0.52497919])
>>> soft... |
java | public String getMimeType(final String fileId) {
FileWidgetUpload fileWidget = getFile(fileId);
if (fileWidget != null) {
return FileUtil.getFileMimeType(fileWidget.getFile());
}
return null;
} |
java | @Override
public MeanVarianceMinMax put(double[] vals) {
final int l = vals.length;
if(l < 2) {
if(l == 1) {
put(vals[0]);
}
return this;
}
// First pass:
double s1 = 0.;
for(int i = 0; i < l; i++) {
final double v = vals[i];
s1 += v;
min = v < min ?... |
python | def _pid_to_id(self, pid):
"""Converts a pid to a URI that can be used as an OAI-ORE identifier."""
return d1_common.url.joinPathElements(
self._base_url,
self._version_tag,
"resolve",
d1_common.url.encodePathElement(pid),
) |
python | def decide_which_users_to_annotate(centrality_vector,
number_to_annotate,
already_annotated,
node_to_id):
"""
Sorts a centrality vector and returns the Twitter user ids that are to be annotated.
Inputs:... |
java | public void exists(String tableName, String columnName, String jdbcType, boolean ignoreCase) throws SQLException
{
if (tableName == null) throw new SQLException("TableName was null. You must specify a valid table name.");
if (columnName == null) throw new SQLException("Column name was null. You must specify a... |
python | def send_requests(self, *args):
"""
Send a set of requests.
Each request is sent over its own connection and the function will
return when all the requests have been fulfilled.
"""
threads = [ClientThread(self, req) for req in args]
for t in threads:
... |
java | public void marshall(ConfirmPublicVirtualInterfaceRequest confirmPublicVirtualInterfaceRequest, ProtocolMarshaller protocolMarshaller) {
if (confirmPublicVirtualInterfaceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
... |
python | def plain_keys(self):
"""A subset of the :attr:`entries` dictionary, filtered down to only
those entries of type :class:`BksKeyEntry`."""
return dict([(a, e) for a, e in self.entries.items()
if isinstance(e, BksKeyEntry)]) |
java | public EClass getIfcReinforcementBarProperties() {
if (ifcReinforcementBarPropertiesEClass == null) {
ifcReinforcementBarPropertiesEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(432);
}
return ifcReinforcementBarPropertiesEClass;
} |
java | protected final String resolvePlaceholder(final String placeholderWithDefault, final Properties props,
final int systemPropertiesMode) {
String placeholder = getPlaceholder(placeholderWithDefault);
String resolved = super.resolvePlaceholder(placeholder, prop... |
java | private PointSequence createPointSequence(double[][] coordinates, CrsId crsId) {
if (coordinates == null) {
return null;
} else if (coordinates.length == 0) {
return PointCollectionFactory.createEmpty();
}
DimensionalFlag df = coordinates[0].length == 4 ? Dimensi... |
python | def show_header(**header):
"Display a HTTP-style header on the command-line."
print('%s: %s' % ('Now', header['now']))
print('%s: %s' % ('Stop-Name', header['name']))
print('%s: %s' % ('Stop-ID', header.get('id', None)))
print('') |
java | protected void jobFinished(Throwable error)
{
this.lock.lock();
try {
if (this.status instanceof AbstractJobStatus) {
// Store error
((AbstractJobStatus) this.status).setError(error);
}
// Give a chance to any listener to do custo... |
java | public static String getCodeFromCrs( CoordinateReferenceSystem crs ) throws Exception {
String code = null;
try {
Integer epsg = CRS.lookupEpsgCode(crs, true);
code = "EPSG:" + epsg; //$NON-NLS-1$
} catch (Exception e) {
// try non epsg
code = CRS.... |
java | @Override
public Response toResponse(Throwable exception) {
Optional<io.katharsis.errorhandling.mapper.JsonApiExceptionMapper> exceptionMapper = exceptionMapperRegistry.findMapperFor(exception.getClass());
io.katharsis.repository.response.Response errorResponse;
if (exceptionMapper.isPresent()) {
errorRespons... |
python | def start_session(self):
"""
Starts a Salesforce session and determines which SF instance to use for future requests.
"""
if self.has_active_session():
raise Exception("Session already in progress.")
response = requests.post(self._get_login_url(),
... |
python | def animate(func: types.AnyFunction = None,
*,
animation: types.AnimationGenerator = _default_animation(),
step: float = 0.1) -> types.AnyFunction:
"""Wrapper function for the _Animate wrapper class.
Args:
func: A function to run while animation is showing.
... |
java | public void setRootLoggingLevel(final int loggingLevel) {
rootLoggingLevel = loggingLevel;
if (rootLoggerBack != null) {
rootLoggerBack.setLevel(LoggingLevel.getLevelFromInt(loggingLevel));
}
} |
java | public static String decodePath(String path, int offset, int length) {
try {
Utf8StringBuilder builder = null;
int end = offset + length;
for (int i = offset; i < end; i++) {
char c = path.charAt(i);
switch (c) {
case '%':
... |
python | def unpack_response(self, cursor_id=None,
codec_options=_UNICODE_REPLACE_CODEC_OPTIONS,
user_fields=None, legacy_response=False):
"""Unpack a response from the database and decode the BSON document(s).
Check the response for errors and unpack, returning a... |
python | def l1_loss(tensor, weight=1.0, scope=None):
"""Define a L1Loss, useful for regularize, i.e. lasso.
Args:
tensor: tensor to regularize.
weight: scale the loss by this factor.
scope: Optional scope for name_scope.
Returns:
the L1 loss op.
"""
with tf.name_scope(scope, 'L1Loss', [tensor]):
... |
python | def findAllSingle(self, selfValue):
'''Looks for all the single values and subclasses *recursively* and returns a list of them
Args:
selfValue: A list of single, str, int. Normally just ``self.value``
Returns:
list: A list contains only singles and subclasses.
'... |
python | def parse_simpleexprsp(self, tup_tree):
# pylint: disable=unused-argument
"""
This Function not implemented. This response is for export senders
(indication senders) so it is not implemented in the pywbem
client.
"""
raise CIMXMLParseError(
_format("In... |
python | def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CAB archive."""
cmdlist = [cmd, '-d', outdir]
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist |
java | @Nonnull
public static String replaceMultipleAsString (@Nullable final String sInputString,
@Nonnull final char [] aSearchChars,
final char cReplacementChar)
{
ValueEnforcer.notNull (aSearchChars, "SearchChars");
... |
python | def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameter... |
python | def _convert_to_font(cls, font_dict):
"""
Convert ``font_dict`` to an openpyxl v2 Font object
Parameters
----------
font_dict : dict
A dict with zero or more of the following keys (or their synonyms).
'name'
'size' ('sz')
... |
python | def send_message(self, peer: Peer, text: str, reply: int=None, link_preview: bool=None, on_success: callable=None):
"""
Send message to peer.
:param peer: Peer to send message to.
:param text: Text to send.
:param reply: Message object or message_id to reply to.
:param li... |
java | public long sum() {
long sum = base;
Cell[] as = cells;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null) sum += a.value;
}
}
return sum;
} |
java | @Override
public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment env = context.getEnvironment();
String[] activeProfiles = env.getActiveProfiles();
if (activeProfiles == null || activeProfiles.length == 0){ // don't override settings in configuration files and command line argum... |
java | public String url(Map<String, ?> parametersMap)
{
StringBuilder queryStringBuilder = new StringBuilder();
for (Map.Entry<String, ?> entry : parametersMap.entrySet()) {
if (entry.getKey() == null) {
// Skip the parameter if its name is null.
continue;
... |
java | protected boolean processTopicTags(final TagProvider tagProvider, final ITopicNode specTopic, final TopicWrapper topic) {
LOG.debug("Processing topic tags");
boolean changed = false;
// Get the tags for the topic
final List<String> addTagNames = specTopic.getTags(true);
final Li... |
python | def appender(defaultdocs, passed_to=None):
"""Decorator for appending commonly used parameter definitions.
Useful in cases where functions repeatedly use the same parameters. (But
where a class implementation is not appropriate.)
`defaultdocs` -> dict, format as shown in Example below, with key... |
java | public void setCSVHeader(java.util.Collection<String> cSVHeader) {
if (cSVHeader == null) {
this.cSVHeader = null;
return;
}
this.cSVHeader = new java.util.ArrayList<String>(cSVHeader);
} |
python | def get_feh(cls, filename):
"""
example filename: yapsi_w_X0p602357_Z0p027643.dat
"""
X,Y,Z = cls._get_XYZ(filename)
Xsun = 0.703812
Zsun = 0.016188
return np.log10((Z/X) / (Zsun/Xsun)) |
java | @Override
public RemoteConsumerDispatcher getRemoteConsumerDispatcher(SIBUuid8 meId, SIBUuid12 gatheringTargetDestUuid, boolean createAIH)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getRemoteConsumerDispatcher", new Object[] { meId, gatheringTargetDes... |
python | def create_parser():
"""Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--dictionary',
nargs='?',
default='dictionaries/all_en_US.dict',
... |
java | protected Long getLong(Exchange exchange, Message message, String name) {
Object value = getObject(exchange, message, name);
if (value instanceof Long) {
return (Long)value;
} else if (value instanceof Number) {
return Long.valueOf(((Number)value).longValue());
} ... |
java | public static void addRange(Collection<Integer> c, int start, int to, int step)
{
if(step <= 0)
throw new RuntimeException("Would create an infinite loop");
for(int i = start; i < to; i+= step)
c.add(i);
} |
java | private void processSplit(final String parsed_value) {
if (splits == null) {
// then this is the first time we're processing the value, so we need to
// execute the split if there's a separator, after some validation
if (parsed_value == null || parsed_value.isEmpty()) {
throw new IllegalAr... |
python | def followers(request, content_type_id, object_id, flag):
"""
Creates a listing of ``User``s that follow the actor defined by
``content_type_id``, ``object_id``.
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
instance = get_object_or_404(ctype.model_class(), pk=object_id)
fla... |
java | public static ClientBuilder kubeconfig(KubeConfig config) throws IOException {
final ClientBuilder builder = new ClientBuilder();
String server = config.getServer();
if (!server.contains("://")) {
if (server.contains(":443")) {
server = "https://" + server;
} else {
server = "ht... |
java | public static boolean isChar(int ch)
{
return 0x09 == ch // TAB
|| 0x0a == ch // LF
|| 0x0d == ch // CR
|| (0x20 <= ch && ch <= 0xD7FF) || (0xE000 <= ch && ch <= 0xFFFD) || (0x10000 <= ch && ch <= 0x10FFFF);
} |
python | def choicerank(
digraph, traffic_in, traffic_out, weight=None,
initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8):
"""Compute the MAP estimate of a network choice model's parameters.
This function computes the maximum-a-posteriori (MAP) estimate of model
parameters given a network st... |
python | def request(self, method, args, response_cb):
"""Send a msgpack-rpc request to Nvim.
A msgpack-rpc with method `method` and argument `args` is sent to
Nvim. The `response_cb` function is called with when the response
is available.
"""
request_id = self._next_request_id
... |
python | def build_wheel(self, wheel, directory, compile_c=True):
# type: (str, str, bool) -> None
"""Build an sdist into a wheel file."""
arguments = ['--no-deps', '--wheel-dir', directory, wheel]
env_vars = self._osutils.environ()
shim = ''
if not compile_c:
env_vars... |
python | def compare_root_path(path_cost1, path_cost2, bridge_id1, bridge_id2,
port_id1, port_id2):
""" Decide the port of the side near a root bridge.
It is compared by the following priorities.
1. root path cost
2. designated bridge ID value
... |
python | def bytes_to_int(b, order='big'): # pragma: no cover
"""convert bytes to integer"""
if six.PY2:
# save the original type of b without having to copy any data
_b = b.__class__()
if order != 'little':
b = reversed(b)
if not isinstance(_b, b... |
java | public Where<T, ID> between(String columnName, Object low, Object high) throws SQLException {
addClause(new Between(columnName, findColumnFieldType(columnName), low, high));
return this;
} |
java | public final EObject ruleXVariableDeclaration() throws RecognitionException {
EObject current = null;
Token lv_writeable_1_0=null;
Token otherlv_2=null;
Token otherlv_6=null;
EObject lv_type_3_0 = null;
AntlrDatatypeRuleToken lv_name_4_0 = null;
AntlrDatatypeRu... |
python | def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},'.format(name=name,
data_type=data_type,
... |
python | def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token):
"""Sets the mapping between token indices and token embedding vectors.
Parameters
----------
token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding`
One or m... |
python | def empty_wav(wav_path: Union[Path, str]) -> bool:
"""Check if a wav contains data"""
with wave.open(str(wav_path), 'rb') as wav_f:
return wav_f.getnframes() == 0 |
python | def zipf_distribution(nbr_symbols, alpha):
"""Helper function: Create a Zipf distribution.
Args:
nbr_symbols: number of symbols to use in the distribution.
alpha: float, Zipf's Law Distribution parameter. Default = 1.5.
Usually for modelling natural text distribution is in
the range [1.1-1.6].
... |
python | def stats(self):
""" shotcut to pull out useful info for a graph"""
out = []
out += [("Ontologies", len(self.all_ontologies))]
out += [("Triples", self.triplesCount())]
out += [("Classes", len(self.all_classes))]
out += [("Properties", len(self.all_properties))]
o... |
python | def get_server_unread_messages_count(self, server_name=None):
"""Gets count of unread messages from server
"""
server = self._servers.get(server_name)
return server.get_messages_count_in_buffer() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.