language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def insert(self, point, number, axis): """Inserts number of rows/cols/tabs into selection at point on axis Parameters ---------- point: Integer \tAt this point the rows/cols are inserted or deleted number: Integer \tNumber of rows/cols to be inserted, negative nu...
python
def indent(self, node, dirty=True): """Indent an item. Does nothing if the target has subitems. Args: node (gkeepapi.node.ListItem): Item to indent. dirty (bool): Whether this node should be marked dirty. """ if node.subitems: return self._su...
java
boolean isLookupNeeded(Set<TraceeBackendProvider> classLoaderProviders) { return classLoaderProviders == null || !(classLoaderProviders instanceof EmptyBackendProviderSet) && classLoaderProviders.isEmpty(); }
java
public /*@ pure @*/ int cmpPow52(int p5, int p2) { if (p5 == 0) { int wordcount = p2 >> 5; int bitcount = p2 & 0x1f; int size = this.nWords + this.offset; if (size > wordcount + 1) { return 1; } else if (size < wordcount + 1) { ...
python
def reservoir_sample(stream, num_items, item_parser=lambda x: x): """ samples num_items from the stream keeping each with equal probability """ kept = [] for index, item in enumerate(stream): if index < num_items: kept.append(item_parser(item)) else: r = rando...
java
public ServiceFuture<SharedAccessSignatureAuthorizationRuleInner> getKeysForKeyNameAsync(String resourceGroupName, String resourceName, String keyName, final ServiceCallback<SharedAccessSignatureAuthorizationRuleInner> serviceCallback) { return ServiceFuture.fromResponse(getKeysForKeyNameWithServiceResponseAsyn...
java
@Override public DBParameterGroup createDBParameterGroup(CreateDBParameterGroupRequest request) { request = beforeClientExecution(request); return executeCreateDBParameterGroup(request); }
java
public static Object runMethod(Object object, String method, Object... args) throws JException { try { final Method m = object.getClass().getMethod(method); return m.invoke(object, args); } catch (Exception e) { throw new JException(e); } }
java
public void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { verify(key, ""); }
python
def _mergemap(map1, map2): """ Positions in map2 have an integer indicating the relative shift to the equivalent position in map1. E.g., the i'th position in map2 corresponds to the i + map2[i] position in map1. """ merged = array('i', [0] * len(map2)) for i, shift in enumerate(map2): ...
java
@Override public byte[] load(Value v) { long skip = 0; Key k = v._key; // Convert a chunk into a long-offset from the base file. if( k._kb[0] == Key.DVEC ) skip = water.fvec.NFSFileVec.chunkOffset(k); // The offset try { FileInputStream s = null; try { s = new FileInputStre...
python
def roty(t): """Rotation about the y-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
java
@Override public TaskRecord getTrigger(long taskId) throws Exception { String find = "SELECT t.OWNR,t.STATES,t.TRIG FROM Task t WHERE t.ID=:i"; final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "getTrigger", taskId, ...
java
private HandshakeResponse build400Response(WebSocketConnection conn) throws WebSocketException { if (log.isDebugEnabled()) { log.debug("build400Response: {}", conn); } // make up reply data... IoBuffer buf = IoBuffer.allocate(32); buf.setAutoExpand(true); buf....
python
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False): """ Override this so we can handle case of file not writable, as well as to make our _lastSavedState copy. """ self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\ str(set_ro)+', overwrit...
python
def get_url_rev_options(self, url): # type: (str) -> Tuple[str, RevOptions] """ Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). """ url, rev, user_pass = self.get_url_rev_and_auth(url) username, pa...
java
public static base_response change(nitro_service client, nsaptlicense resource) throws Exception { nsaptlicense updateresource = new nsaptlicense(); updateresource.id = resource.id; updateresource.sessionid = resource.sessionid; updateresource.bindtype = resource.bindtype; updateresource.countavailable = reso...
java
public EmbeddedResponse getEmbeddedSignUrl(String signatureId) throws HelloSignException { String url = BASE_URI + EMBEDDED_SIGN_URL_URI + "/" + signatureId; return new EmbeddedResponse(httpClient.withAuth(auth).post(url).asJson()); }
python
def param_logx_diagram(run_list, **kwargs): """Creates diagrams of a nested sampling run's evolution as it iterates towards higher likelihoods, expressed as a function of log X, where X(L) is the fraction of the prior volume with likelihood greater than some value L. For a more detailed description and...
python
def build_sample_smoother_problem_friedman82(N=200): """Sample problem from supersmoother publication.""" x = numpy.random.uniform(size=N) err = numpy.random.standard_normal(N) y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err return x, y
java
public static vpntrafficaction[] get(nitro_service service) throws Exception{ vpntrafficaction obj = new vpntrafficaction(); vpntrafficaction[] response = (vpntrafficaction[])obj.get_resources(service); return response; }
java
public static boolean contains(final boolean caseSensitive, final CharSequence text, final CharSequence fragment) { if (text == null) { throw new IllegalArgumentException("Text cannot be null"); } if (fragment == null) { throw new IllegalArgumentException("Fragment canno...
java
public EEnum getIfcPumpTypeEnum() { if (ifcPumpTypeEnumEEnum == null) { ifcPumpTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(879); } return ifcPumpTypeEnumEEnum; }
java
public void set(double x, double y) { assert Vector2D.isUnitVector(x, y) : AssertMessages.normalizedParameters(0, 1); if ((x != getX() || y != getY()) && !isBound()) { final Vector2dfx v = super.get(); v.set(x, y); fireValueChangedEvent(); } }
python
def in_array(self, event_property, value): """An in-array filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.in_array('path', '/event') >>> print(filtered) request(elapsed_ms).in(path, ["/", "e", "v", "e", "n", "t"]) >>>...
python
def setup_modules(self, args): """Performs setup tasks for each module in the module pool. Threads declared modules' setup() functions. Takes CLI arguments into account when replacing recipe parameters for each module. Args: args: Command line arguments that will be used to replace the parameter...
python
async def setup_watchdog(self, cb, timeout): """Trigger a reconnect after @timeout seconds of inactivity.""" self._watchdog_timeout = timeout self._watchdog_cb = cb self._watchdog_task = self.loop.create_task(self._watchdog(timeout))
python
def surface_of_section(orbit, plane_ix, interpolate=False): """ Generate and return a surface of section from the given orbit. .. warning:: This is an experimental function and the API may change. Parameters ---------- orbit : `~gala.dynamics.Orbit` plane_ix : int Integer ...
python
def get_config_map(self, name): """ Get a ConfigMap object from the server Raises exception on error :param name: str, name of configMap to get from the server :returns: ConfigMapResponse containing the ConfigMap with the requested name """ response = self.os.ge...
python
def wrap_context(func): """Wraps the provided servicer method by passing a wrapped context The context is wrapped using `lookout.sdk.grpc.log_fields.LogFieldsContext`. :param func: the servicer method to wrap_context :returns: the wrapped servicer method """ @functools.wraps(func) def wra...
java
@Override public RunScheduledInstancesResult runScheduledInstances(RunScheduledInstancesRequest request) { request = beforeClientExecution(request); return executeRunScheduledInstances(request); }
python
def get_tags(user): """Get all tags.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _T_COLUMNS) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name) return flask.jsonify({'t...
java
public static long sizeOf(File file) { if (!file.exists()) { String message = file + " does not exist"; throw new IllegalArgumentException(message); } if (file.isDirectory()) { return sizeOfDirectory(file); } else { return file.length(); } }
java
@OnClose public void onClose(Session session, CloseReason closeReason) { logger.info("WebSocket closed. : SessionId={}, Reason={}", session.getId(), closeReason.toString()); AmLogServerAdapter.getInstance().onClose(session); }
java
@Private @Override public void cancelled(final int pTaskletId) { assert taskletId == pTaskletId; this.cancelled.set(true); if (callbackHandler != null) { executor.execute(new Runnable() { @Override public void run() { callbackHandler.onFailure(new InterruptedException("V...
java
public static String timestampToString(long ts, int precision, TimeZone tz) { int p = (precision <= 3 && precision >= 0) ? precision : 3; String format = DEFAULT_DATETIME_FORMATS[p]; return dateFormat(ts, format, tz); }
java
public static void multRows(double[] diag, int offset, DMatrixSparseCSC A) { if( diag.length < A.numRows ) throw new IllegalArgumentException("Array is too small. "+diag.length+" < "+A.numCols); for (int i = 0; i < A.nz_length; i++) { A.nz_values[i] *= diag[A.nz_rows[i+offset]];...
java
private void doDeliverHintsToEndpoint(InetAddress endpoint) { // find the hints for the node using its token. UUID hostId = Gossiper.instance.getHostId(endpoint); logger.info("Started hinted handoff for host: {} with IP: {}", hostId, endpoint); final ByteBuffer hostIdBytes = ByteBuff...
python
def unsubscribe(self, client): """Unsubscribe a client from the channel.""" if client in self.clients: self.clients.remove(client) log("Unsubscribed client {} from channel {}".format(client, self.name))
java
int runCommands(DispatchCallback callback, String... cmds) { return runCommands(Arrays.asList(cmds), callback); }
python
def parse_intrans(path_dir): """ Parses boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs Args: path_dir: (str) dir containing the boltztrap.intrans file Returns: intrans (dict): a dictionary containing various inpu...
java
private <T extends Appendable> T _toPattern(T result, boolean escapeUnprintable) { if (pat == null) { return appendNewPattern(result, escapeUnprintable, true); } try { if (!escapeUnprintable) { result.append(pat); return result;...
java
public synchronized Object convertToDatetimeInterval(String s, DTIType type) { Object value; IntervalType intervalType = null; int dateTimeToken = -1; int errorCode = type.isDateTimeType() ? ErrorCode.X_22007 ...
java
public static final byte[] compress(byte[] data, int level) throws IOException { final Deflater deflater = new Deflater(level, true); deflater.setInput(data); deflater.finish(); final byte[] buffer = new byte[data.length + 128]; final int length = deflater.deflate(buffer); final byte[] compressed = ne...
python
def krylovMethod(self,tol=1e-8): """ We obtain ``pi`` by using the :func:``gmres`` solver for the system of linear equations. It searches in Krylov subspace for a vector with minimal residual. The result is stored in the class attribute ``pi``. Example ------- >>> P...
java
@Override public Enumeration getAllIds() { Set ids = this.coreCache.getCacheIds(); ValueSet idvs = new ValueSet(ids.iterator()); return idvs.elements(); }
java
private void build() { // nextRecurringDate are computed based on *proposed* items, and not missing items (= proposed - existing). So // we need to filter out the dates for which there is no item left otherwsie we may end up in creating too many notification dates // and in particular that could...
python
def transit_read_key(self, name, mount_point='transit'): """GET /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype: """ url = '/v1/{0}/keys/{1}'.format(mount_point, name) return self....
java
public float getWidthPoint() { if (getImage() != null) { return getImage().getScaledWidth(); } return font.getCalculatedBaseFont(true).getWidthPoint(getContent(), font.getCalculatedSize()) * getHorizontalScaling(); }
java
@Override protected Map<String, Object> initializeVariables(final Set<StringTextValue<?>> allSettings) { final Map<String, Object> variables = super.initializeVariables(allSettings); variables.put(COMMAND, getCommand(getSettings())); return variables; }
java
@Override public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery) { ResultSet rSet = (ResultSet) this.execute(cqlQuery, null); if (clazz == null) { // XXX if (isNative) return iterateAndReturnNative(rSet); retur...
python
def p_statement_draw3(p): """ statement : DRAW expr COMMA expr COMMA expr """ p[0] = make_sentence('DRAW3', make_typecast(TYPE.integer, p[2], p.lineno(3)), make_typecast(TYPE.integer, p[4], p.lineno(5)), make_typecast(TYPE.float_, p[...
python
def unicode(self, s, encoding=None): """ Convert a string to unicode using the given encoding, and return it. This function uses the underlying to_unicode attribute. Arguments: s: a basestring instance to convert to unicode. Unlike Python's built-in unicode() fu...
java
public String cleanCommand(String command) { if (command == null) return command; Map<String,Object> properties = Util.parseArgs(null, command); properties.remove(Params.APPLET); properties.remove("code"); properties.remove("jnlpjars"); properties.remove("jnlpextensions"); properties.remove(ScreenUtil...
java
public final void execute () throws InternetSCSIException { final ProtocolDataUnit protocolDataUnit = connection.receive(); if (!(protocolDataUnit.getBasicHeaderSegment().getParser() instanceof LogoutResponseParser)) { throw new InternetSCSIException("This PDU type (" + protocolDataUnit.getBasicHeader...
java
private String maybeAddTrailingSlash(String key) { if (!key.isEmpty() && !key.endsWith("/")) { return key + '/'; } else { return key; } }
java
public void scrollTo(int x, int y) { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth()); y = clamp(y, getHeight() - getPaddin...
java
public ArrayList<OvhSubnet> project_serviceName_network_private_networkId_subnet_GET(String serviceName, String networkId) throws IOException { String qPath = "/cloud/project/{serviceName}/network/private/{networkId}/subnet"; StringBuilder sb = path(qPath, serviceName, networkId); String resp = exec(qPath, "GET",...
java
@Override public String cookieValue(String name) { return CookieHelper.getCookieValue(name, request().cookies()); }
java
public final void infoDebug(final Throwable cause, final String message) { logDebug(Level.INFO, cause, message); }
python
def configure_plugin(app): # noqa: C901 """ This is a factory function that configures all the routes for flask given a particular library. """ @app.route( "/v1/api/client_has_addon/<hashed_client_id>/<addon_id>/", methods=["GET"] ) def client_has_addon(hashed_client_id, addon_id):...
java
@Override public void close() throws Exception { Throwable exception = null; try { blobStoreService.close(); } catch (Throwable t) { exception = t; } internalClose(); if (exception != null) { ExceptionUtils.rethrowException(exception, "Could not properly close the ZooKeeperHaServices."); } }
java
public String substitute(File file, Object... args) { try { ITemplate t = getTemplate(file, args, BasicRythm.INSTANCE); return t.render(); } finally { renderCleanUp(); } }
python
def train(cls, data, iterations=100, initialWeights=None, regParam=0.0, regType="l2", intercept=False, corrections=10, tolerance=1e-6, validateData=True, numClasses=2): """ Train a logistic regression model on the given data. :param data: The training data, an RDD of Lab...
java
private ComplexCondition getSleeper(final long identifier) throws InvalidIdentifierException { final ComplexCondition call = sleeperMap.get(identifier); if (null == call) { throw new InvalidIdentifierException(identifier); } return call; }
java
public static boolean containsAny(final String str, final String... set) { if (StringUtils.isEmpty(str) || deepEmpty(set)) { return false; } final CharSet chars = CharSet.getInstance(set); for (final char c : str.toCharArray()) { if (chars.contains(c)) { ...
java
public Matrix3d rotation(AxisAngle4f axisAngle) { return rotation(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z); }
java
public static boolean containsAny(String str, String searchChars) { if (searchChars == null) { return false; } return containsAny(str, searchChars.toCharArray()); }
python
def append_seeding_annotation(self, annotation: str, values: Set[str]) -> Seeding: """Add a seed induction method for single annotation's values. :param annotation: The annotation to filter by :param values: The values of the annotation to keep """ return self.seeding.append_ann...
java
private void readResourceCustomPropertyDefinitions(Resources gpResources) { CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1); field.setAlias("Phone"); for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition()) { // ...
python
def _process_batch(self, param, df_name): """Update selected dataframe after a completed batch Parameters ---------- df_name : str Selected dataframe name needs to be modified. """ if param.eval_metric is not None: metrics = dict(param.eval_metric....
java
public SDVariable confusionMatrix(String name, SDVariable labels, SDVariable pred, Integer numClasses) { validateInteger("confusionMatrix", "labels", labels); validateInteger("confusionMatrix", "prediction", pred); SDVariable result = f().confusionMatrix(labels, pred, numClasses); return...
python
def get_masked_cnv_manifest(tcga_id): """Get manifest for masked TCGA copy-number variation data. Params ------ tcga_id : str The TCGA project ID. download_file : str The path of the download file. Returns ------- `pandas.DataFrame` The manifest. ...
java
public ResourceDetails withOther(java.util.Map<String, String> other) { setOther(other); return this; }
java
public ServiceFuture<Void> moveAsync(String resourceGroupName, String workflowName, WorkflowInner move, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(moveWithServiceResponseAsync(resourceGroupName, workflowName, move), serviceCallback); }
python
def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE): """Maps a texture onto a surface, then projects to 2D and returns a layer. Args: texture (texture): the texture to project surface (surface): the surface to project onto angle (float): the projection angle in degrees...
java
public Content simpleTagOutput(Element element, List<? extends DocTree> simpleTags, String header) { CommentHelper ch = utils.getCommentHelper(element); ContentBuilder result = new ContentBuilder(); result.addContent(HtmlTree.DT(HtmlTree.SPAN(HtmlStyle.simpleTagLabel, new RawHtml(header)))); ...
java
public void marshall(UtilizationByTime utilizationByTime, ProtocolMarshaller protocolMarshaller) { if (utilizationByTime == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(utilizationByTime.getTimePer...
java
private boolean hidden(String className) { className = removeTemplate(className); ClassInfo ci = classnames.get(className); return ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className); }
java
public void updateVersion() { try { MessageDigest versionDigest = MessageDigest.getInstance("MD5"); for (Row row : SystemKeyspace.serializedSchema()) { if (invalidSchemaRow(row) || ignoredSchemaRow(row)) continue; ...
python
def infer_schema(environment, start_response, headers): """ Return the inferred schema of the requested stream. POST body should contain a JSON encoded version of: { stream: stream_name, namespace: namespace_name (optional) } """ stream = environment['json']['stream'] namespace = environment['...
java
@Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
protected boolean isInherited(ProgramElementDoc ped){ if(ped.isPrivate() || (ped.isPackagePrivate() && ! ped.containingPackage().equals(classdoc.containingPackage()))){ return false; } return true; }
python
def byaxis_out(self): """Object to index along output dimensions. This is only valid for non-trivial `out_shape`. Examples -------- Indexing with integers or slices: >>> domain = odl.IntervalProd(0, 1) >>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2...
java
public String getApiPath() { if (StringUtils.isBlank(path)) { return DEFAULT_PATH; } else { if (!path.endsWith("/")) { path += "/"; } return path; } }
java
private void checkCapacity() { if (memoryQueue.size() > maxMemoryLogSize) { // 超过阀值,需要批量刷盘 if (flushing.compareAndSet(false, true)) { // 这里可以采用new Thread, 因为这里只会同时new一个 new Thread(new Runnable() { @Override public vo...
python
def getattr_with_deprecated_properties(obj, item, deprecated_properties): """Helper method to use in the getattr method of a class with deprecated properties. :param obj: Instance of the Class containing the deprecated properties in question. :type obj: object :param item: Name of the attribute being r...
python
def impulse_deltav_plummerstream(v,y,b,w,GSigma,rs,tmin=None,tmax=None): """ NAME: impulse_deltav_plummerstream PURPOSE: calculate the delta velocity to due an encounter with a Plummer-softened stream in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the...
java
public static void negative(Double value) { if(!validation) return; Validate.notNull(value); if(value >= 0.0) throw new ParameterException(ErrorCode.NOTNEGATIVE); }
java
public Observable<Page<LabAccountInner>> listByResourceGroupAsync(final String resourceGroupName) { return listByResourceGroupWithServiceResponseAsync(resourceGroupName) .map(new Func1<ServiceResponse<Page<LabAccountInner>>, Page<LabAccountInner>>() { @Override public...
java
public int lookupIndex (Object entry) { if (entry == null) throw new IllegalArgumentException ("Can't lookup \"null\" in an Alphabet."); int ret = map.get(entry); if (ret <= 0 && !growthStopped) { numEntries++; ret = numEntries; map.put(entry, ...
java
public static boolean argEquals(LLogicalTernaryOpMemento the, Object that) { return Null.<LLogicalTernaryOpMemento> equals(the, that, (one, two) -> { if (one.getClass() != two.getClass()) { return false; } LLogicalTernaryOpMemento other = (LLogicalTernaryOpMemento) two; return LObjBoolPair.argEquals...
java
public void put(InputStream in, String remote, FileTransferProgress progress) throws SftpStatusException, SshException, TransferCancelledException { put(in, remote, progress, 0); }
python
def show_instance(name=None, instance_id=None, call=None, kwargs=None): ''' Show the details from EC2 concerning an AMI. Can be called as an action (which requires a name): .. code-block:: bash salt-cloud -a show_instance myinstance ...or as a function (which requires either a name or in...
java
public Mutations<S> getRange(int from, int to) { return new Mutations<>(alphabet, Arrays.copyOfRange(mutations, from, to)); }
python
def feeds(self): """List GitHub's timeline resources in Atom format. :returns: dictionary parsed to include URITemplates """ url = self._build_url('feeds') json = self._json(self._get(url), 200) del json['ETag'] del json['Last-Modified'] urls = [ ...
python
def evaluate_rule(self, rule, value, target): """Calculate the value.""" def evaluate(expr): if expr in LOGICAL_OPERATORS.values(): return expr rvalue = self.get_value_for_expr(expr, target) if rvalue is None: return False # ignore thi...
python
def _find_service_name(self): """ For cloud operations there is support for multiple pools of resources dedicated to logstash. The service name as a result follows the pattern logstash-{n} where n is some number. We can find it from the service marketplace. """ ...
java
@Override public List<Option> getCommandLineOptions() { List<Option> options = sizedArrayList(4); options.add(new Option(TAX_ID_SHORT, TAX_ID, true, TAX_ID_DESCRIPTION)); return options; }
python
def learn(self, steps=1, **kwargs): """ Train the model using the environment and the agent. Note that the model might be shared between multiple agents (which most probably are of the same type) at the same time. :param steps: The number of steps to train for. """ ...