language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def ec2_route_table_main_route_table_id(self, lookup, default=None): """ Args: lookup: the friendly name of the VPC whose main route table we are looking up default: the optional value to return if lookup failed; returns None if not set Returns: the ID of the main route table of the named ...
python
def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.Marath...
java
public static void signToInfo(String info, String signfile) { // 从文件当中读取私匙 PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1); // 从文件中读取公匙 PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2); try { // Signature 对象可用来生成和验证数字签名 Signature signet = Signature.getInstance("DSA"); ...
python
def find_command(cmd, path=None, pathext=None): """ Taken `from Django http://bit.ly/1njB3Y9>`_. """ if path is None: path = os.environ.get('PATH', '').split(os.pathsep) if isinstance(path, string_types): path = [path] # check if there are path extensions for Windows executables...
python
def candle_lighting(self): """Return the time for candle lighting, or None if not applicable.""" today = HDate(gdate=self.date, diaspora=self.location.diaspora) tomorrow = HDate(gdate=self.date + dt.timedelta(days=1), diaspora=self.location.diaspora) # If today...
java
void setServletPaths(String servletPath, String pathInfo, ServletHolder holder) { _servletPath=servletPath; _pathInfo=pathInfo; _servletHolder=holder; }
java
public static boolean replaceEntry(File zip, ZipEntrySource entry, File destZip) { return replaceEntries(zip, new ZipEntrySource[] { entry }, destZip); }
java
@Override public boolean contains(Object arg0) { checkUnsupportedOperationForIterationOnlyMode("contains(Object arg0)"); if ( allResults.contains(arg0) ) return true; while ( nextResultsAvailable() ) { boolean found = nextResults.contains(arg0); ...
java
public Assignment update(Border border) { Arrays.sort(cs); int j = 1; boolean found = (cs[0].core == border.core); for(int i = 1; i < cs.length; i++) { if(cs[i].core != cs[i - 1].core) { cs[j++] = cs[i]; } found |= (cs[i].core == border.core); } if(found) { if(j =...
java
public synchronized boolean killConnectionListener(String id) { ConnectionListener cl = null; Iterator<ConnectionListener> it = listeners.keySet().iterator(); while (cl == null && it.hasNext()) { ConnectionListener l = it.next(); if (Integer.toHexString(System.identityHashCo...
java
public static void logStderr(String msg, Throwable e) { try { long now = CurrentTime.currentTime(); //msg = QDate.formatLocal(now, "[%Y-%m-%d %H:%M:%S] ") + msg; _origSystemErr.println(msg); //e.printStackTrace(_origSystemErr.getPrintWriter()); _origSystemErr.flush(); } c...
python
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') ...
java
@Override public T add(final Asset asset, final String target, final String name) throws IllegalArgumentException { Validate.notNull(target, "target must be specified"); final ArchivePath path = ArchivePaths.create(target); return this.add(asset, path, name); }
java
public Observable<RestorePointInner> getAsync(String resourceGroupName, String serverName, String databaseName, String restorePointName) { return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointName).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner>() { ...
python
def delete(self, table_id): """ Delete a table in Google BigQuery Parameters ---------- table : str Name of table to be deleted """ from google.api_core.exceptions import NotFound if not self.exists(table_id): raise NotFoundException("Tab...
java
public static <T extends FieldDescription> ElementMatcher.Junction<T> genericFieldType(Type fieldType) { return genericFieldType(TypeDefinition.Sort.describe(fieldType)); }
java
public static MeanVarianceMinMax[] newArray(int dimensionality) { MeanVarianceMinMax[] arr = new MeanVarianceMinMax[dimensionality]; for(int i = 0; i < dimensionality; i++) { arr[i] = new MeanVarianceMinMax(); } return arr; }
java
public void setResourceSpecificResults(java.util.Collection<ResourceSpecificResult> resourceSpecificResults) { if (resourceSpecificResults == null) { this.resourceSpecificResults = null; return; } this.resourceSpecificResults = new com.amazonaws.internal.SdkInternalList<...
java
public static void appendHex(StringBuilder builder, byte b, boolean toLowerCase) { final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER; int high = (b & 0xf0) >>> 4;//高位 int low = b & 0x0f;//低位 builder.append(toDigits[high]); builder.append(toDigits[low]); }
java
public ChannelManagementSyncClient build() { final Builder okHttpClientBuilder = new Builder(); okHttpClientBuilder .addInterceptor(buildAuthenticationInterceptor(channelTokenSupplier)) .addInterceptor(buildLoggingInterceptor()); final OkHttpClient okHttpClient ...
python
def fist() -> Histogram1D: """A simple histogram in the shape of a fist.""" import numpy as np from ..histogram1d import Histogram1D widths = [0, 1.2, 0.2, 1, 0.1, 1, 0.1, 0.9, 0.1, 0.8] edges = np.cumsum(widths) heights = np.asarray([4, 1, 7.5, 6, 7.6, 6, 7.5, 6, 7.2]) + 5 return Histogram1...
python
def texture(self, size, components, data=None, *, samples=0, alignment=1, dtype='f1') -> 'Texture': ''' Create a :py:class:`Texture` object. Args: size (tuple): The width and height of the texture. components (int): The number of components 1, 2, 3 or 4. ...
java
@Override public Conversation connect(InetSocketAddress remoteHost, ConversationReceiveListener convRecvListener, String chainName) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()...
java
public JaversBuilder registerValueGsonTypeAdapter(Class valueType, TypeAdapter nativeAdapter) { registerValue(valueType); jsonConverterBuilder().registerNativeTypeAdapter(valueType, nativeAdapter); return this; }
java
protected String resolveVersion(final MavenDependency dependency) throws IllegalArgumentException { final String declaredVersion = dependency.getVersion(); if (Validate.isNullOrEmpty(declaredVersion)) { throw new ResolutionException(MessageFormat.format( "Unable to get versio...
java
public final Integer getPriority() { // If the transient is not set, get the int value from the message and cache it. if (cachedPriority == null) { cachedPriority = (Integer) getHdr2().getField(JsHdr2Access.PRIORITY); } // Return the (possibly newly) cached value retu...
python
def extract(args): """ %prog extract fasta query extract query out of fasta file, query needs to be in the form of "seqname", or "seqname:start-stop", or "seqname:start-stop:-" """ p = OptionParser(extract.__doc__) p.add_option('--newname', help="Use this new name instead") p.add_option...
java
public void marshall(ListAttachedIndicesRequest listAttachedIndicesRequest, ProtocolMarshaller protocolMarshaller) { if (listAttachedIndicesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(l...
java
@Override public List<String> getModules() throws BadRequestException { final String sourceMethod = "getModules"; //$NON-NLS-1$ if (isTraceLogging) { log.entering(RequestedModuleNames.class.getName(), sourceMethod); } if (modules == null) { modules = decodeModules(moduleQueryArg, base64decodedIdLi...
python
def trailing_blank_lines(physical_line, lines, line_number, total_lines): r"""Trailing blank lines are superfluous. Okay: spam(1) W391: spam(1)\n However the last line should end with a new line (warning W292). """ if line_number == total_lines: stripped_last_line = physical_line.rstri...
java
public long wrapRecords(ChunkStream<byte[], BytesReference> stream, boolean withCollection) throws IOException { final AtomicInteger l = new AtomicInteger(); try { // keep reference to our record listener here, because builder will // enforce an intern...
java
@Override public boolean isWithin(double delta) { readLock.lock(); try { if (average.getCount() > min.getInitialSize()) { return (deviation() < delta); } else { return false; ...
python
def create_submission(self, source_code, language_name=None, language_id=None, std_input="", run=True, private=False): """ Create a submission and upload it to Ideone. Keyword Arguments ----------------- * source_code: a string of the programs source c...
java
private void putInCache(UserProfile profile) { cache.put(profile.getUserName(), profile, CacheType.USER_PROFILE); }
java
public <K, V> Map<K, V> map(String name, Class<K> ktype, Class<V> vtype) { Map<K, V> map = getNamedObject(name); if (map == null) putNamedObject(name, map = new HashMap<K, V>()); return map; }
python
def guessFormat(self): '''return quality score format - might return several if ambiguous.''' c = [ord(x) for x in self.quals] mi, ma = min(c), max(c) r = [] for entry_format, v in iteritems(RANGES): m1, m2 = v if mi >= m1 and ma < m2: ...
java
public void initialize( Supplier<DataSource<Bitmap>> dataSourceSupplier, String id, Object callerContext) { super.initialize(id, callerContext); init(dataSourceSupplier); }
python
def css(self): """Clayton Skill Score (ad - bc)/((a+b)(c+d))""" return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[0, 1]) * (self.table[1, 0] + self.table[1, 1]))
java
private static boolean isPermanentError(Throwable throwable) { Status status = getStatus(throwable); switch (status.getCode()) { case CANCELLED: case UNKNOWN: case DEADLINE_EXCEEDED: case RESOURCE_EXHAUSTED: case INTERNAL: case UNAVAILABLE: case UNAUTHENTICATED: ...
python
def next_update(self, value): """ A datetime.datetime object of when the response may next change. This should only be set if responses are cached. If responses are generated fresh on every request, this should not be set. """ if not isinstance(value, datetime): ...
java
public Map<String, Object> toObject() { final List<String> slaActions = new ArrayList<>(); final Map<String, Object> slaInfo = new HashMap<>(); slaInfo.put(SlaOptionDeprecated.INFO_FLOW_NAME, this.flowName); if (hasAlert()) { slaActions.add(SlaOptionDeprecated.ACTION_ALERT); slaInfo.put(Sla...
java
@SuppressWarnings("unchecked") @Override public T readConfig(InputStream fileAsStream) throws ConfigurationException { XStream xstream = new XStream(new StaxDriver()); xstream.alias("configuration", clazz); return (T) xstream.fromXML(fileAsStream); }
python
def _normalize_eigensystem(u, lv, rv): """Normalize the eigenvectors of a reversible Markov state model according to our preferred scheme. """ # first normalize the stationary distribution separately lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0]) for i in range(1, lv.shape[1]): # the remaining ...
python
def perform_align(input_list, **kwargs): """Main calling function. Parameters ---------- input_list : list List of one or more IPPSSOOTs (rootnames) to align. archive : Boolean Retain copies of the downloaded files in the astroquery created sub-directories? clobber : Boolean ...
java
public void writeStringUTF8(String data) throws AsnException, IOException { this.writeStringUTF8(Tag.CLASS_UNIVERSAL, Tag.STRING_UTF8, data); }
python
def deprovision(self, instance_id: str, details: DeprovisionDetails, async_allowed: bool) -> DeprovisionServiceSpec: """ Further readings `CF Broker API#Deprovisioning <https://docs.cloudfoundry.org/services/api.html#deprovisioning>`_ :param instance_id: Instance id provided...
java
public com.google.javascript.jscomp.Requirement.TypeMatchingStrategy getTypeMatchingStrategy() { com.google.javascript.jscomp.Requirement.TypeMatchingStrategy result = com.google.javascript.jscomp.Requirement.TypeMatchingStrategy.valueOf(typeMatchingStrategy_); return result == null ? com.google.javascript.jsco...
java
@Override public DeleteVoiceConnectorTerminationResult deleteVoiceConnectorTermination(DeleteVoiceConnectorTerminationRequest request) { request = beforeClientExecution(request); return executeDeleteVoiceConnectorTermination(request); }
python
def get_enabled(limit=''): ''' Return the enabled services. Use the ``limit`` param to restrict results to services of that type. CLI Examples: .. code-block:: bash salt '*' service.get_enabled salt '*' service.get_enabled limit=upstart salt '*' service.get_enabled limit=s...
java
@SuppressWarnings( { "unchecked" }) public static <T> Enhancer<T> getDirtyableDBObjectEnhancer(Class<T> baseClass) { if (dirtyableDBObjectEnhancers.containsKey(baseClass)) { return (Enhancer<T>) dirtyableDBObjectEnhancers.get(baseClass); } synchronized (dirtyableDBObjectEnhancer...
java
@Override public void toWriter(boolean wholeDocument, Writer writer, Properties outputProperties) { try { super.toWriter(wholeDocument, writer, outputProperties); } catch (TransformerException e) { throw wrapExceptionAsRuntimeException(e); } }
python
def get_tag_ns(self, el): """Get tag namespace.""" if self.supports_namespaces(): namespace = '' ns = el.namespace if ns: namespace = ns else: namespace = NS_XHTML return namespace
python
def status(self): """ The current status of the event (started, finished or pending). """ myNow = timezone.localtime(timezone=self.tz) if getAwareDatetime(self.date, self.time_to, self.tz) < myNow: return "finished" elif getAwareDatetime(self.date, self.time_f...
java
@Override public CPOption[] findByGroupId_PrevAndNext(long CPOptionId, long groupId, OrderByComparator<CPOption> orderByComparator) throws NoSuchCPOptionException { CPOption cpOption = findByPrimaryKey(CPOptionId); Session session = null; try { session = openSession(); CPOption[] array = new CPOptio...
java
public static void cleanup(Driver driver) { try { DriverManager.deregisterDriver(driver); } catch (SQLException ex) { LOGGER.debug("An error occurred unloading the database driver", ex); } catch (Throwable unexpected) { LOGGER.debug("An unexpected throwable oc...
python
def to_single_data(input): """Convert an input to a single bcbio data/world object. Handles both single sample cases (CWL) and all sample cases (standard bcbio). """ if (isinstance(input, (list, tuple)) and len(input) == 1): return input[0] else: assert isinstance(input, dict), inpu...
python
def compose(*funcs): """ Compose any number of unary functions into a single unary function. >>> import textwrap >>> from six import text_type >>> stripped = text_type.strip(textwrap.dedent(compose.__doc__)) >>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped True Compose also allows th...
python
def _bind_channels(self, events, channels): """ Binds given channel events to callbacks. :param events: str or list :param channels: dict of channel_name: callback_method() pairs :return: """ for channel_name in channels: if channel_name in self.channe...
python
def start_(name): ''' Start a container name Container name or ID **RETURN DATA** A dictionary will be returned, containing the following keys: - ``status`` - A dictionary showing the prior state of the container as well as the new state - ``result`` - A boolean noting whet...
python
def get_running_time(self): """ Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATI...
python
def popvalue(self, k, d=None): """ D.popvalue(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ if k not in self._col_dict: return d value = self._col_dict.pop(k)...
java
@Warmup(iterations = 5) @Measurement(iterations = 5) @Benchmark public void structLoggerLogging1Call() { structLoggerNoMessageParametrization.info("Event with double and boolean") .varDouble(1.2) .varBoolean(false) .log(); }
python
def get_angle_difference(v1, v2): """returns angular difference in degrees between two vectors. takes in cartesian coordinates.""" v1 = numpy.array(v1) v2 = numpy.array(v2) angle=numpy.arccos(old_div((numpy.dot(v1, v2) ), (numpy.sqrt(math.fsum(v1**2)) * numpy.sqrt(math.fsum(v2**2))))) return ma...
java
@Override public boolean isOrderDeterministic() { assert(m_children != null); assert(m_children.size() == 1); // This implementation is very close to AbstractPlanNode's implementation of this // method, except that we assert just one child. // Java doesn't allow calls to sup...
python
def date_decimal_hook(dct): '''The default JSON decoder hook. It is the inverse of :class:`stdnet.utils.jsontools.JSONDateDecimalEncoder`.''' if '__datetime__' in dct: return todatetime(dct['__datetime__']) elif '__date__' in dct: return todatetime(dct['__date__']).date() elif '__decimal...
java
public void spawnTracksFromDetected() { // mark detected features with no matches as available FastQueue<AssociatedIndex> matches = associate.getMatches(); int N = detector.getNumberOfFeatures(); for( int i = 0; i < N; i++ ) associated[i] = false; for( AssociatedIndex i : matches.toList() ) { associat...
python
def as_urlpatterns(self): """ Creates the appropriate URLs for this object. """ urls = [] # for each of our actions for action in self.actions: view_class = self.view_for_action(action) view_pattern = self.pattern_for_view(view_class, action) ...
java
public void drawImage (final PDImageXObject image, final float x, final float y) throws IOException { drawImage (image, x, y, image.getWidth (), image.getHeight ()); }
python
def video_load_time(self): """ Returns aggregate video load time for all pages. """ load_times = self.get_load_times('video') return round(mean(load_times), self.decimal_precision)
python
def sgn(x): """ Return the sign of x. Return a positive integer if x > 0, 0 if x == 0, and a negative integer if x < 0. Raise ValueError if x is a NaN. This function is equivalent to cmp(x, 0), but more efficient. """ x = BigFloat._implicit_convert(x) if is_nan(x): raise Valu...
python
def resolve_sid(sid): """Get the PID to which the ``sid`` currently maps. Preconditions: - ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid(). """ return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did
java
public void appendType(final String text) { autoHover(); if (text == null) return; runWithRetries(() -> { elementImpl.locateElement().sendKeys(Keys.chord(Keys.COMMAND, Keys.ARROW_DOWN) + text); }); }
python
def force_map_handle_removal_win(self, base_path): """ONLY AVAILABLE ON WINDOWS On windows removing files is not allowed if anybody still has it opened. If this process is ourselves, and if the whole process uses this memory manager (as far as the parent framework is concerned) we can en...
python
def _build_merge_query(cls, merge_params, update_existing=False, lazy=False, relationship=None): """ Get a tuple of a CYPHER query and a params dict for the specified MERGE query. :param merge_params: The target node match parameters, each node must have a "create" key and optional "update". ...
java
private static void scanFile(File file, TreeMap<String, String> strings) throws IOException { Document doc = Jsoup.parse(file, "UTF-8"); // First, scan for elements with the 'apiman-i18n-key' attribute. These require translating. Elements elements = doc.select("*[apiman-i18n-key]"); fo...
java
@Trivial private final String getOwner() { ComponentMetaData cData = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData(); String name = cData == null ? null : cData.getJ2EEName().getApplication(); if (name == null) { ClassLoader threadContextClassL...
java
public PolyhedralSurface toPolyhedralSurface( List<com.google.android.gms.maps.model.Polygon> polygonList, boolean hasZ, boolean hasM) { PolyhedralSurface polyhedralSurface = new PolyhedralSurface(hasZ, hasM); for (com.google.android.gms.maps.model.Polygon mapPolygon : polygonL...
java
private List<String> readFile(File file) throws Exception { List<String> content = new ArrayList<>(100); try (BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String line; while ((line = is.readLine()) != null) { ...
java
public MethodState getSaved(int idx) { if (idx < 0) { throw new IllegalArgumentException(); } MethodState state = firstPointer; for (int i = 0; i < idx; i++) { state = state.getNext(); if (state == null) { throw new IllegalArgumentExcep...
java
public static byte[] decode(byte[] source) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode(source, 0, source.length, OBase64Utils.NO_OPTIONS); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessa...
python
def time_restarts(data_path): """ When called will create a file and measure its mtime on restarts """ path = os.path.join(data_path, 'last_restarted') if not os.path.isfile(path): with open(path, 'a'): os.utime(path, None) last_modified = os.stat(path).st_mtime with open(path,...
java
public static ComputerVisionClient authenticate(ServiceClientCredentials credentials, String endpoint) { return authenticate("https://{endpoint}/vision/v2.0/", credentials) .withEndpoint(endpoint); }
python
def add_event(self, name, data=None): ''' Add an event of type *name* to the queue. May raise a `ValueError` if the event type is mergeable and *data* is not None or if *name* is not a declared event type (in strict mode). ''' try: mergeable = self.event_types[name].mergeable except K...
java
@Override public TileMatrixSet createTileTableWithMetadata(String tableName, BoundingBox contentsBoundingBox, long contentsSrsId, BoundingBox tileMatrixSetBoundingBox, long tileMatrixSetSrsId) { return createTileTableWithMetadata(ContentsDataType.TILES, tableName, contentsBoundingBox, contentsSrsId, tileMa...
python
def _head(self, client_kwargs): """ Returns object HTTP header. Args: client_kwargs (dict): Client arguments. Returns: dict: HTTP header. """ return _handle_http_errors( self.client.request( 'HEAD', timeout=self._TIMEO...
python
def log(self, msg, *args): """Logs a message to stderr.""" if args: msg %= args click.echo(msg, file=sys.stderr)
java
public static Map<String, String> createCookiesMap(HttpServletRequest request) { Map<String, String> cookiesMap = new HashMap<String, String>(); Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : request.getCookies()) { ...
python
def delete_key(self, key_id): """ :: DELETE /:login/keys/:key :param key_id: identifier for an individual key record for the account :type key_id: :py:class:`basestring` Deletes an SSH key from the server identified by `key_id`. """ ...
python
def query_obj(self): """Returns the query object for this visualization""" d = super().query_obj() d['row_limit'] = self.form_data.get( 'row_limit', int(config.get('VIZ_ROW_LIMIT'))) numeric_columns = self.form_data.get('all_columns_x') if numeric_columns is None: ...
java
public com.squareup.okhttp.Call getCharactersCharacterIdPlanetsPlanetIdAsync(Integer characterId, Integer planetId, String datasource, String ifNoneMatch, String token, final ApiCallback<CharacterPlanetResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getCharacte...
java
public final EObject ruleTerminalRule() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token lv_fragment_2_0=null; Token otherlv_5=null; Token otherlv_7=null; Token otherlv_9=null; EObject lv_annotations_0_0 = null; AntlrData...
java
@BetaApi public final AggregatedListInstancesPagedResponse aggregatedListInstances(String project) { AggregatedListInstancesHttpRequest request = AggregatedListInstancesHttpRequest.newBuilder().setProject(project).build(); return aggregatedListInstances(request); }
java
void setSource(Reader reader) { if (reader == null) { throw new IllegalArgumentException("'reader' must not be null."); } br = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader( reader); }
java
public String addClass(String content, String selector, List<String> classNames, int amount) { Element body = parseContent(content); List<Element> elements = body.select(selector); if (amount >= 0) { // limit to the indicated amount elements = elements.subList(0, Math.min(amount, elements.size())); } ...
python
def _remove_source(self, source_name): """ Remember to call _update_parameters after this :param source_name: :return: """ assert source_name in self.sources, "Source %s is not part of the current model" % source_name source = self.sources.pop(source_name) ...
java
public static Builder newBuilder(String bucket, String name) { return newBuilder(BlobId.of(bucket, name)); }
python
def check_misc(text): """Avoid mixing metaphors. source: Garner's Modern American Usage source_url: http://bit.ly/1T4alrY """ err = "mixed_metaphors.misc.misc" msg = u"Mixed metaphor. Try '{}'." preferences = [ ["cream rises to the top", ["cream rises to the crop"]], ...
java
public final CharsetDecoder onUnmappableCharacter(CodingErrorAction newAction) { if (newAction == null) throw new IllegalArgumentException("Null action"); unmappableCharacterAction = newAction; implOnUnmappableCharacter(newAct...
python
def initiate_handshake(self, headers, timeout=None): """Initiate a handshake with the remote host. :param headers: A dictionary of headers to send. :returns: A future that resolves (with a value of None) when the handshake is complete. """ io_...
java
public static boolean isFunctionHeader( Object obj ) { if( obj instanceof String ){ String str = (String) obj; return str.startsWith( FUNCTION_PREFIX ) && RegexpUtils.getMatcher( FUNCTION_HEADER_PATTERN, true ).matches( str ); } return false; }