language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public ColumnModel getColumn(String colOrFieldName) { for (ColumnModel columnModel : columns) { if (columnModel.getColumnName() != null && columnModel.getColumnName().equalsIgnoreCase(colOrFieldName)) return columnModel; if (columnModel.getEntityField() != null && columnModel.getEntityField().equalsIgnoreCa...
python
def returnLabelState(peptide, labelDescriptor, labelSymbols=None, labelAminoacids=None): """Calculates the label state of a given peptide for the label setup described in labelDescriptor :param peptide: peptide which label state should be calcualted :param labelDescriptor: :class:`...
java
private String getMatchedFigureKeyword(String line) { for (String keyword : Config.FIGURE_KEYWORDS) { if (line.startsWith(keyword)) { return keyword; } } return null; }
python
def orifice_diameter(self): """The actual orifice diameter. We don't let the diameter extend beyond its row space. """ maxdrill = min(self.b_rows, self.d_orifice_max) return ut.floor_nearest(maxdrill, self.drill_bits)
java
public static <T extends Enum<T>> IAccessor<T> createAccessor(Class<T> clazz) { return new EnumNameAccessor<T>(clazz); }
java
public List<URL> getClasspathURLs() { scanSpec.performScan = false; try (ScanResult scanResult = scan()) { return scanResult.getClasspathURLs(); } }
java
private Point getFirstDifferent(Point init, boolean color, int dx, int dy) { int x = init.getX() + dx; int y = init.getY() + dy; while (isValid(x, y) && image.get(x, y) == color) { x += dx; y += dy; } x -= dx; y -= dy; while (isValid(x, y) && image.get(x, y) == color) { ...
java
public static void swap(short[] shortArray1, int array1Index, short[] shortArray2, int array2Index) { if(shortArray1[array1Index] != shortArray2[array2Index]) { short hold = shortArray1[array1Index]; shortArray1[array1Index] = shortArray2[array2Index]; shortArray2[array2Index...
java
private static String getTopLevelCauseMessage(Throwable t) { Throwable topLevelCause = t; while (topLevelCause.getCause() != null) { topLevelCause = topLevelCause.getCause(); } return topLevelCause.getMessage(); }
python
def ldap_server_host_basedn(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(ldap_server, "host") hostname_key = ET.SubElement(host, ...
python
def _setup_serializers(self): """ Auto set the return serializer based on Accept headers http://docs.webob.org/en/latest/reference.html#header-getters Intersection of requested types and supported types tells us if we can in fact respond in one of the request formats """...
java
public static MessageBody fromBinaryData(List<byte[]> binaryData) { if(binaryData == null || binaryData.size() == 0 || binaryData.size() > 1) { throw new IllegalArgumentException("Binary data is null or has more than one byte array in it."); } MessageBody body = new MessageBody(); ...
java
@Override @SuppressWarnings("unchecked") public List<Command> deserialize(final byte[] commands) { return kryo.get().readObject(new Input(commands), LinkedList.class); }
java
public static void sleep(int i) { try { Thread.sleep(i); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
python
def forward(self, data_batch, is_train=None): """Forward computation. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or ...
java
public CreateDeploymentGroupRequest withOnPremisesInstanceTagFilters(TagFilter... onPremisesInstanceTagFilters) { if (this.onPremisesInstanceTagFilters == null) { setOnPremisesInstanceTagFilters(new com.amazonaws.internal.SdkInternalList<TagFilter>(onPremisesInstanceTagFilters.length)); } ...
java
public void popBrowserHistory(int quanityToPop, boolean bCommandHandledByJava, String browserTitle) { if (this.getBrowserManager() != null) this.getBrowserManager().popBrowserHistory(quanityToPop, bCommandHandledByJava, this.getStatusText(Constants.INFORMATION)); // Let browser know about...
python
def _prepare_wsdl_objects(self): """ This sets the package identifier information. This may be a tracking number or a few different things as per the Fedex spec. """ self.SelectionDetails = self.client.factory.create('TrackSelectionDetail') # Default to Fedex se...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "multiCoverage") public JAXBElement<MultiSurfacePropertyType> createMultiCoverage(MultiSurfacePropertyType value) { return new JAXBElement<MultiSurfacePropertyType>(_MultiCoverage_QNAME, MultiSurfacePropertyType.class, null, value); }
java
@InterfaceAudience.Public public int getTotalRows() { try { updateIndex(); } catch (CouchbaseLiteException e) { Log.e(Log.TAG_VIEW, "Update index failed when getting the total rows", e); } return getCurrentTotalRows(); }
python
def volume(self, lmax=None): """ If the function is the real shape of an object, calculate the volume of the body. Usage ----- volume = x.volume([lmax]) Returns ------- volume : float The volume of the object. Parameters ...
python
def Pack(cls, obj, version): """Pack the given object using Ad Manager-specific logic. Args: obj: an object to be packed for SOAP using Ad Manager-specific logic, if applicable. version: the version of the current API, e.g. 'v201811' Returns: The given object packed with Ad Man...
python
def vsan_datastore_configured(name, datastore_name): ''' Configures the cluster's VSAN datastore WARNING: The VSAN datastore is created automatically after the first ESXi host is added to the cluster; the state assumes that the datastore exists and errors if it doesn't. ''' cluster_name, d...
java
public void insert(final AbstractInsnNode location, final InsnList insns) { if (insns.size == 0) { return; } size += insns.size; AbstractInsnNode ifirst = insns.first; AbstractInsnNode ilast = insns.last; AbstractInsnNode next = location.next; if (next...
python
def flush_if_ended(self): """Call 'flush' function if all files have been transformed.""" if self.ended and self.next and len(self.files) == self.transformed: future = asyncio.ensure_future(self.transformer.flush()) future.add_done_callback(lambda x: self.next.end_of_stream())
python
def _get_address_by_hash(self, block_hash): """Get mapped address by its hash. :param block_hash: :return: """ address_key = address_prefix + block_hash return self.db.get(address_key)
python
def _create_logger_(name): """Implementation detail, creates a logger.""" logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(levelname)s %(message)s')) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
java
private CellFormatResult getMergedCellValue(final Cell cell, final Locale locale) { final Sheet sheet = cell.getSheet(); final int size = sheet.getNumMergedRegions(); for(int i=0; i < size; i++) { final CellRangeAddress range = sheet.getMergedRegion(i); if(!range...
java
public static double calculateScore(FlatDataList errorList) { double DWdeltasquare=0; double DWetsquare=0; int n = errorList.size(); for(int i=0;i<n;++i) { Double error = errorList.getDouble(i); if(i>=1) { Double errorPrevious = errorList.getDoubl...
java
public void setSearchRoots(String[] searchRoots) { List<String> l = new ArrayList<String>(Arrays.asList(searchRoots)); m_parameters.setRoots(l); resetLastResult(); }
python
def get_system_series(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries w...
java
public static XElement parseXML(InputStream in) throws XMLStreamException { XMLInputFactory inf = XMLInputFactory.newInstance(); XMLStreamReader ir = inf.createXMLStreamReader(in); return parseXML(ir); }
python
def setup(self): """ Performs some checks. :return: None if successful, otherwise error message. :rtype: str """ result = super(BranchDirector, self).setup() if result is None: try: self.check_actors() except Exception, e: ...
python
def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original): """ Generate BigQuery JSON fields define :param name_case: name case type * DdlParse.NAME_CASE.original : Return to no convert * DdlParse.NAME_CASE.lower : Return to lower * DdlParse.NAM...
python
def throttle(self, key, amount=1, rate=None, capacity=None, exc_class=Throttled, **kwargs): """Consume an amount for a given key, or raise a Throttled exception.""" if not self.consume(key, amount, rate, capacity, **kwargs): raise exc_class("Request of %d unit for %s exceeds cap...
python
def filter(self, func, dropna=True, *args, **kwargs): # noqa """ Return a copy of a DataFrame excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- f : function Function to apply to each subframe. S...
python
def on_message(self, sender, content): """ Got a message from the client """ try: message = json.loads(content) except (ValueError, TypeError) as ex: logging.error("Not a valid JSON string: %s", ex) return try: # Check the...
java
void init(Preprocessor pp, LexerSource s) { this.listener = pp.getListener(); this.source = s; setTrigraphs(pp.getFeature(Feature.TRIGRAPHS), pp.getWarning(Warning.TRIGRAPHS)); }
java
public static final float parseField(byte[] bytes, int startPos, int length, char delimiter) { final int limitedLen = nextStringLength(bytes, startPos, length, delimiter); if (limitedLen > 0 && (Character.isWhitespace(bytes[startPos]) || Character.isWhitespace(bytes[startPos + limitedLen - 1]))) { throw new...
python
def transform_data(function, input_data): ''' a function to apply a function to each value in a nested dictionary :param function: callable function with a single input of any datatype :param input_data: dictionary or list with nested data to transform :return: dictionary or list with data transformed...
java
public void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst) throws IOException { fs.copyFromLocalFile(delSrc, overwrite, srcs, dst); }
python
def all_symbols(self): """Combination of :attr:`free_symbols` and :attr:`bound_symbols`""" if self._all_symbols is None: self._all_symbols = self.free_symbols | self.bound_symbols return self._all_symbols
java
public static <D extends Comparable> DateExpression<D> addWeeks(DateExpression<D> date, int weeks) { return Expressions.dateOperation(date.getType(), Ops.DateTimeOps.ADD_WEEKS, date, ConstantImpl.create(weeks)); }
python
def guess_filename(filename): """Guess filename""" if osp.isfile(filename): return filename if not filename.endswith('.py'): filename += '.py' for path in [getcwd_or_home()] + sys.path: fname = osp.join(path, filename) if osp.isfile(fname): return fna...
java
@Override public VType get(KType key) { if (Intrinsics.<KType> isEmpty(key)) { return hasEmptyKey ? Intrinsics.<VType> cast(values[mask + 1]) : Intrinsics.<VType> empty(); } else { final KType[] keys = Intrinsics.<KType[]> cast(this.keys); final int mask = this.mask; int slot = hashKey...
python
def get_rows(self, infer_nrows, skiprows=None): """ Read rows from self.f, skipping as specified. We distinguish buffer_rows (the first <= infer_nrows lines) from the rows returned to detect_colspecs because it's simpler to leave the other locations with skiprows logic a...
java
public Observable<ServiceResponse<RegistryPoliciesInner>> listPoliciesWithServiceResponseAsync(String resourceGroupName, String registryName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); ...
java
public void setCompName(String newCompName) { String oldCompName = compName; compName = newCompName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.OBJECT_CLASSIFICATION__COMP_NAME, oldCompName, compName)); }
java
public static void shuffle (Object[] values, int offset, int length) { shuffle(values, offset, length, _rnd); }
python
def main(): mesh = parse_gmsh('../commands.msh', '../boundary_lines.dat') # now create the CRTomo grid """ 1. Header 2. Nodes 3. Elements: Triangles, Boundary elements 4. Element ids for adjoining boundary elements """ str_header = get_header(mesh) str_nodes = get_nodes(mesh) ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "singleOperationRef") public JAXBElement<SingleOperationRefType> createSingleOperationRef(SingleOperationRefType value) { return new JAXBElement<SingleOperationRefType>(_SingleOperationRef_QNAME, SingleOperationRefType.class, null, value); ...
java
public VpnGatewayInner beginCreateOrUpdate(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).toBlocking().single().body(); }
python
def is_job_config(config): """ Check whether given dict of config is job config """ try: # Every job has name if config['config']['job']['name'] is not None: return True except KeyError: return False except TypeError: return False except IndexError...
python
def _remember_avatarness( self, character, graph, node, is_avatar=True, branch=None, turn=None, tick=None ): """Use this to record a change in avatarness. Should be called whenever a node that wasn't an avatar of a character now is, and whenever a node th...
java
protected static void jsonEscape3(StringBuilder sb, String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\b': sb.append("\\b"); break; case '\f': sb.append("...
python
def _merge_list_fastqs(files, out_file, config): """merge list of fastq files into one""" if not all(map(fastq.is_fastq, files)): raise ValueError("Not all of the files to merge are fastq files: %s " % (files)) assert all(map(utils.file_exists, files)), ("Not all of the files to merge " ...
python
def plugin_get(name): """ Return plugin class. @param name: the cms label. """ plugins = plugins_base_get() for plugin in plugins: if plugin.Meta.label == name: return plugin raise RuntimeError('CMS "%s" not known.' % name)
python
def load_models(context: mx.context.Context, max_input_len: Optional[int], beam_size: int, batch_size: int, model_folders: List[str], checkpoints: Optional[List[int]] = None, softmax_temperature: Optional[float] = None, ...
python
def make_openid_request(arq, keys, issuer, request_object_signing_alg, recv): """ Construct the JWT to be passed by value (the request parameter) or by reference (request_uri). The request will be signed :param arq: The Authorization request :param keys: Keys to use for signing/encrypting. A Ke...
java
public CrosstabBuilder addColumn(String title, String property, String className, boolean showTotal) { DJCrosstabColumn col = new CrosstabColumnBuilder() .setProperty(property,className) .setShowTotals(showTotal) .setTitle(title) .build(); addColumn(col); return this; }
java
public ApplicationReportIndexModel getApplicationReportIndexForProjectModel(ProjectModel projectModel) { GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(projectModel.getElement()); pipeline.in(ApplicationReportIndexModel.APPLICATION_REPORT_INDEX_TO_...
python
def validate(self): """ check that the block can be run """ if self.required and len(self.selected()) == 0: raise ReliureError("No component selected for block '%s'" % self.name)
java
@Override public void memcpyAsync(DataBuffer dstBuffer, Pointer srcPointer, long length, long dstOffset) { // if (dstBuffer.isConstant()) { // this.memoryHandler.memcpySpecial(dstBuffer, srcPointer, length, dstOffset); // } else this.memoryHandler.memcpyAsync...
python
def _get_last_node_for_prfx(self, node, key_prfx, seen_prfx): """ get last node for the given prefix, also update `seen_prfx` to track the path already traversed :param node: node in form of list, or BLANK_NODE :param key_prfx: prefix to look for :param seen_prfx: prefix already seen, u...
java
@Override public UpdateWebACLResult updateWebACL(UpdateWebACLRequest request) { request = beforeClientExecution(request); return executeUpdateWebACL(request); }
python
def close_editors(self, ): """Close all current editors :returns: None :rtype: None :raises: None """ for k in reversed(self._edit_widgets.keys()): self.commit_close_editor(k)
java
@Override public CompletableFuture<StreamSegmentRecord> getSegment(final long segmentId) { // extract epoch from segment id. // fetch epoch record for the said epoch // extract segment record from it. int epoch = StreamSegmentNameUtils.getEpoch(segmentId); return getEpochReco...
python
def canonical_uri_path(self): """ The canonicalized URI path from the request. """ result = getattr(self, "_canonical_uri_path", None) if result is None: result = self._canonical_uri_path = get_canonical_uri_path( self.uri_path) return result
java
public static Optional<SoyType> computeLowestCommonTypeArithmetic(SoyType t0, SoyType t1) { // If either of the types is an error type, return the error type if (t0.getKind() == Kind.ERROR || t1.getKind() == Kind.ERROR) { return Optional.of(ErrorType.getInstance()); } // If either of the types isn...
python
def _solve_loci_deprecated(c, locilen_sorted, seen_seqs, filtered, maxseq, n_cluster): """internal function to reduce loci complexity The function will read the all loci in a cluster of sequences and will determine if all loci are part of the same transcriptional unit(TU) by most-vote locus or by e...
java
public final String quoted_string() throws RecognitionException { String value = null; Token STRING_WITH_QUOTE_DOUBLE6=null; Token STRING_WITH_QUOTE7=null; try { // C:\\Project\\Obdalib\\obdalib-parent\\obdalib-core\\src\\main\\java\\it\\unibz\\inf\\obda\\gui\\swing\\utils...
python
def _query_string_params(flask_request): """ Constructs an APIGW equivalent query string dictionary Parameters ---------- flask_request request Request from Flask Returns dict (str: str) ------- Empty dict if no query params where in the ...
python
def qteInsertMode(self, pos: int, mode: str, value): """ Insert ``mode`` at position ``pos``. If ``pos`` is negative then this is equivalent to ``pos=0``. If it is larger than the number of modes in the list then it is appended as the last element. |Args| * ``p...
java
public void setValueFor(Object value, String name) { getMapHelper().setValueForIn(value, name, getCurrentValues()); }
java
protected String getCurrentValueForGroup(String group) { Object obj = groupValues.get(group); if (obj == null) { return ""; } return obj.toString(); }
python
def load_configuration(): """Load the configuration""" (belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files() log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ") config = {} if belbio_conf_fp: with open(belbio_conf_fp, "r") as f: config = ya...
java
protected void _generate(SarlCapacity capacity, IExtraLanguageGeneratorContext context) { final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(capacity); final PyAppendable appendable = createAppendable(jvmType, context); final List<? extends JvmTypeReference> superTypes; if (!capacity.getE...
python
def save_files(self, nodes): """ Saves user defined files using give nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool """ metrics = {"Opened": 0, "Cached": 0} for node in nodes: file = node.file ...
python
def convert_directory(dicom_directory, output_folder, compression=True, reorient=True): """ This function will order all dicom files by series and order them one by one :param compression: enable or disable gzip compression :param reorient: reorient the dicoms according to LAS orientation :param ou...
python
def run(self, stdscr): """ Initialize curses and refresh in a loop """ self.win = stdscr curses.curs_set(0) stdscr.timeout(0) curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3,...
java
public void removeNodesFromPool(String poolId, Collection<ComputeNode> computeNodes) throws BatchErrorException, IOException { removeNodesFromPool(poolId, computeNodes, null, null, null); }
java
public static String relativize(final String path, final File parentDir, final boolean removeInitialFileSep) { // Check sanity Validate.notNull(path, "path"); Validate.notNull(parentDir, "parentDir"); final String ...
java
public GrantsFilter withPage(int pageNumber, int amountPerPage) { parameters.put("page", pageNumber); parameters.put("per_page", amountPerPage); return this; }
java
public Object fetchValue() { try { return m_propertyMetadata.getGetMethod().invoke(m_proxyObject.getObject()); } catch (Exception e) { throw new RuntimeException(e); } }
python
def _prttex_summary_cnts(self, prt, cnts): """Write summary of level and depth counts for active GO Terms.""" # Count level(shortest path to root) and depth(longest path to root) # values for all unique GO Terms. prt.write("\n\n% LaTeX Table for GO counts at each level and depth in the G...
java
public boolean removeColumn(String name) { if (getColumnIndex(name) < 0) return false; this.mColumns.remove(getColumnIndex(name)); return true; }
python
def analyze(problem, Y, M=4, print_to_console=False, seed=None): """Performs the Fourier Amplitude Sensitivity Test (FAST) on model outputs. Returns a dictionary with keys 'S1' and 'ST', where each entry is a list of size D (the number of parameters) containing the indices in the same order as the...
java
public static int readRawVarint32( final int firstByte, final InputStream input) throws IOException { if ((firstByte & 0x80) == 0) { return firstByte; } int result = firstByte & 0x7f; int offset = 7; for (; offset < 32; offset += 7) { final int b = input.read(); if (b == -1)...
java
public void decryptAsync(final String data, final Callback callback) { if (callback == null) return; new Thread(new Runnable() { @Override public void run() { try { String decrypt = decrypt(data); if (decrypt == null) { ...
python
def Commit(self): """ Commits all currently open connections @author: Nick Verbeck @since: 9/12/2008 """ self.lock.acquire() try: for bucket in self.connections.values(): try: for conn in bucket: conn.lock() try: conn.commit() conn.release() except Exception:...
python
def smeft_toarray(wc_name, wc_dict): """Construct a numpy array with Wilson coefficient values from a dictionary of label-value pairs corresponding to the non-redundant elements.""" shape = smeftutil.C_keys_shape[wc_name] C = np.zeros(shape, dtype=complex) for k, v in wc_dict.items(): if...
java
public String get(final String name, final String defaultv) { final String value = get(name); return value == null ? defaultv : value; }
python
def unique_row(array, use_columns=None, selected_columns_only=False): '''Takes a numpy array and returns the array reduced to unique rows. If columns are defined only these columns are taken to define a unique row. The returned array can have all columns of the original array or only the columns defined in use_...
python
def convert_graphic_elements(self): """ This is a method for the odd special cases where <graphic> elements are standalone, or rather, not a part of a standard graphical element such as a figure or a table. This method should always be employed after the standard cases have alrea...
python
def wait_turns(self, turns, cb=None): """Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between Disables input for the duration. :param turns: number of turns to wait :param cb: function to call when done waiting, optional :return: ``None`...
python
def notes(path): """This function extracts any experimental notes from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :return: The rows of the data file that contain text notes inse...
python
def log_level(conf): """Get debug settings from arguments. --debug: turn on additional debug code/inspection (implies logging.DEBUG) --verbose: turn up logging output (logging.DEBUG) --quiet: turn down logging output (logging.WARNING) Default is logging.INFO """ if conf.debu...
java
private void get_class_system_resource() { // // Try to retrieve the class resource doc_url // if (Util._UseDb) { try { // // Call db server // final DbDatum res_value = db_class.get_property("doc_url"); ...
java
public <T> Action1<Delivery<View, T>> split(final Action2<View, T> onNext, @Nullable final Action2<View, Throwable> onError) { return new Action1<Delivery<View, T>>() { @Override public void call(Delivery<View, T> delivery) { delivery.split(onNext, onError); }...
java
public XcapResponseImpl handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException { int statusCode = httpResponse.getStatusLine().getStatusCode(); String eTag = null; String mimetype = null; if (statusCode == 200 || statusCode == 201) { // sucessful response org.apache.htt...