language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _url_base64_encode(msg): """ Base64 encodes a string using the URL-safe characters specified by Amazon. """ msg_base64 = base64.b64encode(msg) msg_base64 = msg_base64.replace('+', '-') msg_base64 = msg_base64.replace('=', '_') msg_base64 = msg_base64.r...
java
public Set<String> getOtLabelAndSynonyms(OntologyTerm ontologyTerm) { Set<String> allTerms = Sets.newLinkedHashSet(ontologyTerm.getSynonyms()); allTerms.add(ontologyTerm.getLabel()); return allTerms; }
python
def directed_graph(trajectories, k=5, verbose=False, pruning_thresh=0, return_coords=False): '''Directed graph construction alg. from Johns & Mahadevan, ICML '07. trajectories: list of NxD arrays of ordered states ''' X = np.vstack(trajectories) G = neighbor_graph(X, k=k) if pruning_thres...
java
public void actionParent() throws Exception { String ouFqn = CmsOrganizationalUnit.getParentFqn(getParamOufqn()); Map<String, String[]> params = new HashMap<String, String[]>(); params.put(A_CmsOrgUnitDialog.PARAM_OUFQN, new String[] {ouFqn}); params.put(CmsDialog.PARAM_ACTION, new Str...
python
def truncate_html(html, *args, **kwargs): """Truncates HTML string. :param html: The HTML string or parsed element tree (with :func:`html5lib.parse`). :param kwargs: Similar with :class:`.filters.TruncationFilter`. :return: The truncated HTML string. """ if hasattr(html, 'getc...
java
private synchronized boolean removeWrapperFromList(EventListenerWrapper<K, V> wrapper, List<EventListenerWrapper<K, V>> listenersList) { int index = listenersList.indexOf(wrapper); if (index != -1) { EventListenerWrapper<K, V> containedWrapper = listenersList.remove(index); if(containedWrapper.isOrd...
java
public final void ruleXSetLiteral() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXbase.g:746:2: ( ( ( rule__XSetLiteral__Group__0 ) ) ) // InternalXbase.g:747:2: ( ( rule__XSetLiteral__Group__0 ) ) { // Inter...
python
def _check_ui_parameters(self): """ Checks that tasks parameters exist in the task and are of the right type. Runs before the task is run. :return: None :raises TaskValidationError: the task parameter is missing or invalid. """ if isinstance(self.PARAMETER_UI_STUFF, dict)...
java
public static List<Integer> toIntegerList(int[] array) { List<Integer> result = new ArrayList<Integer>(array.length); for (int partitionId : array) { result.add(partitionId); } return result; }
python
def query_row(stmt, args=(), factory=None): """ Execute a query. Returns the first row of the result set, or `None`. """ for row in query(stmt, args, factory): return row return None
python
def key(self): ''' Returns the redis key to access this object's values ''' prefix = type(self).cls_key() return '{}:{}:obj'.format(prefix, self.id)
java
public void setLong(String key, long value) { prefHelper_.prefsEditor_.putLong(key, value); prefHelper_.prefsEditor_.apply(); }
java
public void setThemes_protein(FSArray v) { if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_themes_protein == null) jcasType.jcas.throwFeatMissing("themes_protein", "ch.epfl.bbp.uima.genia.Event"); jcasType.ll_cas.ll_setRefValue(addr, ((Event_Type)jcasType).casFeatCode_themes_protein, jcasType.l...
java
public static DocumentFactory getInstance() { if (CONFIGURED_INSTANCE == null) { synchronized (DocumentFactory.class) { if (CONFIGURED_INSTANCE == null) { CONFIGURED_INSTANCE = new DocumentFactory(); } } } return CONFIGURED_INSTANCE; }
python
def Nu_Xu(Re, Pr, rho_w=None, rho_b=None, mu_w=None, mu_b=None): r'''Calculates internal convection Nusselt number for turbulent vertical upward flow in a pipe under supercritical conditions according to [1]_. .. math:: Nu_b = 0.02269 Re_b^{0.8079} \bar{Pr}_b^{0.9213} \left(\frac{\r...
java
ServiceRegistry getServiceRegistry(final boolean modify, final Step registryActiveStep) { if (modify) { readOnly = false; } assert isControllingThread(); Stage currentStage = this.currentStage; if (modify) { if (!isRuntimeChangeAllowed()) { ...
java
public void setDeviceCapabilityTargeting(com.google.api.ads.admanager.axis.v201805.DeviceCapabilityTargeting deviceCapabilityTargeting) { this.deviceCapabilityTargeting = deviceCapabilityTargeting; }
python
def matchBytes(self, bytes): """Look for a sequence of bytes at the start of a string. If the bytes are found return True and advance the position to the byte after the match. Otherwise return False and leave the position alone""" p = self.position data = self[p:p + len(bytes)] ...
java
@Override public Optional<Field> indexedField(String name, Long value) { return Optional.of(new LongField(name, value, STORE)); }
java
private void eventPostCommit(SIMPMessage msg) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "eventPostCommit", msg); MessageItem msgItem = (MessageItem) msg; JsMessage jsMsg = msgItem.getMessage(); // If we...
python
def tokeniter(self, source, name, filename=None, state=None): """This method tokenizes the text and returns the tokens in a generator. Use this method if you just want to tokenize a template. """ source = '\n'.join(unicode(source).splitlines()) pos = 0 lineno = 1 ...
java
protected String getMFMainClass(Container appEntryContainer, String entryPath, boolean required) { String mfMainClass = null; try { String entry = "/META-INF/MANIFEST.MF"; Entry manifestEntry = appEntryContainer.getEntry(entry); if (manifestEntry != null) { ...
python
def set_loggers_from_config(config=None): """Set loggers configuration according to the `logging` section of Docido configuration file. :param nameddict config: overrides Docido configuration """ config = config or app_config.logging for lname, lconfig in config.get('loggers', {}).iterite...
java
protected SortedMap<String, SortedSet<String>> loadSignificantParametersForSignatureBaseString(HttpServletRequest request) { //first collect the relevant parameters... SortedMap<String, SortedSet<String>> significantParameters = new TreeMap<String, SortedSet<String>>(); //first pull from the request... ...
python
def loss_l2(self, l2=0): """L2 loss centered around mu_init, scaled optionally per-source. In other words, diagonal Tikhonov regularization, ||D(\mu-\mu_{init})||_2^2 where D is diagonal. Args: - l2: A float or np.array representing the per-source regularization...
java
@Override public Response loadUnzippedApplicationTemplate( String localFilePath ) { if( localFilePath == null ) localFilePath = "null"; this.logger.fine( "Request: load application from a local file (" + localFilePath + ")." ); Response response; try { ApplicationTemplate tpl = this.manager.application...
java
public void marshall(DeleteAppReplicationConfigurationRequest deleteAppReplicationConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (deleteAppReplicationConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try {...
java
public static Comparable canonicalizeForHashLookup(Comparable value) { if (value instanceof Number) { return Numbers.canonicalizeForHashLookup(value); } return value; }
java
public void convertPackage(PackageElement pkg, DocPath outputdir) throws DocFileIOException, SimpleDocletException { if (pkg == null) { return; } for (Element te : utils.getAllClasses(pkg)) { // If -nodeprecated option is set and the class is marked as depreca...
java
public PublicIPAddressInner getVirtualMachineScaleSetPublicIPAddress(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String ipConfigurationName, String publicIpAddressName, String expand) { return getVirtualMachineScaleSetPublicIPAddressWithS...
java
public String createUniqueId(FacesContext context, String seed) { if (seed != null) { return UIViewRoot.UNIQUE_ID_PREFIX + seed; } else { Integer i = (Integer) getStateHelper().get(PropertyKeys.lastId); int lastId = ((i != null) ? i : 0); getStateHelper()....
python
async def delete(self, *, reason=None): """|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the ...
java
public void performAdd(InputStream in, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException, MarkLogicSesameException { try { graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType()); if (dataFormat.equals(RDFFormat.NQUADS) || dataF...
java
@Override public void onSelectLocation(SelectLocationEvent event) { mapPresenter.getViewPort().applyBounds(event.getBbox()); geocoderWidgetView.setValue(event.getCanonicalLocation()); }
java
public long skip(final long n) throws IOException { if (remaining == 0) { startChunk(); } if (remaining < 1) { return 0; } final long toSkip = n < remaining ? n : remaining; final long ret = input.skip(toSkip); this.remaining = remaining - ...
python
def red_dim(self, array): """ This function reduces the dimensions of an array until it is no longer of length 1. """ while isinstance(array, list) == True or \ isinstance(array, np.ndarray) == True: try: if len(array) == 1: ...
python
def fresh_working_set(): """return a pkg_resources "working set", representing the *currently* installed packages""" class WorkingSetPlusEditableInstalls(pkg_resources.WorkingSet): def __init__(self, *args, **kwargs): self._normalized_name_mapping = {} super(WorkingSetPlusEditab...
java
public void flush() { synchronized (mBufferLock) { if (mCurrentBuffer == null) { throw new IllegalStateException("No buffer to flush!"); } --mBufferDepth; if (mBufferDepth == 0) { final GLRunnable r = mRunnablePool.acquire(); ...
java
public SnapshotResponses getMessageSnapshots(String sdids, Boolean includeTimestamp) throws ApiException { ApiResponse<SnapshotResponses> resp = getMessageSnapshotsWithHttpInfo(sdids, includeTimestamp); return resp.getData(); }
python
def stop_app(app_id, is_finished=False): """ update app state to 'Stopped' """ state = constant.STATE_APP_STOPPED if is_finished else constant.STATE_APP_STOPPING app_update_state(app_id, state)
python
def glob (dirs, patterns): """ Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can...
python
def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = ...
java
void index(int indexToNavigateTo) { this.index = 0; this.offset = 0; this.nextSplit = StringUtil.indexOf(path, '.', 0); this.token = null; for (int i = 1; i <= indexToNavigateTo; i++) { if (!advanceToNextToken()) { throw new IndexOutOfBoundsException(...
java
protected static double sparsity(final int setsize, final int dbsize, final int k, final double phi) { // calculate sparsity c final double fK = MathUtil.powi(1. / phi, k); return (setsize - (dbsize * fK)) / FastMath.sqrt(dbsize * fK * (1 - fK)); }
java
private static ImmutableList<ImportTree> getWildcardImports(List<? extends ImportTree> imports) { ImmutableList.Builder<ImportTree> result = ImmutableList.builder(); for (ImportTree tree : imports) { // javac represents on-demand imports as a member select where the selected name is '*'. Tree ident ...
python
def _array_make_sure_table_exists(self, array_name, index, name_seq): """ Makes sure the table with the full name comprising of name_seq exists. """ t = self[array_name][index] for key in name_seq[:-1]: t = t[key] name = name_seq[-1] if name not in t: ...
python
def convert_to_kb(unit, size): ''' Converts the given size to KB based on the unit, returns a long integer. unit Unit of the size eg. GB; Note: to VMware a GB is the same as GiB = 1024MiB size Number which represents the size ''' if unit.lower() == 'gb': # vCenter needs ...
java
private Integer getReleaseId() { final String[] versionParts = stringVersion.split("-"); if(isBranch() && versionParts.length >= 3){ return Integer.valueOf(versionParts[2]); } else if(versionParts.length >= 2){ return Integer.valueOf(versionParts[1]); } return 0; }
java
void select(OptMapInfo alt) { if (alt.value == 0) return; if (value == 0) { copy(alt); return; } int v1 = z / value; int v2 = z /alt.value; if (mmd.compareDistanceValue(alt.mmd, v1, v2) > 0) copy(alt); }
java
public synchronized T borrow() throws JMSException { if (closed) throw new ObjectPoolException("Object pool is closed"); // Object immediately available ? int availableCount = available.size(); if (availableCount > 0) return available.remove(availableCount-1); // Can we create one more ? if (al...
python
def fft_propagate_3d(fftfield, d, nm, res, method="helmholtz", ret_fft=False): """Propagate a 2D Fourier transformed field in 3D Parameters ---------- fftfield : 2d array Fourier transform of 2D Electric field component d : float Distance to be propagated in p...
java
private static int metaPurge(final TSDB tsdb) throws Exception { final long start_time = System.currentTimeMillis() / 1000; final long max_id = CliUtils.getMaxMetricID(tsdb); // now figure out how many IDs to divy up between the workers final int workers = Runtime.getRuntime().availableProcessors()...
python
def revoke(self, only_access=False): """Revoke the current Authorization. :param only_access: (Optional) When explicitly set to True, do not evict the refresh token if one is set. Revoking a refresh token will in-turn revoke all access tokens associated with that authorizat...
java
public boolean notEquals(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.notEquals(this); return...
java
public void internalNodeRemoved( String internalNodeKey ) { if (this.snapshot.get().containsProjectionForInternalNode(internalNodeKey)) { // identify all the projections which from this internal (aka. federated node) and remove them synchronized (this) { Snapshot current ...
java
private void redirectToAccessDeniedView(FacesContext context, UIViewRoot viewRoot) { // If a user has already done a redirect and rendered the response (possibly in an observer) we cannot do this output final PhaseId currentPhase = context.getCurrentPhaseId(); if (!context.getResponseComplete() ...
python
def _attrs_to_tuple(obj, attrs): """ Create a tuple of all values of *obj*'s *attrs*. """ return tuple(getattr(obj, a.name) for a in attrs)
java
public final <T3, T4> Tuple4<T1, T2, T3, T4> concat(Tuple2<T3, T4> tuple) { return new Tuple4<>(v1, v2, tuple.v1, tuple.v2); }
java
public Object evaluate(TaskRequest req, TaskResponse res) { String rslt = null; try { rslt = new File(".").toURI().toURL().toExternalForm(); } catch (Throwable t) { String msg = "Unable to represent the current directory as a URL."; throw new RuntimeException(msg, t); } return rslt; }
java
@Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); // TODO: do we need to write/read the capacity? out.writeInt(entries.length); for(Entry entry : entries) { if(entry == null) { break; } entry.writeExternal(out); } }
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "onlyBasicPermissions", scope = GetACL.class) public JAXBElement<Boolean> createGetACLOnlyBasicPermissions(Boolean value) { return new JAXBElement<Boolean>(_GetACLOnlyBasicPermissions_QNAME, Boolean.class, GetACL.class,...
python
def run(self): ''' Run the api ''' ui = salt.spm.SPMCmdlineInterface() self.parse_args() self.setup_logfile_logger() v_dirs = [ self.config['spm_cache_dir'], ] verify_env(v_dirs, self.config['user'], ...
python
def parse_task_outputs(self, i): ''' Parse the WDL output section. Outputs are like declarations, with a type, name, and value. Examples: ------------ Simple Cases ------------ 'Int num = 7' var_name: 'num' var_type: 'Int' v...
java
public Optional<E> create(AnnotatedElement element) { Optional<E> component; for (Annotation annotation : element.getAnnotations()) { component = create(annotation); if (component.isPresent()) { return component; } } return Optional.empty(); }
java
public static List<Global> getVariableList( final List<String> variableCells ){ final List<Global> variableList = new ArrayList<Global>(); if ( variableCells == null ) return variableList; for( String variableCell: variableCells ){ final StringTokenizer tokens = new StringTokenizer(...
python
def log_in(self, username, password): """ Logs in to the CouchDB instance with the credentials `username` and `password` """ self.resource.credentials = (username, password) return self.resource.get_json("_session")[2]
python
def remove_showcase(self, showcase): # type: (Union[hdx.data.showcase.Showcase,Dict,str]) -> None """Remove dataset from showcase Args: showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary Returns: ...
python
def lint(ctx, scenario_name): # pragma: no cover """ Lint the role. """ args = ctx.obj.get('args') subcommand = base._get_subcommand(__name__) command_args = { 'subcommand': subcommand, } base.execute_cmdline_scenarios(scenario_name, args, command_args)
java
private CmsPair<String, org.apache.solr.client.solrj.SolrQuery.ORDER> getSort() { final String sortTitle = CmsSearchFieldConfiguration.getLocaleExtendedName( CmsSearchField.FIELD_TITLE_UNSTORED, getLocale()) + "_s"; switch (getSortOrder()) { case dateCreated_asc: ...
python
def filter_flags(use, use_expand_hidden, usemasked, useforced): ''' .. versionadded:: 2015.8.0 Filter function to remove hidden or otherwise not normally visible USE flags from a list. @type use: list @param use: the USE flag list to be filtered. @type use_expand_hidden: list @param u...
java
public ServiceFuture<BuildGetLogResultInner> getLogLinkAsync(String resourceGroupName, String registryName, String buildId, final ServiceCallback<BuildGetLogResultInner> serviceCallback) { return ServiceFuture.fromResponse(getLogLinkWithServiceResponseAsync(resourceGroupName, registryName, buildId), serviceCall...
java
public final Membership join(@Nullable final Runnable onLoseMembership) throws JoinException, InterruptedException { return join(NO_MEMBER_DATA, onLoseMembership); }
python
def usage(self, node_id=None, metric=None, params=None): """ The cluster nodes usage API allows to retrieve information on the usage of features for each node. `<http://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_ :arg node_id: A comma-separ...
python
def typechecked(memb): """Decorator applicable to functions, methods, properties, classes or modules (by explicit call). If applied on a module, memb must be a module or a module name contained in sys.modules. See pytypes.set_global_typechecked_decorator to apply this on all modules. Asserts compati...
java
@Nonnull public Iterator<S> bfsIterator() { Set<S> visited = new HashSet<>(); final Deque<S> bfsQueue = new ArrayDeque<>(); bfsQueue.add(root); visited.add(root); return new AbstractIterator<S>() { @Override protected S computeNext() { ...
python
def _get_single_set(self, num_objects, num_features): """Generate one input sequence and output label. Each sequences of objects has a feature that consists of the feature vector for that object plus the encoding for its ID, the reference vector ID and the n-th value relative ID for a total feature siz...
java
private boolean havePropogatedError() { Request req = getRequest(); return req != null && req.getAttribute(ACTION_ERROR_KEY) != null; }
python
def addgroupuser(username, uid, groupnames=None, system=False, no_login=True, no_password=False, gecos=None, sudo=False, **kwargs): """ Generates a unix command line for creating user and group with the same name, assigning the user to the group. Has the same effect as combining :func:`~add...
java
@Override public AddTagsToOnPremisesInstancesResult addTagsToOnPremisesInstances(AddTagsToOnPremisesInstancesRequest request) { request = beforeClientExecution(request); return executeAddTagsToOnPremisesInstances(request); }
java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); italicFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Italic.ttf"); regularFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Regular.ttf"); ...
python
def err_exit(msg, rc=1): """Print msg to stderr and exit with rc. """ print(msg, file=sys.stderr) sys.exit(rc)
python
def load_stream(filename): """Load a file stream from the package resources.""" rawfile = pkg_resources.resource_stream(__name__, filename) if six.PY2: return rawfile return io.TextIOWrapper(rawfile, 'utf-8')
java
protected StringDistance[] getInnerDistances() { StringDistance[] innerDistances = new StringDistance[ innerLearners.length ]; for (int j=0; j<innerLearners.length; j++) { innerDistances[j] = innerLearners[j].getDistance(); } return innerDistances; }
python
def serialize_to_bundle(self, transformer, path, model): """ :param transformer: Random Forest Regressor or Classifier :param path: Root path where to serialize the model :param model: Name of the model to be serialized :type transformer: sklearn.ensemble.forest.BaseForest ...
java
public void setSiteRoot(String siteRoot) { // site roots must never end with a "/" if (siteRoot.endsWith("/")) { m_siteRoot = siteRoot.substring(0, siteRoot.length() - 1); } else { m_siteRoot = siteRoot; } }
java
public static <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema, boolean numeric) throws IOException { ArrayBufferInput bios = new ArrayBufferInput(data, offset, length); MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bios); try ...
java
public static Object withTraits(Object self, Class<?>... traits) { List<Class> interfaces = new ArrayList<Class>(); Collections.addAll(interfaces, traits); return ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, self); }
python
def value_of( self, value: Union[sympy.Basic, float, str] ) -> Union[sympy.Basic, float]: """Attempt to resolve a Symbol or name or float to its assigned value. If unable to resolve a sympy.Symbol, returns it unchanged. If unable to resolve a name, returns a sympy.Sy...
java
@Override public EClass getIfcSectionedSpine() { if (ifcSectionedSpineEClass == null) { ifcSectionedSpineEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(590); } return ifcSectionedSpineEClass; }
python
def get_relative_embeddings_left_right(max_relative_position, length, depth, num_heads, heads_share_relative_embedding, name): """Instantiate or retrieve relative embeddings, sliced according to length...
python
def set_velocities(self, velocities): """ :param velocities (au): list of list of atom velocities :return: """ assert len(velocities) == len(self.mol) self.params["velocity"] = velocities
python
def decode_centroids(encoded, mapping): """Decodes the encoded centroids array back to the original data labels using a list of mappings. """ decoded = [] for ii in range(encoded.shape[1]): # Invert the mapping so that we can decode. inv_mapping = {v: k for k, v in mapping[ii].items(...
java
public EClass getEIM() { if (eimEClass == null) { eimEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(248); } return eimEClass; }
python
def tvBrowserAggregation_selection_changed(self): """Update layer description label.""" (is_compatible, desc) = self.get_layer_description_from_browser( 'aggregation') self.lblDescribeBrowserAggLayer.setText(desc) self.parent.pbnNext.setEnabled(is_compatible)
java
@SafeVarargs public static <Type> Validator<Type> disjunctive(@NonNull final CharSequence errorMessage, @NonNull final Validator<Type>... validators) { return DisjunctiveValidator.create(errorMessage, validators); }
java
public static Folder createFolderPath(final SecurityContext securityContext, final String path) throws FrameworkException { final App app = StructrApp.getInstance(securityContext); if (path == null) { return null; } Folder folder = (Folder) FileHelper.getFileByAbsolutePath(securityContext, path); if (...
java
PendingCheckpointStats reportPendingCheckpoint( long checkpointId, long triggerTimestamp, CheckpointProperties props) { ConcurrentHashMap<JobVertexID, TaskStateStats> taskStateStats = createEmptyTaskStateStatsMap(); PendingCheckpointStats pending = new PendingCheckpointStats( checkpointId, trigge...
python
def _handle_post(self, method, remainder, request=None): ''' Routes ``POST`` requests. ''' if request is None: self._raise_method_deprecation_warning(self._handle_post) # check for custom POST/PUT requests if remainder: match = self._handle_custom...
python
def init(self): """Init the connection to the Cassandra server.""" if not self.export_enable: return None # if username and/or password are not set the connection will try to connect with no auth auth_provider = PlainTextAuthProvider( username=self.username, pass...
python
def display_len(text): """ Get the display length of a string. This can differ from the character length if the string contains wide characters. """ text = unicodedata.normalize('NFD', text) return sum(char_width(char) for char in text)