language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static JavaRDD<String> listPaths(JavaSparkContext sc, String path, boolean recursive, Set<String> allowedExtensions) throws IOException { return listPaths(sc, path, recursive, allowedExtensions, sc.hadoopConfiguration()); }
java
private void initState() { skipPhase = false; beforeMethodException = false; //noinspection unchecked List<PhaseListener> listeners = (List<PhaseListener>) getStateHelper().get(PropertyKeys.phaseListeners); phaseListenerIterator = ((listeners != null) ...
python
def fastp_filtered_reads_chart(self): """ Function to generate the fastp filtered reads bar plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['filtering_result_passed_filter_reads'] = { 'name': 'Passed Filter' } keys['filtering_result_lo...
python
def resample(self, sampling_rate=None, variables=None, force_dense=False, in_place=False, kind='linear'): ''' Resample all dense variables (and optionally, sparse ones) to the specified sampling rate. Args: sampling_rate (int, float): Target sampling rate (in Hz). I...
python
def request_issuance(self, csr): """ Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes...
python
def stop_sync(self): """Safely stop this BLED112 instance without leaving it in a weird state""" # Stop to scan if self.scanning: self.stop_scan() # Disconnect all connected devices for connection_id in list(self.connections.get_connections()): self.disco...
python
def _validate(cls, message): """Confirm the validitiy of a given dict as an OpenXC message. Returns: ``True`` if the message contains at least a ``name`` and ``value``. """ valid = False if(('name' in message and 'value' in message) or ('id' in messag...
java
public static <A, B, EA extends A, A1> DecomposableMatchBuilder1<Tuple2<A, B>, A1> tuple2( DecomposableMatchBuilder1<EA, A1> a, MatchesExact<B> b) { List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.any(), ArgumentMatchers.eq(b.t)); return new DecomposableMatchBuilder1<Tuple2<A, B>, EA>( ...
java
public boolean fastEquals(NumberRange that) { return that != null && reverse == that.reverse && inclusive == that.inclusive && compareEqual(from, that.from) && compareEqual(to, that.to) && compareEqual(stepSize, that.stepSize); ...
java
protected void backtrack(final int newLevel) { assert 0 <= newLevel && newLevel <= this.level; if (newLevel == this.level) { return; } CLFrame f = this.control.back(); while (f.level() > newLevel) { assert f.level() == this.level; assert f.trail() < this.trail.siz...
python
def ReadClientCrashInfo(self, client_id): """Reads the latest client crash record for a single client.""" history = self.crash_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.ClientCrash.FromSerializedString(history[ts]) res.timestamp = ts r...
java
void addPTable(PdfPTable ptable) throws DocumentException { ColumnText ct = new ColumnText(writer.getDirectContent()); // if the table prefers to be on a single page, and it wouldn't //fit on the current page, start a new page. if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && cur...
python
def is_uniform(self): """Return if file contains a uniform series of pages.""" # the hashes of IFDs 0, 7, and -1 are the same pages = self.pages page = pages[0] if page.is_scanimage or page.is_nih: return True try: useframes = pages.useframes ...
python
def processPreKeyBundle(self, preKey): """ :type preKey: PreKeyBundle """ if not self.identityKeyStore.isTrustedIdentity(self.recipientId, preKey.getIdentityKey()): raise UntrustedIdentityException(self.recipientId, preKey.getIdentityKey()) if preKey.getSignedPreKey(...
java
static public double integrate(Function1D f, double tol, double a, double b) { return integrate(f, tol, a, b, 100); }
java
public final short readShortLE() throws IOException { int ch1 = this.read(); int ch2 = this.read(); if ((ch1 | ch2) < 0) throw new EOFException(); return (short)((ch2 << 8) + (ch1 << 0)); }
java
public void addProcedure(ProcedureDef procDef) { procDef.setOwner(this); _procedures.put(procDef.getName(), procDef); }
python
def restart(self, restart_only_stale_services=None, redeploy_client_configuration=None, restart_service_names=None): """ Restart all services in the cluster. Services are restarted in the appropriate order given their dependencies. @param restart_only_stale_services: Only restart services that ...
java
public final void mFLOAT() throws RecognitionException { try { int _type = FLOAT; int _channel = DEFAULT_TOKEN_CHANNEL; // src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:88:5: ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( Exponent )? ( FloatTypeSuffix )? | '.' ( '0' .. '9' )+ ( Exponent )? ( FloatTypeSuff...
java
@Override public void prepare(@SuppressWarnings("rawtypes") Map conf, TridentOperationContext context) { this.objectMapper = new ObjectMapper(); this.javaDateFormat = new SimpleDateFormat(this.dateFormatStr); }
python
def outputscreate(): """ Brain.Outputs table creation :return: """ # Create table with a nested index r.db("Brain").table_create("Outputs").run() r.db("Brain").table("Outputs").index_create("Output_job_id", r.row["OutputJob"]["id"]).run() r.db("Brain").table("Outputs").index_wait("Output...
java
public static IntBuffer allocate (int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 4); bb.order(ByteOrder.nativeOrder()); return bb.asIntBuffer(); }
java
public static String getProperty(final ResourceBundle bundle, final String key) { if (bundle == null) { return key; } try { return bundle.getString(key); } catch (MissingResourceException e) { LOG.warn("找不到名为 " + key + " 的资源项", e); return key; } }
java
public final int getNumberOfCommandLineArgs() { if (commandLine == null) { return 0; } List<?> args = commandLine.getArgList(); if (args == null) { return 0; } return args.size(); }
java
public static String getProperty(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getProperty(name); } catch (MissingPropertyException mpe) { // Do nothing, since we have a...
python
def _try_compile(source, name): """Attempts to compile the given source, first as an expression and then as a statement if the first approach fails. Utility function to accept strings in functions that otherwise expect code objects """ try: c = compile(source, name, 'eval') ...
java
protected void on(JsonToken token, String fieldName, JsonParser jp) throws JsonParseException, IOException { switch (token) { case START_OBJECT: onStartObject(fieldName, jp); break; case END_OBJECT: onEndObject(fieldName, jp); break; case START_ARRAY: onStartArray(fieldName, jp); brea...
java
public long roundHalfFloor(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor <= diffToCeiling) { // Closer to the floor, or halfway ...
java
public void setInitialClusters(List<? extends Cluster<? extends MeanModel>> initialMeans) { double[][] vecs = new double[initialMeans.size()][]; for(int i = 0; i < vecs.length; i++) { vecs[i] = initialMeans.get(i).getModel().getMean(); } this.initialMeans = vecs; }
java
@Override public List<byte[]> sort(final byte[] key, final SortingParams sortingParameters) { checkIsInMultiOrPipeline(); client.sort(key, sortingParameters); return client.getBinaryMultiBulkReply(); }
java
public static LocalCall<Map<String, Xor<Info, List<Info>>>> infoInstalledAllVersions( List<String> attributes, boolean reportErrors, String... packages) { LinkedHashMap<String, Object> kwargs = new LinkedHashMap<>(); kwargs.put("attr", attributes.stream().collect(Collectors.joining(","))); ...
python
def delete_policy(self, scaling_group, policy): """ Deletes the specified policy from the scaling group. """ return self._manager.delete_policy(scaling_group=scaling_group, policy=policy)
python
def opsview_info(self, verbose=False): ''' Get information about the current opsview instance http://docs.opsview.com/doku.php?id=opsview4.6:restapi#opsview_information ''' url = '{}/{}'.format(self.rest_url, 'info') return self.__auth_req_get(url, verbose=verbose)
java
public void evaluate(XPathContext xctxt, FastStringBuffer buf, int context, org.apache.xml.utils.PrefixResolver nsNode) { buf.append(m_val); }
python
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" state = self.splitter.saveState() self.set_option('splitter_state', qbytearray_to_str(state)) filenames = [] editorstack = self.editorstacks[0] active_project_pat...
python
def get_names(cs): """Return list of every name.""" records = [] for c in cs: records.extend(c.get('names', [])) return records
java
@Override @SuppressWarnings("unchecked") public <E extends Entity> E getEntity(String attributeName, Class<E> clazz) { Entity entity = delegate().getEntity(attributeName, clazz); if (clazz.equals(FileMeta.class)) { return entity != null ? (E) new FileMeta(newPretendingEntity(entity)) : null; } els...
java
public String camelCase( String lowerCaseAndUnderscoredWord, boolean uppercaseFirstLetter, char... delimiterChars ) { if (lowerCaseAndUnderscoredWord == null) return null; lowerCaseAndUnderscoredWord = lowerCaseAndUnderscoredWord.trim(); ...
python
def choropleth(): """ Returns """ path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv') df=pd.read_csv(path) del df['Unnamed: 0'] df['z']=[np.random.randint(0,100) for _ in range(len(df))] return df
python
def sign(self, msg, key): """ Create a signature over a message as defined in RFC7515 using an RSA key :param msg: the message. :type msg: bytes :returns: bytes, the signature of data. :rtype: bytes """ if not isinstance(key, rsa.RSAPrivateKey): ...
java
public FutureData<DataSiftResult> start(FutureData<PreparedHistoricsQuery> query) { if (query == null) { throw new IllegalArgumentException("A valid PreparedHistoricsQuery is required"); } final FutureData<DataSiftResult> future = new FutureData<>(); DataSiftResult h = new Ba...
java
public PutMethodResult withMethodResponses(java.util.Map<String, MethodResponse> methodResponses) { setMethodResponses(methodResponses); return this; }
java
public static Collection<Channel> filterbyTags( Collection<Channel> channels, Collection<String> tagNames) { Collection<Channel> result = new ArrayList<Channel>(); Collection<Channel> input = new ArrayList<Channel>(channels); for (Channel channel : input) { if (channel.getTagNames().containsAll(tagNames)) {...
java
public static List<CompiledAutomaton> createAutomata(String prefix, String regexp, Map<String, Automaton> automatonMap) throws IOException { List<CompiledAutomaton> list = new ArrayList<>(); Automaton automatonRegexp = null; if (regexp != null) { RegExp re = new RegExp(prefix + MtasToken.DELIMIT...
java
static int maximumDistance(List<Point2D_I32> contour , int indexA , int indexB ) { Point2D_I32 a = contour.get(indexA); Point2D_I32 b = contour.get(indexB); int best = -1; double bestDistance = -Double.MAX_VALUE; for (int i = 0; i < contour.size(); i++) { Point2D_I32 c = contour.get(i); // can't sum s...
java
public static int getWrappedValue(int value, int minValue, int maxValue) { if (minValue >= maxValue) { throw new IllegalArgumentException("MIN > MAX"); } int wrapRange = maxValue - minValue + 1; value -= minValue; if (value >= 0) { return (value % wrapRa...
python
def save_outputs(self, rootpath='.', raw=False): """Saves TWI, UCA, magnitude and direction of slope to files. """ self.save_twi(rootpath, raw) self.save_uca(rootpath, raw) self.save_slope(rootpath, raw) self.save_direction(rootpath, raw)
java
protected void setJoin(String[] masterLabels, String masterColumn, String dataColumn, List<String> masterData) { setJoin(masterLabels, masterColumn, dataColumn, null, false, masterData); }
python
def set(self, instance, value, **kw): # noqa """Set the value of the refernce field """ ref = [] # The value is an UID if api.is_uid(value): ref.append(api.get_object_by_uid(value)) # The value is already an object if api.is_at_content(value): ...
java
public static <T extends Message> Marshaller<T> jsonMarshaller( final T defaultInstance, final Parser parser, final Printer printer) { final Charset charset = Charset.forName("UTF-8"); return new Marshaller<T>() { @Override public InputStream stream(T value) { try { return ...
java
public void error( XPathContext xctxt, int sourceNode, String msg, Object[] args) throws javax.xml.transform.TransformerException { String fmsg = XSLMessages.createXPATHMessage(msg, args); ErrorListener ehandler = xctxt.getErrorListener(); if (null != ehandler) { ehandler...
python
def directly_connected(self, ident): '''Return a generator of labels connected to ``ident``. ``ident`` may be a ``content_id`` or a ``(content_id, subtopic_id)``. If no labels are defined for ``ident``, then the generator will yield no labels. Note that this only retur...
java
public JsMessage next() throws SIResourceException, SISessionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "next"); JsMessage msg = null; Iterator<BrowseCursor> it = cursors.iterator(); while(it.hasNext() && msg==null) msg = it.ne...
java
public EClass getIfcIonConcentrationMeasure() { if (ifcIonConcentrationMeasureEClass == null) { ifcIonConcentrationMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(690); } return ifcIonConcentrationMeasureEClass; }
java
@Override public boolean existsInStore(IEntityLock lock) throws LockingException { Class entityType = lock.getEntityType(); String key = lock.getEntityKey(); Integer lockType = lock.getLockType(); Date expiration = lock.getExpirationTime(); String owner = lock.getLockOwner();...
python
def _srels_for(phys_reader, source_uri): """ Return |_SerializedRelationships| instance populated with relationships for source identified by *source_uri*. """ rels_xml = phys_reader.rels_xml_for(source_uri) return _SerializedRelationships.load_from_xml( sourc...
python
def post_message(name, user=None, device=None, message=None, title=None, priority=None, expire=None, retry=None, sound=None, api_version=1, token=None...
python
def _set_port_list(self, v, load=False): """ Setter method for port_list, mapped from YANG variable /tvf_domain_list_state/domain_list/port_list (container) If this variable is read-only (config: false) in the source YANG file, then _set_port_list is considered as a private method. Backends looking ...
python
def properties(self): """ Properties for Introspection results. :return: :rtype: """ properties = defaultdict(list) for pattern in self.patterns: for key, values in pattern.properties.items(): extend_safe(properties[key], values) ...
java
@Override public AdminRemoveUserFromGroupResult adminRemoveUserFromGroup(AdminRemoveUserFromGroupRequest request) { request = beforeClientExecution(request); return executeAdminRemoveUserFromGroup(request); }
java
private PHSFellowshipSupplemental11 getPHSFellowshipSupplemental11() { PHSFellowshipSupplemental11 phsFellowshipSupplemental = PHSFellowshipSupplemental11.Factory .newInstance(); phsFellowshipSupplemental.setFormVersion(FormVersion.v1_1.getVersion()); phsFellowshipSupplemental.setApplicationType(getApplicatio...
python
def _find_usage_applications(self): """find usage for ElasticBeanstalk applications""" applications = self.conn.describe_applications() self.limits['Applications']._add_current_usage( len(applications['Applications']), aws_type='AWS::ElasticBeanstalk::Application', ...
java
@Override public InsertsType getDefaultInsertsType() { return InsertsType.valueOf(getDefaultProps().getOrDefault(PROPS_KEY_DEFAULT_INSERTS_TYPE, InsertsType.BULK.toString())); }
java
@Override public <T> void postProcess(T anyContext) { Tuple2<List<String>, List<String>> dimsAndMetrics = (Tuple2<List<String>, List<String>>)anyContext; List<String> dims = dimsAndMetrics._1(); List<String> metrics = dimsAndMetrics._2(); Iterator<Map.Entry<String, String>> colIter =...
python
async def _do(self, ctx, times: int, *, command): """Repeats a command a specified number of times.""" msg = copy.copy(ctx.message) msg.content = command for i in range(times): await self.bot.process_commands(msg)
python
def _filters_to_query(self, includes, excludes, serializer, q=None): """ Construct Django Query object from request. Arguments are dictionaries, which will be passed to Q() as kwargs. e.g. includes = { 'foo' : 'bar', 'baz__in' : [1, 2] } produces: Q(foo...
python
def forum_topic_get_by_tag_for_user(self, tag=None, author=None): """Get all forum topics with a specific tag""" if not tag: return None if author: r = self._request('ebuio/forum/search/bytag/' + tag + '?u=' + author) else: r = self._request('ebuio/f...
python
def plot_options(cls, obj, percent_size): """ Given a holoviews object and a percentage size, apply heuristics to compute a suitable figure size. For instance, scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad ...
java
public RelationshipTuple[] getRelationships(Context context, String pid, String relationship) throws ServerException { return worker.getRelationships(context, pid, relationship); }
java
public Observable<EntityRole> getClosedListEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId) { return getClosedListEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).map(new Func1<ServiceResponse<EntityRole>, EntityRole>() { @Override public En...
java
protected final void firePropertyChange( final String propertyName, final Object oldValue, final Object newValue) { propertySupport.firePropertyChange(propertyName, oldValue, newValue); }
java
@Override public String getFormatPattern( DisplayStyle style, Locale locale ) { return GenericDatePatterns.get("chinese", style, locale); // always redirect to chinese calendar }
java
protected static boolean isFolder(CmsResource resource) throws CmsLoaderException { I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(resource.getTypeId()); return resourceType.isFolder(); }
java
public static <T> String join(T[] array, CharSequence conjunction, String prefix, String suffix) { if (null == array) { return null; } final StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (T item : array) { if (isFirst) { isFirst = false; } else { sb.append(co...
java
public synchronized static void write(int fd, CharBuffer ... data) throws IllegalStateException, IOException { write(fd, StandardCharsets.US_ASCII, data); }
java
public boolean existsResource(String resourcename, CmsResourceFilter filter) { return m_securityManager.existsResource(m_context, addSiteRoot(resourcename), filter); }
java
static public List<ColumnMetaData> createList(ResultSetMetaData m) throws SQLException{ List<ColumnMetaData> result = new ArrayList<ColumnMetaData>(m.getColumnCount()); for (int i = 1; i <= m.getColumnCount(); i ++){ ColumnMetaData cm = new ColumnMetaData(m, i); result.add(cm); } return result; }
java
public String getClassificationId(ScopCategory category) { if(classificationId == null || classificationId.isEmpty()) { return null; } int numParts = 0; switch(category) { case Family: numParts++; case Superfamily: numParts++; case Fold: numParts++; case Class: numParts++; break; ...
python
def get_db_prep_value(self, value, connection, prepared=False): """ Further conversion of Python value to database value for QUERYING. This follows ``get_prep_value()``, and is for backend-specific stuff. See notes above. """ log.debug("get_db_prep_value: {}, {}", value, ...
java
public void setTime(Date time) { String timeString = ""; if (time != null) timeString = timeFormat.format(time); jTextField3.setText(timeString); jTimeButton1.setTargetDate(time); }
java
protected Map<Page, Double> getSimilarPages(String pPattern, int pSize) throws WikiApiException { Title title = new Title(pPattern); String pattern = title.getWikiStyleTitle(); // a mapping of the most similar pages and their similarity values // It is returned by this method. M...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.MCDRG__RG_LENGTH: return RG_LENGTH_EDEFAULT == null ? rgLength != null : !RG_LENGTH_EDEFAULT.equals(rgLength); case AfplibPackage.MCDRG__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super....
java
int nextSymbol() { // Move to next group selector if required if (++groupPosition % HUFFMAN_GROUP_RUN_LENGTH == 0) { groupIndex++; if (groupIndex == selectors.length) { throw new DecompressionException("error decoding block"); } currentTabl...
python
def match_precision(val, ref, *args, **kwargs): """ Returns a string version of a value *val* matching the significant digits as given in *ref*. *val* might also be a numpy array. All remaining *args* and *kwargs* are forwarded to ``Decimal.quantize``. Example: .. code-block:: python match...
python
def group_files_by_size_fast(fileslist, nbgroups, mode=1): # pragma: no cover '''Given a files list with sizes, output a list where the files are grouped in nbgroups per cluster. Pseudo-code for algorithm in O(n log(g)) (thank's to insertion sort or binary search trees) See for more infos: http://cs.stack...
python
def add_handler(cls, level, fmt, colorful, **kwargs): """Add a configured handler to the global logger.""" global g_logger if isinstance(level, str): level = getattr(logging, level.upper(), logging.DEBUG) handler = cls(**kwargs) handler.setLevel(level) if colorful: formatte...
python
def htmlReadDoc(cur, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options) if ret is None:raise treeError('htmlReadDoc() failed') return xmlDoc(_obj=ret)
java
public void setRules(java.util.Collection<DataRetrievalRule> rules) { if (rules == null) { this.rules = null; return; } this.rules = new java.util.ArrayList<DataRetrievalRule>(rules); }
java
private static void adjustCalibrated(FMatrixRMaj rectifyLeft, FMatrixRMaj rectifyRight, FMatrixRMaj rectifyK, RectangleLength2D_F32 bound, float scale) { // translation float deltaX = -bound.x0*scale; float deltaY = -bound.y0*scale; // adjustment matrix SimpleMatrix A = new SimpleMatrix...
java
public AsciiTable setPaddingLeftRight(int paddingLeft, int paddingRight){ for(AT_Row row : this.rows){ if(row.getType()==TableRowType.CONTENT){ row.setPaddingLeftRight(paddingLeft, paddingRight); } } return this; }
java
public OvhOrder license_virtuozzo_new_duration_POST(String duration, OvhOrderableVirtuozzoContainerNumberEnum containerNumber, String ip, OvhLicenseTypeEnum serviceType, OvhOrderableVirtuozzoVersionEnum version) throws IOException { String qPath = "/order/license/virtuozzo/new/{duration}"; StringBuilder sb = path(q...
java
public static String getCurrentDateTime(final String localeLang, final String localeCountry, final String timezone, final String dateFormat) throws Exception { final DateTimeFormatter formatter = getDateTimeFormatter(localeLang, localeCountry, timezone, dateFormat); final DateTime datetime = DateTime.no...
java
public static NameVirtualHostHandler virtualHost(final HttpHandler hostHandler, String... hostnames) { NameVirtualHostHandler handler = new NameVirtualHostHandler(); for (String host : hostnames) { handler.addHost(host, hostHandler); } return handler; }
python
def is_nested_list_like(obj): """ Check if the object is list-like, and that all of its elements are also list-like. .. versionadded:: 0.20.0 Parameters ---------- obj : The object to check Returns ------- is_list_like : bool Whether `obj` has list-like properties. ...
python
def _handler_http(self, result): """ Handle the result of an http monitor """ monitor = result['monitor'] self.thread_debug("process_http", data=monitor, module='handler') self.stats.http_handled += 1 # splunk will pick this up logargs = { 'ty...
java
public final void assignmentOperator() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:730:5: ( EQUALS_ASSIGN | PLUS_ASSIGN | MINUS_ASSIGN | MULT_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | MOD_ASSIGN | LESS LESS EQUALS_ASSIGN | ( GREATER GREATER...
java
@Override public CPFriendlyURLEntry[] findByUuid_PrevAndNext( long CPFriendlyURLEntryId, String uuid, OrderByComparator<CPFriendlyURLEntry> orderByComparator) throws NoSuchCPFriendlyURLEntryException { CPFriendlyURLEntry cpFriendlyURLEntry = findByPrimaryKey(CPFriendlyURLEntryId); Session session = null; ...
python
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
java
public String encode() throws IOException { FastStringWriter fsw = new FastStringWriter(); try { ChartUtils.writeDataValue(fsw, "display", this.display, false); ChartUtils.writeDataValue(fsw, "position", this.position, true); ChartUtils.writeDataValue(fsw, "fullWidth...
python
def _inject_conversion(self, value, conversion): """ value: '{x}', conversion: 's' -> '{x!s}' """ t = type(value) return value[:-1] + t(u'!') + conversion + t(u'}')