language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def plot_distance_landscape_projection(self, x_axis, y_axis, ax=None, *args, **kwargs): """ Plots the projection of distance landscape (if it was returned), onto the parameters specified :param x_axis: symbol to plot on x axis :param y_axis: symbol to plot on y axis :par...
java
public void marshall(DescribeAssociationRequest describeAssociationRequest, ProtocolMarshaller protocolMarshaller) { if (describeAssociationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(d...
python
def make_query(args, other=None, limit=None, strand=None, featuretype=None, extra=None, order_by=None, reverse=False, completely_within=False): """ Multi-purpose, bare-bones ORM function. This function composes queries given some commonly-used kwargs that can be passed to ...
python
async def route_msg(self, msg): """Given a message, route it either to the incoming queue, or to the future associated with its correlation_id. """ if msg.correlation_id in self._futures: self._set_reply(msg.correlation_id, msg) else: await self._push_inco...
java
public String getString(String propertyPath) throws PropertyException { Object o = getValue(propertyPath); return o.toString(); }
java
public static Geometry ringBuffer(Geometry geom, double bufferDistance, int numBuffer, String parameters, boolean doDifference) throws SQLException { if(geom==null){ return null; } if (geom.getNumGeometries() > 1) { throw new SQLException("This function suppor...
java
public void setHeaderFooter(HeaderFooter headerFooter, int displayAt) { this.mode = MODE_MULTIPLE; switch(displayAt) { case RtfHeaderFooter.DISPLAY_ALL_PAGES: headerAll = new RtfHeaderFooter(this.document, headerFooter, this.type, displayAt); break; c...
python
def call_somatic(tumor_name, normal_name): """Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag. Works from stdin and writes to stdout, finding positions of tumor and normal samples. Uses MuTect like somatic filter based on implementation in speedseq: https://github...
java
@Deprecated public RpcInternalContext setLocalAddress(String host, int port) { if (host == null) { return this; } if (port < 0 || port > 0xFFFF) { port = 0; } // 提前检查是否为空,防止createUnresolved抛出异常,损耗性能 this.localAddress = InetSocketAddress.createU...
python
def outcount(dset,fraction=0.1): '''gets outlier count and returns ``(list of proportion of outliers by timepoint,total percentage of outlier time points)''' polort = nl.auto_polort(dset) info = nl.dset_info(dset) o = nl.run(['3dToutcount','-fraction','-automask','-polort',polort,dset],stderr=None,quiet...
python
def get_parent_element(self): """Signatures and Audit elements share sub-elements, we need to know which to set attributes on""" return {AUDIT_REF_STATE: self.context.audit_record, SIGNATURE_REF_STATE: self.context.signature}[self.ref_state]
java
private File getKeyPath(final KeyType keyType) { return new File(Config.getInstance().getDataDirectorty() + File.separator + "keys" + File.separator + keyType.name().toLowerCase() + ".key"); }
java
private void visitFrame(final Frame f) { int i, t; int nTop = 0; int nLocal = 0; int nStack = 0; int[] locals = f.inputLocals; int[] stacks = f.inputStack; // computes the number of locals (ignores TOP types that are just after // a LONG or a DOUBLE, and a...
python
def cmdline(argv, flags): """A cmdopts wrapper that takes a list of flags and builds the corresponding cmdopts rules to match those flags.""" rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags]) return parse(argv, rules)
java
public void pauseJob (@Nonnull final TriggerKey aTriggerKey) { ValueEnforcer.notNull (aTriggerKey, "TriggerKey"); try { m_aScheduler.pauseTrigger (aTriggerKey); LOGGER.info ("Succesfully paused job with TriggerKey " + aTriggerKey.toString ()); } catch (final SchedulerException ex) ...
java
@DataRehashed public void dataRehashed(DataRehashedEvent<K, V> event) { ConsistentHash startHash = event.getConsistentHashAtStart(); ConsistentHash endHash = event.getConsistentHashAtEnd(); boolean trace = log.isTraceEnabled(); if (startHash != null && endHash != null) { if (trace) {...
java
public ApplicationGetOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; }
java
public synchronized void shutdown() { checkIsRunning(); try { beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION); } finally { discard(id); // Destroy all the dependent beans correctly creationalContext.rel...
java
public List<Example> actionCells(Example row) { List<Example> checkRow = new ArrayList<Example>(); checkRow.add(row.at(0, 1)); return checkRow; }
java
protected void record( final Block block, final Node blockNode ) throws Exception { if (block != null) { @SuppressWarnings( "unchecked" ) final List<Statement> statements = block.statements(); if ((statements != null) && !statements.isEmpty()) { ...
python
def cpu_halt_reasons(self): """Retrives the reasons that the CPU was halted. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLInkMOEInfo`` instances specifying the reasons for which the CPU was halted. This list may be empty in the case that the ...
python
def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.re...
python
def returns_cumulative(returns, geometric=True, expanding=False): """ return the cumulative return Parameters ---------- returns : DataFrame or Series geometric : bool, default is True If True, geometrically link returns expanding : bool default is False If True,...
python
def setup_launch_parser(self, parser): """Setup the given parser for the launch command :param parser: the argument parser to setup :type parser: :class:`argparse.ArgumentParser` :returns: None :rtype: None :raises: None """ parser.set_defaults(func=self....
java
public int setProperties(Map<String,Object> properties) { return this.setProperties(properties, DBConstants.DISPLAY, DBConstants.SCREEN_MOVE); }
java
public List<EventColumn> getUpdatedKeys() { List<EventColumn> columns = new ArrayList<EventColumn>(); for (EventColumn column : this.keys) { if (column.isUpdate()) { columns.add(column); } } return columns; }
java
public static void waitForDie(Thread thread) { boolean dead = false; do { try { thread.join(); dead = true; } catch (InterruptedException e) { // ignore } } while (!dead); }
python
def _get_lantern_format(self, df): """ Feature slice view browser expects data in the format of: {"metricValues": {"count": 12, "accuracy": 1.0}, "feature": "species:Iris-setosa"} {"metricValues": {"count": 11, "accuracy": 0.72}, "feature": "species:Iris-versicolor"} ... This f...
java
private Response serveOneOrAll(Map<String, Model> modelsMap) { // returns empty sets if !this.find_compatible_frames Pair<Map<String, Frame>, Map<String, Set<String>>> frames_info = fetchFrames(); Map<String, Frame> all_frames = frames_info.getFirst(); Map<String, Set<String>> all_frames_cols = frames_i...
java
@Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case SimpleExpressionsPackage.IF_CONDITION: { IfCondition ifCondition = (IfCondition)theEObject; T result = caseIfCondition(ifCondition); if (result == null) result = defaultCas...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ns_config_diff_responses result = (ns_config_diff_responses) service.get_payload_formatter().string_to_resource(ns_config_diff_responses.class, response); if(result.errorcode != 0) { if (result.er...
python
def pdf_preprocess(pdf, batch=False): """ Load pdfs from local filepath if not already b64 encoded """ if batch: return [pdf_preprocess(doc, batch=False) for doc in pdf] if os.path.isfile(pdf): # a filepath is provided, read and encode return b64encode(open(pdf, 'rb').read()...
python
def _validate(self): """ Validate the input data. """ if self.data_format is FormatType.PYTHON: self.data = self.raw_data elif self.data_format is FormatType.JSON: self._validate_json() elif self.data_format is FormatType.YAML: self._va...
java
public static String[] getMethodVariableNames(final Class<?> clazz, final String targetMethodName, final Class<?>[] types) { CtClass cc; CtMethod cm = null; try { if (null == CLASS_POOL.find(clazz.getName())) { CLASS_POOL.insertClassPath(new ClassClassPath(clazz)); ...
java
@Override public GetLifecyclePoliciesResult getLifecyclePolicies(GetLifecyclePoliciesRequest request) { request = beforeClientExecution(request); return executeGetLifecyclePolicies(request); }
python
def read_tpld_stats(self): """ :return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions. """ payloads_stats = OrderedDict() for tpld in self.tplds.values(): payloads_stats[tpld] = tpld.read_stats() return payloa...
java
public EClass getIfcFace() { if (ifcFaceEClass == null) { ifcFaceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers() .get(220); } return ifcFaceEClass; }
java
public ISynchronizationPoint<IOException> write(char c) { if (!(stream instanceof ICharacterStream.Writable.Buffered)) return write(new char[] { c }, 0, 1); ISynchronizationPoint<IOException> last = lastWrite; if (last.isUnblocked()) { lastWrite = ((ICharacterStream.Writable.Buffered)stream).writeAsync...
java
public void compose(StylesheetRoot sroot) throws TransformerException { super.compose(sroot); int length = getSortElemCount(); for (int i = 0; i < length; i++) { getSortElem(i).compose(sroot); } java.util.Vector vnames = sroot.getComposeState().getVariableNames(); if (null != m_...
python
def _remove_bound_conditions(agent, keep_criterion): """Removes bound conditions of agent such that keep_criterion is False. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate keep_criterion: function Evaluates removal_criterion(a) for each agent a in a ...
python
def process_affinity(affinity=None): """Get or set the CPU affinity set for the current process. This will affect all future threads spawned by this process. It is implementation-defined whether it will also affect previously-spawned threads. """ if affinity is not None: affinity = CPU...
java
static Integer convertToInt(SessionInterface session, Object a, int type) { int value; if (a instanceof Integer) { if (type == Types.SQL_INTEGER) { return (Integer) a; } value = ((Integer) a).intValue(); } else if (a instanceof Long) { ...
java
@Override protected FaxJobStatus getFaxJobStatusImpl(FaxJob faxJob) { //get fax job ID int faxJobIDInt=WindowsFaxClientSpiHelper.getFaxJobID(faxJob); //invoke fax action String faxJobStatusStr=this.winGetFaxJobStatus(this.faxServerName,faxJobIDInt); //get fax job status...
java
public void setContent(final String contentString, final String type) { final Content newContent = new Content(); newContent.setType(type == null ? Content.HTML : type); newContent.setValue(contentString); final ArrayList<Content> contents = new ArrayList<Content>(); contents.add...
java
@SuppressWarnings("unchecked") public List<Page> getPermittedChildren(Page page) { return gpUtil.getContentPermissionManager().getPermittedChildren(page, getRemoteUser()); }
java
public static <E extends HTMLElement> HtmlContentBuilder<E> htmlElement(String tag, Class<E> type) { return new HtmlContentBuilder<>(createElement(tag, type)); }
java
@Override public boolean containsKey(Object o) { @SuppressWarnings("unchecked") final K key = (K) o; return binarySearchInArray(key) >= 0 || overflowEntries.containsKey(key); }
java
public static void storeTracerInfo(ClientRequestContext requestContext) { // tracer信息放入request 发到服务端 SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan(); RpcInternalContext context = RpcInternalC...
python
def _request_helper(self, url, params, method): '''API request helper method''' try: if method == 'POST': return self._request_post_helper(url, params) elif method == 'GET': return self._request_get_helper(url, params) raise VultrError(...
python
def logpdf(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the log likelihood (log pdf) using it .. math: \\log p(y|\\lambda(f)) :param f: latent variables f :type f: Nx1 array :param y: data :type y: Nx1 array ...
python
def get_gateway_url(self, request): """ Routes a payment to Gateway, should return URL for redirection. """ params = { 'id': self.get_backend_setting('id'), 'description': self.get_order_description(self.payment, self.payment.order), 'amount': self.pay...
java
public static Method getSetterPropertyMethod(Class<?> type, String propertyName) { String sourceMethodName = "set" + BeanUtils.capitalizePropertyName(propertyName); Method sourceMethod = BeanUtils.getMethod(type, sourceMethodName); return sourceMethod; }
python
def feed_data(self, data: bytes) -> None: """ 代理 feed_data """ if self._parser is not None: self._parser.feed_data(data)
java
private void onWindowHit(Node node) { admittor.record(node.key); node.moveToTail(headWindow); }
python
def _write_result_handler(self, routine): """ Generates code for calling the stored routine in the wrapper method. """ self._write_line('ret = {}') self._write_execute_rows(routine) self._write_line('for row in rows:') num_of_dict = len(routine['columns']) ...
java
public FutureOperation subscribeTicker(final BitfinexTickerSymbol tickerSymbol) throws BitfinexClientException { final FutureOperation future = new FutureOperation(tickerSymbol); pendingSubscribes.registerFuture(future); final SubscribeTickerCommand command = new SubscribeTickerCommand(tickerSymbol); ...
java
private void readProjectProperties(Gantt gantt) { Gantt.File file = gantt.getFile(); ProjectProperties props = m_projectFile.getProjectProperties(); props.setLastSaved(file.getSaved()); props.setCreationDate(file.getCreated()); props.setName(file.getName()); }
java
public static Matrix fromCSV(String csv) { StringTokenizer lines = new StringTokenizer(csv, "\n"); Matrix result = DenseMatrix.zero(10, 10); int rows = 0; int columns = 0; while (lines.hasMoreTokens()) { if (result.rows() == rows) { result = result.co...
python
def reply_to(self) -> Optional[Sequence[AddressHeader]]: """The ``Reply-To`` header.""" try: return cast(Sequence[AddressHeader], self[b'reply-to']) except KeyError: return None
java
public static void main(String... args) { CommandLineRunner runner = new CommandLineRunner(); try { runner.run(args); } catch (Exception t) { System.err.println(t.getMessage()); System.err.println("Try '--help' for more information."); t.printSta...
python
def get_namespace_by_preorder( self, preorder_hash ): """ Given a namespace preorder hash, get the associated namespace reveal or ready (it may be expired). """ cur = self.db.cursor() return namedb_get_namespace_by_preorder_hash( cur, preorder_hash )
java
public R uploadAndFinish(InputStream in) throws X, DbxException, IOException { return start().uploadAndFinish(in); }
python
def peek(self, offset=0): """ Looking forward in the input text without actually stepping the current position. returns None if the current position is at the end of the input. """ pos = self.pos + offset if pos >= self.end: return None return self.text[pos]
java
public static int getDataType(String content) { String text = content.trim(); if(text.length() < 1) { return 9; } int i = 0; int d = 0; int e = 0; char c = text.charAt(0); int length = text.length(); if(c == '+' || c == '-') { ...
java
private void updateRequiredOptions(Option opt) throws ParseException { // if the option is a required option remove the option from // the requiredOptions list if (opt.isRequired()) { getRequiredOptions().remove(opt.getKey()); } // if the option is in an ...
java
public RandomVariableInterface barrier(RandomVariableInterface trigger, RandomVariableInterface valueIfTriggerNonNegative, RandomVariableInterface valueIfTriggerNegative) { // Set time of this random variable to maximum of time with respect to which measurability is known. double newTime = Math.max(time, trigger.ge...
java
public static HtmlTree SCRIPT() { HtmlTree htmltree = new HtmlTree(HtmlTag.SCRIPT); htmltree.addAttr(HtmlAttr.TYPE, "text/javascript"); return htmltree; }
python
def explain_prediction_df(estimator, doc, **kwargs): # type: (...) -> pd.DataFrame """ Explain prediction and export explanation to ``pandas.DataFrame`` All keyword arguments are passed to :func:`eli5.explain_prediction`. Weights of all features are exported by default. """ kwargs = _set_default...
python
def onStart(self): """ Override onStart method for npyscreen """ curses.mousemask(0) self.paths.host_config() version = Version() # setup initial runtime stuff if self.first_time[0] and self.first_time[1] != 'exists': system = System() thr = Threa...
python
def add_to_space_size(self, addition_bytes): # type: (int) -> None ''' A method to add bytes to the space size tracked by this Volume Descriptor. Parameters: addition_bytes - The number of bytes to add to the space size. Returns: Nothing. ''' ...
java
@Override public void put(String id, Session session) throws Exception { if (id == null || session == null) { throw new IllegalArgumentException("Put key=" + id + " session=" + (session == null ? "null" : session.getId())); } try (Lock ignored = session.lock()) { if ...
java
void addRuleRootNodes(List<RBBINode> dest, RBBINode node) { if (node == null) { return; } if (node.fRuleRoot) { dest.add(node); // Note: rules cannot nest. If we found a rule start node, // no child node can also be a sta...
java
public boolean exists(String path) { if (path == null) { return false; } for (SubdocOperationResult<OPERATION> result : resultList) { if (path.equals(result.path()) && !(result.value() instanceof Exception)) { return true; } } r...
java
@Nullable public Symbol getSymbolFromString(String symStr) { symStr = inferBinaryName(symStr); Name name = getName(symStr); Modules modules = Modules.instance(context); boolean modular = modules.getDefaultModule() != getSymtab().noModule; if (!modular) { return getSymbolFromString(getSymtab(...
java
private boolean isTrimEnabled() { String contentType = response.getContentType(); // If the contentType is the same string (by identity), return the previously determined value. // This assumes the same string instance is returned by the response when content type not changed between calls. if(contentType!=isTr...
python
def _get_storage_api(retry_params, account_id=None): """Returns storage_api instance for API methods. Args: retry_params: An instance of api_utils.RetryParams. If none, thread's default will be used. account_id: Internal-use only. Returns: A storage_api instance to handle urlfetch work to GCS. ...
java
@Override public Message decrypt(SignMessage signMessage) throws DecryptionException { ServiceableComponent<SignMessageDecryptionService> component = null; try { component = service.getServiceableComponent(); if (null == component) { throw new DecryptionException("SignMessageDecryptionServ...
python
def _init_humidity(self): """ Internal. Initialises the humidity sensor via RTIMU """ if not self._humidity_init: self._humidity_init = self._humidity.humidityInit() if not self._humidity_init: raise OSError('Humidity Init Failed')
java
private static String rewriteSoapAddress(SOAPAddressRewriteMetadata sarm, String origAddress, String newAddress, String uriScheme) { try { URL url = new URL(newAddress); String path = url.getPath(); String host = sarm.getWebServiceHost(); String port = getDotPortNumber...
java
@Override public <T> ByteBuffer serialize(final Serializer<T> serializer, final T value) throws IOException { try (final BytesSerialWriter writer = writeBytes()) { serializer.serialize(writer, value); return writer.toByteBuffer(); } }
python
def send_error_response(self, msgid, methodname, status_code, status_desc, error_insts=None): """Send a CIM-XML response message back to the WBEM server that indicates error.""" resp_xml = cim_xml.CIM( cim_xml.MESSAGE( cim_xml.SIMPLEEXPRSP...
java
public static void removeActionForm(ActionMapping mapping, HttpServletRequest request) { if (mapping.getAttribute() != null) { if ("request".equals(mapping.getScope())) request.removeAttribute(mapping.getAttribute()); else { HttpSession session = request.getSession(); session.removeAttribute(m...
java
@Transactional(readOnly = true) public Settings getSettings() { try { return (Settings) getEntity(StorageConstants.SETTINGS_ROOT); } catch (NotFoundException e) { // should never happen e.printStackTrace(); LOG.error("Could not read Settings node", e); return new Settings(); } }
java
public OutputStream extractData( final ClientHttpResponse response ) throws IOException { IoUtil.copy( response.getBody(), _output ); return _output; }
java
public BuildableType.Builder mergeFrom(BuildableType value) { BuildableType_Builder defaults = new BuildableType.Builder(); if (defaults._unsetProperties.contains(Property.TYPE) || !Objects.equals(value.type(), defaults.type())) { type(value.type()); } if (defaults._unsetProperties.contain...
java
public Matrix4f setPerspectiveLH(float fovy, float aspect, float zNear, float zFar, boolean zZeroToOne) { MemUtil.INSTANCE.zero(this); float h = (float) Math.tan(fovy * 0.5f); this._m00(1.0f / (h * aspect)); this._m11(1.0f / h); boolean farInf = zFar > 0 && Float.isInfinite(zFar)...
java
public void setPattern(final ConwayPattern pattern) { final boolean[][] gridData = pattern.getPattern(); int gridWidth = gridData[0].length; int gridHeight = gridData.length; int columnOffset = 0; int rowOffset = 0; if ( gridWidth > getNumberOfColumns() ) { ...
java
@SafeVarargs public static <D extends DestroyInterface> void cleanUp(D... destroys) { JMOptional.getOptional(destroys).map(Arrays::asList) .ifPresent(Destroyer::cleanUp); }
java
public void stopStoppableSession () { //471642 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "stopStoppableSession"); stoppableSessionStopped = true; if (TraceComponent.isAnyTracingEnabled() &&...
python
def load_json_or_yaml(string, is_path=False, file_type='json', exception=ScriptWorkerTaskException, message="Failed to load %(file_type)s: %(exc)s"): """Load json or yaml from a filehandle or string, and raise a custom exception on failure. Args: string (str)...
java
private static List<String> getFilesSafeForUninstall(AddOn addOn, Set<AddOn> installedAddOns) { if (addOn.getFiles() == null || addOn.getFiles().isEmpty()) { return Collections.emptyList(); } List<String> files = new ArrayList<>(addOn.getFiles()); installedAddOns.forEach(ins...
java
@Override public Request<CreateDhcpOptionsRequest> getDryRunRequest() { Request<CreateDhcpOptionsRequest> request = new CreateDhcpOptionsRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def reset_stats(self): """Reset accumulated profiler statistics.""" # Note: not using self.Profile, since pstats.Stats() fails then self.stats = pstats.Stats(Profile()) self.ncalls = 0 self.skipped = 0
python
def delete(context, sequence): """Delete jobs events from a given sequence""" uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence) return context.session.delete(uri)
python
def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20): """Filter junctions from many sj_out files and make panel. Parameters ---------- sj_outD : dict Dict whose keys are sample names and values are sj_out dataframes total_jxn_cov_cutoff : int If the unique read coverage of a ju...
python
def find_vlans( self, number, name, iexact, environment, net_type, network, ip_version, subnet, acl, pagination): """ Find vlans by all search parameters :param nu...
java
private void getLobLocator(CodeAssembler a, StorablePropertyInfo info) { if (!info.isLob()) { throw new IllegalArgumentException(); } a.invokeInterface(TypeDesc.forClass(RawSupport.class), "getLocator", TypeDesc.LONG, new TypeDesc[] {info.getStorageType...
java
private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray numberPickerTypedArray = getContext() .obtainStyl...
java
private List checkTransactionParticipationAndWaitForOtherTransactions(List list, MithraTransaction tx) { if (list == null) return null; List result = list; if (this.getTxParticipationMode(tx).mustParticipateInTxOnRead()) { for(int i=0;i<list.size();i++) ...
python
def update_ref(self, new_ref_info, repository_id, filter, project=None, project_id=None): """UpdateRef. [Preview API] Lock or Unlock a branch. :param :class:`<GitRefUpdate> <azure.devops.v5_1.git.models.GitRefUpdate>` new_ref_info: The ref update action (lock/unlock) to perform :param st...