language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static int count(String str,String target){ int count=0; int index=0; while(true){ index=str.indexOf(target,index+1); if(index>0){ count++; }else{ break; } } return count; }
python
def simple_takeoff(self, alt=None): """ Take off and fly the vehicle to the specified altitude (in metres) and then wait for another command. .. note:: This function should only be used on Copter vehicles. The vehicle must be in GUIDED mode and armed before this is called...
python
def neighbors_iter(self): """Iterate over atoms and return its neighbors.""" for n, adj in self.graph.adj.items(): yield n, {n: attr["bond"] for n, attr in adj.items()}
java
public static <T> List<T> dotGetNullableList(final Map map, final String pathString, final Class<T> clazz) { return (List<T>) dotGetNullable(map, List.class, pathString); }
python
def instantiate_from_dict(self, values): """ Constructs an object given a dictionary containing an "ENGINE" key which contains the full module path to the class, and an "OPTIONS" key which contains a dictionary that will be passed in to the constructor as keyword args. ""...
python
def trim(self, len_): """Return a copy of the version, possibly with less tokens. Args: len_ (int): New version length. If >= current length, an unchanged copy of the version is returned. """ other = Version(None) other.tokens = self.tokens[:len_] ...
java
public void addValue(Date date) { String dateString = XmppDateTime.formatXEP0082Date(date); addValue(dateString); }
java
private static String getJobTemplateName(JobExecutionPlan jobExecutionPlan) { Optional<URI> jobTemplateUri = jobExecutionPlan.getJobSpec().getTemplateURI(); if (jobTemplateUri.isPresent()) { return Files.getNameWithoutExtension(new Path(jobTemplateUri.get()).getName()); } else { return null; ...
python
def get_file_from_iso_fp(self, outfp, **kwargs): # type: (BinaryIO, Any) -> None ''' A method to fetch a single file from the ISO and write it out to the file object. Parameters: outfp - The file object to write data to. blocksize - The number of bytes in each ...
java
public void getBytes(int index, byte[] destination, int destinationIndex, int length) { checkPositionIndexes(index, index + length, this.length); checkPositionIndexes(destinationIndex, destinationIndex + length, destination.length); index += offset; System.arraycopy(data, index, dest...
python
def generate_inverse_mapping(order): """Genereate a lambda entry -> PN order map. This function will generate the opposite of generate mapping. So where generate_mapping gives dict[key] = item this will give dict[item] = key. Valid PN orders are: {} Parameters ---------- order : string...
python
def demo(args): """ %prog demo Draw sample gene features to illustrate the various fates of duplicate genes - to be used in a book chapter. """ p = OptionParser(demo.__doc__) opts, args = p.parse_args(args) fig = plt.figure(1, (8, 5)) root = fig.add_axes([0, 0, 1, 1]) panel_sp...
python
def clientDisconnected(self, proto): """ Called when a client disconnects from the bus """ for rule_id in proto.matchRules: self.router.delMatch(rule_id) for busName in proto.busNames.keys(): self.dbus_ReleaseName(busName, proto.uniqueName) if pr...
python
def _make_nested_list(self, gen): """Makes nested list from generator for creating numpy.array""" res = [] for ele in gen: if ele is None: res.append(None) elif not is_string_like(ele) and is_generator_like(ele): # Nested generator ...
python
def run(self, invite_id, **kwargs): """ Sends a message about service rating to invitee """ self.l = self.get_logger(**kwargs) self.l.info("Looking up the invite") invite = Invite.objects.get(id=invite_id) msg_payload = self.compile_msg_payload(invite) result = se...
python
def flatten(iterable): """Flatten an arbitrarily deep list""" # likely not used iterable = iter(iterable) while True: try: item = next(iterable) except StopIteration: break if isinstance(item, six.string_types): yield item continue...
python
def get_nts_sorted(self, hdrgo_prt, hdrgos, hdrgo_sort): """Return a flat list of grouped and sorted GO terms.""" nts_flat = [] self.get_sorted_hdrgo2usrgos(hdrgos, nts_flat, hdrgo_prt, hdrgo_sort) return nts_flat
java
public void log(HttpRequest request, HttpResponse response, int responseLength) { try{ // ignore ignorables if (_ignorePathMap != null && _ignorePathMap.getMatch(request.getPath()) != null) return; /...
java
Rule PartsPlayOrder() { return OneOrMore(FirstOfS( CharRange('A', 'Z').label("ALPHA").suppressSubnodes(), DIGITS(), String("("), String(")"), suppr("."), suppr("\""),//found P:"AABBCCAA"... suppr(WSPS()) )).label(PartsPlayOrder); //return OneOrMore(AnyOf("1234567890().ABCDEFG...
java
public void importUserRole(String roleName) { if ((m_throwable != null) || (m_user == null)) { return; } try { CmsRole role = CmsRole.valueOfRoleName(roleName); try { // check if the organizational unit exists OpenCms.getOrgUni...
python
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except...
python
def _check_warnings(self, json_response): ''' Extract warnings from the response to make them accessible Args: json_response (dict): JSON response ''' self.warnings = None if json_response: self.warnings = json_response.get('warnings') ...
java
public void setIopsToStorageRatio(java.util.Collection<DoubleRange> iopsToStorageRatio) { if (iopsToStorageRatio == null) { this.iopsToStorageRatio = null; return; } this.iopsToStorageRatio = new com.amazonaws.internal.SdkInternalList<DoubleRange>(iopsToStorageRatio); ...
java
private Indent getIndent() { skipEmptyLines(); if (index < tokens.size()) { Token token = tokens.get(index); if (token.kind == Indent) { return new Indent(token.text, token.start); } return null; } return null; }
java
GMetric makeGMetricFromXml() throws IOException { String hostname = getHostName(); int port = getPort(); UDPAddressingMode addressingMode = getAddressingMode(); boolean v31x = getV31(); String spoof = getSpoof(); StringBuilder buf = new StringBuilder(); buf.append("GMetric host=").append(hostname); buf...
java
private Map<String,TableSchemaImpl> getTableDataFromGroups(DbUser user, List<String> logicalNames) throws Exception { Map<String,TableSchemaImpl> nameToTableMap = new HashMap<String,TableSchemaImpl>(); if( null == user ) { throw new Exception("No user supplied"); } if( null != logicalNames && 0 == logical...
java
protected void releaseTriggersCron(T jedis) throws JobPersistenceException { // has it been more than 10 minutes since we last released orphaned triggers // or is this the first check upon initialization if(isTriggerLockTimeoutExceeded(jedis) || !isActiveInstance(schedulerInstanceId, jedis)){ ...
java
@SuppressWarnings("unchecked") public AsyncProcessFunction<Object, TBase<?, ?>, Object> asyncFunc() { return (AsyncProcessFunction<Object, TBase<?, ?>, Object>) func; }
java
private void addGetParcelClass(TypeSpec.Builder classBuilder) { MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("getParcelerClass") .addModifiers(Modifier.PRIVATE) .returns(Class.class) .addParameter(Object.class, "object") .beginC...
python
def search_with_additional_term_string(self, filterstr): """ Returns a new search object with filterstr and-ed to the original filter string. The caller is responsible for passing in a properly escaped string. """ filterstr = u'(&%s%s)' % (self.filterstr, filterstr) ...
java
public void cancel() { final OnCancelListener listener; synchronized (this) { if (mIsCanceled) { return; } mIsCanceled = true; mCancelInProgress = true; listener = mOnCancelListener; } try { if (list...
python
def setRecords(self, records): """ Manually sets the list of records that will be displayed in this tree. This is a shortcut method to creating a RecordSet with a list of records and assigning it to the tree. :param records | [<orb.Table>, ..] ...
python
async def get_local_version(self): """Get the local installed version.""" self._version_data["source"] = "Local" try: from homeassistant.const import __version__ as localversion self._version = localversion _LOGGER.debug("Version: %s", self.version) ...
java
public static boolean argEquals(LCharToLongFuncDelta the, Object that) { return Null.<LCharToLongFuncDelta> equals(the, that, (one, two) -> { if (one.getClass() != two.getClass()) { return false; } LCharToLongFuncDelta other = (LCharToLongFuncDelta) two; return LBiObjLongTriple.argEquals(one.functio...
java
private static boolean meetsThresholdRequirement(long timeTaken) { final P6LogLoadableOptions opts = P6LogOptions.getActiveInstance(); long executionThreshold = null != opts ? opts.getExecutionThreshold() : 0; return executionThreshold <= 0 || TimeUnit.NANOSECONDS.toMillis(timeTaken) > executio...
java
@Deprecated public UpdateInventoryRequest newUpdateInventoryRequest(String orgToken, UpdateType updateType, String requesterEmail, Strin...
python
def error(code, message, template): """A generic error handler""" if json_requested(): return json_error(code, message) else: return render_template(template, message=message), code
java
private SimpleMatrix translateToOrigin( int x0 , int y0 ) { SimpleMatrix T = SimpleMatrix.identity(3); T.set(0, 2, -x0); T.set(1, 2, -y0); return T; }
java
@Pure public static String shortBasename(File filename) { if (filename == null) { return null; } final String largeBasename = filename.getName(); final int idx = largeBasename.indexOf(getFileExtensionCharacter()); if (idx < 0) { return largeBasename; } return largeBasename.substring(0, idx); }
java
public static List<AuditDto> transformToDto(List<Audit> audits) { if (audits == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<AuditDto> result = new ArrayList<AuditDto>(); for (Audit ...
java
@Override public XMLStreamReader2 createXMLStreamReader(File f) throws XMLStreamException { /* true for auto-close, since caller has no access to the underlying * input stream created from the File */ return createSR(f, false, true); }
java
private void readOpBits(ImageInputStream pStream, boolean hasRegion) throws IOException { // Get rowBytes int rowBytesRaw = pStream.readUnsignedShort(); int rowBytes = rowBytesRaw & 0x7FFF; boolean isPixMap = (rowBytesRaw & 0x8000) > 0; if (DEBUG) { System.out.print(h...
java
public ListDeploymentInstancesRequest withInstanceTypeFilter(String... instanceTypeFilter) { if (this.instanceTypeFilter == null) { setInstanceTypeFilter(new com.amazonaws.internal.SdkInternalList<String>(instanceTypeFilter.length)); } for (String ele : instanceTypeFilter) { ...
java
public double angle(Vector4dc v) { double cos = angleCos(v); // This is because sometimes cos goes above 1 or below -1 because of lost precision cos = cos < 1 ? cos : 1; cos = cos > -1 ? cos : -1; return Math.acos(cos); }
java
@Override public Request<DeleteTransitGatewayRouteTableRequest> getDryRunRequest() { Request<DeleteTransitGatewayRouteTableRequest> request = new DeleteTransitGatewayRouteTableRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def is_present(conf, atom): ''' Tell if a given package or DEPEND atom is present in the configuration files tree. Warning: This only works if the configuration files tree is in the correct format (the one enforced by enforce_nice_config) CLI Example: .. code-block:: bash salt '*'...
python
def get_splits(self, assets, dt): """ Returns any splits for the given sids and the given dt. Parameters ---------- assets : container Assets for which we want splits. dt : pd.Timestamp The date for which we are checking for splits. Note: this is ...
python
def default(self, obj): """ Encodes unknown object types (we use it to make extended types) """ if isinstance(obj, datetime.datetime): # Serialize date-time objects. Make sure they're naive. if obj.tzinfo is not None: raise TypeError('Cannot encode...
python
def resource_collection_response(cls, offset=0, limit=20): """ This method is deprecated for version 1.1.0. Please use get_collection """ request_args = {'page[offset]': offset, 'page[limit]': limit} return cls.get_collection(request_args)
java
void process(Operation operation) throws DataCorruptionException { // Add entry to MemoryTransactionLog and ReadIndex/Cache. This callback is invoked from the OperationProcessor, // which always acks items in order of Sequence Number - so the entries should be ordered (but always check). if (ope...
java
protected JSONObject elementToJson(CmsContainerElementBean element, Set<String> excludeSettings) { JSONObject data = null; try { data = new JSONObject(); data.put(FavListProp.ELEMENT.name().toLowerCase(), element.getId().toString()); if (element.getFormatterId() != n...
python
def get_one(self, key): """ method finds single record base on the given primary key and returns it to the caller""" query = build_db_query(self.primary_key, key) collection = self.ds.connection(self.collection_name) document = collection.find_one(query) if document is None: ...
python
def sequence(start, stop, step=None): """ Generate a sequence of integers from `start` to `stop`, incrementing by `step`. If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`, otherwise -1. >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2')) >>> df1.select(seq...
python
def _set_mldPIM(self, v, load=False): """ Setter method for mldPIM, mapped from YANG variable /interface_vlan/vlan/ipv6/mldPIM (container) If this variable is read-only (config: false) in the source YANG file, then _set_mldPIM is considered as a private method. Backends looking to populate this vari...
java
@Override public int getFileCrc(Path f) throws IOException { File p2f = pathToFile(f); DataChecksum checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, 1); byte[] buf = new byte[1024]; DataInputStream streamIn = new DataInputStream(new BufferedInputStream( new FileInputStream(...
python
def create_package_file(root, master_package, subroot, py_files, opts, subs): """Build the text of the file and write the file.""" text = format_heading(1, '%s' % makename(master_package, subroot)) if opts.modulefirst: text += format_directive(subroot, master_package) text += '\n' # bu...
java
public static byte[] unWrap(Byte... values) { if (null == values) { return null; } final int length = values.length; if (0 == length) { return new byte[0]; } final byte[] array = new byte[length]; for (int i = 0; i < length; i++) { array[i] = values[i].byteValue(); } return arra...
python
def init(**kwargs): """Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database. """ # TODO: Iterate through all engines in name set. database = kwargs.pop('database'...
python
def pufunc(func): """ Called by pfunc to convert NumPy ufuncs to deterministic factories. """ def dtrm_generator(*args): if len(args) != func.nin: raise ValueError('invalid number of arguments') name = func.__name__ + '(' + '_'.join( [str(arg) for arg in list(args...
python
def layer_keyword(self, keyword, value): """Get a layer according to a keyword and its value. :param keyword: The keyword to check. :type keyword: basestring :param value: The value to check for the specific keyword. :type value: basestring :return: The QGIS layer. ...
java
public void getImageAttributes(Map<String, String> attributes, I_CmsSimpleCallback<Map<String, String>> callback) { if (getGalleryMode() == GalleryMode.editor) { m_imageEditorFormatsTab.getImageAttributes(attributes); m_imageAdvancedTab.getImageAttributes(attributes, callback); ...
java
public static Throwable getChainedException(Throwable th) { java.lang.reflect.Method[] methods = th.getClass().getMethods(); // Need to keep looking if we find a valid method but it returns null. For some // throwables, like ResourceException, getLinkedException will be null but // getC...
python
def render_layout(self, app, path, alias=None): """Write to javascript.""" self.assign_routes(app) return ReactComponent( self.layout, self.src_file, self.component_id, props=self.build_props(), static_path=path, alias=alias...
java
private XML checksGlobalExistence(Class<?> aClass){ if(!classExists(aClass)) Error.xmlClassInexistent(this.xmlPath,aClass); if(findXmlClass(aClass).global==null) Error.xmlGlobalInexistent(aClass); return this; }
java
public static Vector3dfx convert(Tuple3D<?> tuple) { if (tuple instanceof Vector3dfx) { return (Vector3dfx) tuple; } return new Vector3dfx(tuple.getX(), tuple.getY(), tuple.getZ()); }
python
def generate_harvester_config(self, catalogs=None, harvest='valid', report=None, export_path=None): """Genera un archivo de configuración del harvester a partir de un reporte, o de un conjunto de catálogos y un criterio de cosecha (`harvest`). Args: ...
java
public @NotNull <T> List<T> findAll(@NotNull Class<T> cl, @NotNull SqlQuery query) { return executeQuery(resultProcessorForClass(cl), query); }
python
def _reset_internal(self): """ Sets initial pose of arm and grippers. """ super()._reset_internal() self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos if self.has_gripper: self.sim.data.qpos[ self._ref_joint_gripper_...
python
def tail(self, n): """Returns the last n rows. Args: n: Integer containing the number of rows to return. Returns: DataManager containing the last n rows of the original DataManager. """ # See head for an explanation of the transposed behavior if ...
java
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { if ((iChangeType == DBConstants.AFTER_ADD_TYPE) || (iChangeType == DBConstants.AFTER_UPDATE_TYPE) || (iChangeType == DBConstants.AFTER_DELETE_TYPE)) { if ((iChangeType == DBConst...
java
public void onEvent(EventIterator eventIterator) { // waiting for Event.PROPERTY_ADDED, Event.PROPERTY_REMOVED, // Event.PROPERTY_CHANGED Session session = null; try { while (eventIterator.hasNext()) { Event event = eventIterator.nextEvent(); St...
java
public int consume(IndexValueConsumer consumer) { int filledChunks = getFilledChunks(); int offset; for (int i = 0; i < filledChunks ; i++) { offset = i * chunkSize; int[] chunk = chunks[i]; if (chunk!=null) { for (int j = 0; j < chunkSize; j++...
python
def kmc(forward_in, database_name, min_occurrences=1, reverse_in='NA', k=31, cleanup=True, returncmd=False, tmpdir='tmp', **kwargs): """ Runs kmc to count kmers. :param forward_in: Forward input reads. Assumed to be fastq. :param database_name: Name for output kmc database. :param min_occurr...
python
def prepare_context(pipeline, context_in_string, context): """Prepare context for pipeline run. Args: pipeline: dict. Dictionary representing the pipeline. context_in_string: string. Argument string used to initialize context. context: pypyr.context.Context. Merge any new context genera...
java
@NotNull public OptionalDouble filterNot(@NotNull DoublePredicate predicate) { return filter(DoublePredicate.Util.negate(predicate)); }
python
def sid(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """Compute the Spectral Information Divergence (SID). .. image:: /pictures/SID.png **Range:** -π/2 ≤ SID < π/2, closer to 0 is better. **Notes:** The spectral information diverge...
python
def _init_idxs_strpat(self, usr_hdrs): """List of indexes whose values will be strings.""" strpat = self.strpat_hdrs.keys() self.idxs_strpat = [ Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in strpat]
java
public static ULocale getDefault() { synchronized (ULocale.class) { if (defaultULocale == null) { // When Java's default locale has extensions (such as ja-JP-u-ca-japanese), // Locale -> ULocale mapping requires BCP47 keyword mapping data that is currently ...
python
def utc_dt(dt): """Set UTC timezone on a datetime object. A naive datetime is assumed to be in UTC TZ. """ if not dt.tzinfo: return pytz.utc.localize(dt) return dt.astimezone(pytz.utc)
java
public static String convertByType(OrderType orderType) { return OrderType.BID.equals(orderType) ? IConstants.BUY : IConstants.SELL; }
java
public static Map<String, Object> parseMap(AbstractContext context, ParserWrapper parserWrapper, Map<String, Object> map) { switch (context.getSupportedFormat()) { case XML: throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support parse direct map parsing")); default: Jac...
python
def _refresh_editor_and_scrollbars(self): """ Refrehes editor content and scollbars. We generate a fake resize event to refresh scroll bar. We have the same problem as described here: http://www.qtcentre.org/threads/44803 and we apply the same solution (don't worry, the...
python
def markup_join(seq): """Concatenation that escapes if necessary and converts to unicode.""" buf = [] iterator = imap(soft_unicode, seq) for arg in iterator: buf.append(arg) if hasattr(arg, '__html__'): return Markup(u'').join(chain(buf, iterator)) return concat(buf)
java
private static double threePointsAngle(Point vertex, Point A, Point B) { double b = pointsDistance(vertex, A); double c = pointsDistance(A, B); double a = pointsDistance(B, vertex); return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b))); }
python
def _fields(self): """ Fields used for hashing, string representation, equality comparison """ return ( ('reference_name', self.reference_name,), ('annotation_name', self.annotation_name), ('annotation_version', self.annotation_version), ('...
python
def limit(self, limit): """ Set absolute limit on number of images to return, or set to None to return as many results as needed; default 50 posts. """ params = join_params(self.parameters, {"limit": limit}) return self.__class__(**params)
java
public TableRef greaterThan(String attributeName, ItemAttribute value){ filters.add(new Filter(StorageFilter.GREATERTHAN, attributeName, value, null)); return this; }
java
public void setAdapter(SlideShowAdapter adapter) { if (this.adapter != null) { this.adapter.unregisterDataSetObserver(adapterObserver); } this.adapter = adapter; this.adapter.registerDataSetObserver(adapterObserver); if (adapter != null) { PlayList pl = g...
python
def read(self, length, skip=False): """Consumes the first ``length`` bytes from the accumulator.""" if length > self.__size: raise IndexError( 'Cannot pop %d bytes, %d bytes in buffer queue' % (length, self.__size)) self.position += length self.__size -= lengt...
java
public static byte[] byteArrayWrappedOrCopy(CollectionNumber coll) { byte[] array = wrappedByteArray(coll); if (array != null) { return array; } return byteArrayCopyOf(coll); }
python
def run_instances(self, xml_bytes): """ Parse the reservations XML payload that is returned from an AWS RunInstances API call. @param xml_bytes: raw XML bytes with a C{RunInstancesResponse} root element. """ root = XML(xml_bytes) # Get the security gr...
java
public long gridDistance(Vector3ic v) { return Math.abs(v.x() - x()) + Math.abs(v.y() - y()) + Math.abs(v.z() - z()); }
java
public static void main(String[] args) { if (args.length != 2) { System.exit(-1); } String mem = args[0]; String sector = args[1]; try { getNumSector(mem, sector); } catch (Exception e) { throw new RuntimeException(e); } }
java
public String getRelation(int position) { if (position < length - 1) return original.getRelation(position); // Check that the request isn't for an invalid index else if (position >= length) throw new IllegalArgumentException("invalid relation: " + position); else ...
java
public T checked(boolean checked) { if (view instanceof CompoundButton) { CompoundButton cb = (CompoundButton) view; cb.setChecked(checked); } return self(); }
python
def get_tracking_id(self): """ Returns a dictionary of tracking-id key/value pairs. """ self.assert_open() tracking = self.handle[self.global_key +'tracking_id'].attrs.items() tracking = {key: _clean(value) for key, value in tracking} return tracking
java
private CmsUUID maybeReplaceFormatter(CmsUUID formatterId) { if (m_customReplacements != null) { CmsUUID replacement = m_customReplacements.get(formatterId); if (replacement != null) { return replacement; } } return formatterId; }
python
def parse_hotkey_combinations(hotkey): """ Parses a user-provided hotkey. Differently from `parse_hotkey`, instead of each step being a list of the different scan codes for each key, each step is a list of all possible combinations of those scan codes. """ def combine_step(step): # A sin...
java
private static void processSurrogateControlContent(HttpResponse response, boolean keepHeader) { if (!response.containsHeader(H_SURROGATE_CONTROL)) { return; } if (!keepHeader) { response.removeHeaders(H_SURROGATE_CONTROL); return; } MoveRespo...
java
public boolean remove(Object o) { int i = indexOf(o); if (i == -1) return false; else { removeAt(i); return true; } }