language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str)...
python
def _parse_arguments(): """Return a parser context result.""" parser = argparse.ArgumentParser(description="CMake AST Dumper") parser.add_argument("filename", nargs=1, metavar=("FILE"), help="read FILE") return parser.parse_args()
python
def _to_java_object_rdd(rdd): """ Return an JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return rdd.ctx._jvm.org.apache.spark...
python
def open_magnet(self): """Open magnet according to os.""" if sys.platform.startswith('linux'): subprocess.Popen(['xdg-open', self.magnet], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif sys.platform.startswith('win32'): os.startfile(self...
python
def _mean_prediction(self, mu, Y, h, t_z): """ Creates a h-step ahead mean prediction Parameters ---------- mu : np.ndarray The past predicted values Y : np.ndarray The past data h : int How many steps ahead for the prediction ...
python
def execute_policy(self, scaling_group, policy): """ Executes the specified policy for the scaling group. """ return self._manager.execute_policy(scaling_group=scaling_group, policy=policy)
python
def init(): """ Execute init tasks for all components (virtualenv, pip). """ print(yellow("# Setting up environment...\n", True)) virtualenv.init() virtualenv.update_requirements() print(green("\n# DONE.", True)) print(green("Type ") + green("activate", True) + green(" to enable your vir...
java
private boolean isCsvField(final String field, final ValidationContext<Object> validationContext) { return validationContext.getBeanMapping().getColumnMapping(field).isPresent(); }
python
def softmax_last_timestep_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "softmax_las...
python
def get_repositories_and_digests(self): """ Returns a map of images to their repositories and a map of media types to each digest it creates a map of images to digests, which is need to create the image->repository map and uses the same loop structure as media_types->digest, but the ima...
python
def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): """Lives in zipline.__init__ for doctests.""" if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
java
public String setExtensionHandlerClass(String handlerClassName) { String oldvalue = m_extensionHandlerClass; m_extensionHandlerClass = handlerClassName; return oldvalue; }
python
def unschedule(self, task_name): ''' Removes a task from scheduled jobs but it will not kill running tasks ''' for greenlet in self.waiting[task_name]: try: gevent.kill(greenlet) except BaseException: pass
python
def widths_in_range_mm( self, minwidth=EMIR_MINIMUM_SLITLET_WIDTH_MM, maxwidth=EMIR_MAXIMUM_SLITLET_WIDTH_MM ): """Return list of slitlets which width is within given range Parameters ---------- minwidth : float Minimum slit width (mm)...
java
protected String getStringParameter(String key, JobInstance ji, boolean pop) { // First try: parameter name with specific RM key. String res = ji.getPrms().get(getParameterRoot() + this.key + "." + key); if (res != null && pop) { ji.getPrms().remove(getParameterRoot() + t...
java
@Override public void createLogoutCookies(HttpServletRequest req, HttpServletResponse res) { createLogoutCookies(req, res, true); }
python
def get_obj(app_label, model_name, object_id): """ Function used to get a object :param app_label: A valid Django Model or a string with format: <app_label>.<model_name> :param model_name: Key into kwargs that contains de data: new_person :param object_id: :return: instance """ try: ...
java
private void instrument(CtClass proxy, final SchemaPropertyRef ref) throws Exception { final Schema schema = schemas.get(ref.getSchemaName()); checkNotNull(schema, "Schema not found for SchemaPropertyRef ["+ref+"]"); final String fieldName = ref.getFieldName(); // for help on javassist s...
python
def update_base_dict(self, yamlfile): """Update the values in baseline dictionary used to resolve names """ self.base_dict.update(**yaml.safe_load(open(yamlfile)))
java
public boolean getBooleanResult(final CharSequence equation) { final Element result = new ValueElement(getResult(equation), null, null); if (result.isBoolean()) { return result.getBoolean(); } else if (result.isInt()) { return result.getInt() > 0; } else if (resul...
java
@Nonnull public static WebSiteResourceWithCondition createForCSS (@Nonnull final ICSSPathProvider aPP, final boolean bRegular) { return createForCSS (aPP.getCSSItemPath (bRegular), aPP.getConditionalComment (), aPP.isBundlable (), aPP.ge...
python
def has_extensions(self, *exts): """Check if file has one of the extensions.""" file_ext = splitext(self.filename)[1] file_ext = file_ext.lower() for e in exts: if file_ext == e: return True return False
java
private byte[] readChunk() throws Exception { if (isEndOfInput()) { return EMPTY_BYTE_ARRAY; } try { // transfer to buffer byte[] tmp = new byte[chunkSize]; int readBytes = in.read(tmp); if (readBytes <= 0) { return nul...
python
def is_progressive(image): """ Check to see if an image is progressive. """ if not isinstance(image, Image.Image): # Can only check PIL images for progressive encoding. return False return ('progressive' in image.info) or ('progression' in image.info)
java
public static String resultSetToString(ResultSet resultSet) throws IllegalAccessException { StringBuilder resultSetStringBuilder = new StringBuilder(); List<String[]> resultSetStringArrayList = resultSetToStringArrayList(resultSet); List<Integer> maxColumnSizes = getMaxColumnSizes(resultSetStringArrayList);...
java
public synchronized void closeAll() { for (Window window : windows) { try { window.removeEventListener("close", this); window.destroy(); } catch (Throwable e) { } } windows.clear(); resetPositio...
java
public static ResourceKey key(Class<?> clazz, String id) { return new ResourceKey(clazz.getName(), id); }
python
def deletion_rate(Nref, Ndeletions, eps=numpy.spacing(1)): """Deletion rate Parameters ---------- Nref : int >=0 Number of entries in the reference. Ndeletions : int >=0 Number of deletions. eps : float eps. Default value numpy.spacing(1) Returns -----...
java
public static String getHeaderName(final String basename, final String filename) { final String base = basename.replaceAll("\\\\", "/"); final String file = filename.replaceAll("\\\\", "/"); if (!file.startsWith(base)) { throw new IllegalArgumentException("Error " + file + " does not start with " + ba...
python
def get_state_machine_m(self, two_factor_check=True): """ Get respective state machine model Get a reference of the state machine model the state model belongs to. As long as the root state model has no direct reference to its state machine model the state machine manager model is checked respe...
python
def keyPressEvent(self, event): """ Processes user input when they enter a key. :param event | <QKeyEvent> """ # emit the return pressed signal for this widget if event.key() in (Qt.Key_Return, Qt.Key_Enter) and \ event.modifiers() == Qt.C...
java
public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException { if (reachedEOF) { return -1; } // TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream... while (buffer.hasRemaining()) { in...
java
private int compareToLFU( CacheEntry other ) { int cmp = compareReadCount( other ); if ( cmp != 0 ) { return cmp; } cmp = compareTime( other ); if ( cmp != 0 ) { return cmp; } return compareOrder( other ); }
java
@Override public java.util.List<com.liferay.commerce.product.model.CPDefinitionOptionValueRel> getCPDefinitionOptionValueRelsByUuidAndCompanyId( String uuid, long companyId, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<com.liferay.commerce.product.model.CPDefinitionOptionValueRel> orderByCo...
python
def max_cation_insertion(self): """ Maximum number of cation A that can be inserted while maintaining charge-balance. No consideration is given to whether there (geometrically speaking) are Li sites to actually accommodate the extra Li. Returns: integer amount of cation. Dep...
java
public static RequestQueue newRequestQueue(HttpStack stack) { File cacheDir = new File("./", DEFAULT_CACHE_DIR); String userAgent = "volley/0"; if (stack == null) { stack = new HurlStack(); } Network network = new BasicNetwork(stack); RequestQueue q...
python
def _build_named_object_id(parameter): """ Builds a NamedObjectId. This is a bit more complex than it really should be. In Python (for convenience) we allow the user to simply address entries by their alias via the NAMESPACE/NAME convention. Yamcs is not aware of this convention so we decompose it i...
java
@Override public DescribeCommandsResult describeCommands(DescribeCommandsRequest request) { request = beforeClientExecution(request); return executeDescribeCommands(request); }
java
public com.google.api.ads.admanager.axis.v201811.SslManualOverride getSslManualOverride() { return sslManualOverride; }
java
@Override protected int compare(Integer o1, Integer o2) { if (o1 < o2) { return -1; } else if (o1 > o2) { return 1; } else { return 0; } }
python
def _add_rhoa(df, spacing): """a simple wrapper to compute K factors and add rhoa """ df['k'] = redaK.compute_K_analytical(df, spacing=spacing) df['rho_a'] = df['r'] * df['k'] if 'Zt' in df.columns: df['rho_a_complex'] = df['Zt'] * df['k'] return df
java
public int consume(Map<String, String> initialVars) { int result = 0; for (int i = 0; i < repeatNumber; i++) { result += super.consume(initialVars); } return result; }
java
public void build(String input, boolean treatWarningsAsError) throws IOException, ParseException { build(new InputSource(new StringReader(input)), treatWarningsAsError); }
python
async def begin_twophase(self, xid=None): """Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of TwoPhaseTransaction, which in addition to the methods provided by Transaction, also provides a TwoPhaseTransaction.prep...
java
public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final String xml, final Class<T> clazz) { return transformSamlObject(configBean, xml.getBytes(StandardCharsets.UTF_8), clazz); }
python
def batchcancel_order(self, order_ids: list): """ 批量撤销订单 :param order_id: :return: """ assert isinstance(order_ids, list) params = {'order-ids': order_ids} path = f'/v1/order/orders/batchcancel' def _wrapper(_func): @wraps(_func) ...
java
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "equivalent") public JAXBElement<RelationsType> createEquivalent(RelationsType value) { return new JAXBElement<RelationsType>(_Equivalent_QNAME, RelationsType.class, null, value); }
java
protected void fireConsumerConnectionEvent(IConsumer consumer, PipeConnectionEvent.EventType type, Map<String, Object> paramMap) { firePipeConnectionEvent(PipeConnectionEvent.build(this, type, consumer, paramMap)); }
java
@Override public int getLastOrderNumber(final NodeData parent) throws RepositoryException { if (!this.equals(versionDataManager) && isSystemDescendant(parent.getQPath())) { return versionDataManager.getLastOrderNumber(parent); } return super.getLastOrderNumber(parent); }
python
def makeImages(self): """Make spiral images in sectors and steps. Plain, reversed, sectorialized, negative sectorialized outline, outline reversed, lonely only nodes, only edges, both """ # make layout self.makeLayout() self.setAgraph() # ...
python
def connect_post_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): """ connect POST requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.con...
python
def apps_installation_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#remove-app-installation" api_path = "/api/v2/apps/installations/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
java
public static int getAxisFromStep( Compiler compiler, int stepOpCodePos) throws javax.xml.transform.TransformerException { int stepType = compiler.getOp(stepOpCodePos); switch (stepType) { case OpCodes.FROM_FOLLOWING : return Axis.FOLLOWING; case OpCodes.FROM_FOLLOWIN...
python
def cross_fade(self, seg1, seg2, duration): """Add a linear crossfade to the composition between two segments. :param seg1: First segment (fading out) :type seg1: :py:class:`radiotool.composer.Segment` :param seg2: Second segment (fading in) :type seg2: :py:class:`radiot...
python
def _generate(self, func): """Generate a population of :math:`\lambda` individuals. Notes ----- Individuals are of type *ind_init* from the current strategy. Parameters ---------- ind_init: A function object that is able to initialize an ...
java
@SuppressWarnings("unchecked") static <T> Monitor<T> wrap(TagList tags, Monitor<T> monitor) { Monitor<T> m; if (monitor instanceof CompositeMonitor<?>) { m = new CompositeMonitorWrapper<>(tags, (CompositeMonitor<T>) monitor); } else { m = MonitorWrapper.create(tags, monitor); } return ...
java
private Object getEvent(EventEnvelope eventEnvelope) { Object event = eventEnvelope.getEvent(); if (event instanceof Data) { event = eventService.nodeEngine.toObject(event); } return event; }
java
protected void parseImports() { List<Element> imports = rootElement.elements("import"); for (Element theImport : imports) { String importType = theImport.attribute("importType"); XMLImporter importer = this.getImporter(importType, theImport); if (importer == null) { addError("Could not...
java
private int addIndexedSplits( List<InputSplit> splits, int i, List<InputSplit> newSplits, Configuration cfg) throws IOException { final Path file = ((FileSplit)splits.get(i)).getPath(); final BGZFBlockIndex idx = new BGZFBlockIndex( file.getFileSystem(cfg).open(getIdxPath(file))); int splitsEnd = sp...
python
def _set_bulk_size(self, bulk_size): """ Set the bulk size :param bulk_size the bulker size """ self._bulk_size = bulk_size self.bulker.bulk_size = bulk_size
python
def setCompleteRedYellowGreenDefinition(self, tlsID, tls): """setCompleteRedYellowGreenDefinition(string, ) -> None . """ length = 1 + 4 + 1 + 4 + \ len(tls._subID) + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 4 # tls parameter itemNo = 1 + 1 + 1 + 1 + 1 for p in tls._phas...
java
public void set(int idx, char chr) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); buff[idx] = chr; }
java
private void appendEntry(Map.Entry<String, EDBObjectEntry> entry, StringBuilder builder) { if (builder.length() > 2) { builder.append(","); } builder.append(" \"").append(entry.getKey()).append("\""); builder.append(" : ").append(entry.getValue()); }
python
def parse_pr_numbers(git_log_lines): """ Parse PR numbers from commit messages. At GitHub those have the format: `here is the message (#1234)` being `1234` the PR number. """ prs = [] for line in git_log_lines: pr_number = parse_pr_number(line) if pr_number: ...
java
public void readChild(Element element, PrintWriter ps, int level, String name) { String nbTab = tabMaker(level); if (element instanceof Resource) { Resource resource = (Resource) element; writeBegin(ps, nbTab, name, level, element.getTypeAsString()); for (Resource.Entry entry : resource) { ...
java
public void changeWorkspaceInURL(String name, boolean changeHistory) { jcrURL.setWorkspace(name); if (changeHistory) { htmlHistory.newItem(jcrURL.toString(), false); } }
python
def get_dialect(self): """Returns a new dialect that implements the current selection""" parameters = {} for parameter in self.csv_params[2:]: pname, ptype, plabel, phelp = parameter widget = self._widget_from_p(pname, ptype) if ptype is types.StringType o...
python
def get_xy(artist): """ Attempts to get the x,y data for individual items subitems of the artist. Returns None if this is not possible. At present, this only supports Line2D's and basic collections. """ xy = None if hasattr(artist, 'get_offsets'): xy = artist.get_offsets().T el...
java
public Set<RGBColor> colours() { return stream().map(Pixel::toColor).collect(Collectors.toSet()); }
java
@Programmatic // for use by fixtures public Gmap3ToDoItem newToDo( final String description, final String userName) { final Gmap3ToDoItem toDoItem = repositoryService.instantiate(Gmap3ToDoItem.class); toDoItem.setDescription(description); toDoItem.setOwnedBy(userName...
python
def crypto_config_from_table_info(materials_provider, attribute_actions, table_info): """Build a crypto config from the provided values and table info. :returns: crypto config and updated kwargs :rtype: tuple(CryptoConfig, dict) """ ec_kwargs = table_info.encryption_context_values if table_info...
java
public static List<Path> getSubPathList(Path startDirectoryPath, int maxDepth) { return getSubPathList(startDirectoryPath, maxDepth, JMPredicate.getTrue()); }
java
@Override public void rename(String oldname, String newname) throws NamingException { rename(new CompositeName(oldname), new CompositeName(newname)); }
python
def log_player_roll(self, player, roll): """ :param player: catan.game.Player :param roll: integer or string, the sum of the dice """ self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else ''))
java
public Boolean setExecutionState( ExecutionEnvironment.ExecutionState executionState, String topologyName) { return awaitResult(delegate.setExecutionState(executionState, topologyName)); }
java
@Override public void grantLeadership(final UUID leaderSessionID) { log.info("{} was granted leadership with leaderSessionID={}", getRestBaseUrl(), leaderSessionID); leaderElectionService.confirmLeaderSessionID(leaderSessionID); }
python
def _insert(self, tree): """ Run an INSERT statement """ tablename = tree.table count = 0 kwargs = {} batch = self.connection.batch_write(tablename, **kwargs) with batch: for item in iter_insert_items(tree): batch.put(item) coun...
python
def deleteWebhook(self, hook_id): """Remove a webhook.""" path = '/'.join(['notification', 'webhook', hook_id]) return self.rachio.delete(path)
python
def cart2frac_all(coordinates, lattice_array): """Convert all cartesian coordinates to fractional.""" frac_coordinates = deepcopy(coordinates) for coord in range(frac_coordinates.shape[0]): frac_coordinates[coord] = fractional_from_cartesian( frac_coordinates[coord], lattice_array) r...
java
public Vector3d origin(Vector3d dest) { if ((properties & PROPERTY_AFFINE) != 0) return originAffine(dest); return originGeneric(dest); }
java
public boolean isOpen(String pn) { return opens.containsKey(pn) && opens.get(pn).isEmpty(); }
java
protected String nagiosCheckValue(String value, String composeRange) { List<String> simpleRange = Arrays.asList(composeRange.split(",")); double doubleValue = Double.parseDouble(value); if (composeRange.isEmpty()) { return "0"; } if (simpleRange.size() == 1) { if (composeRange.endsWith(",")) { if ...
python
def screenshot_to_file(self, filename, includes='subtitles'): """Mapped mpv screenshot_to_file command, see man mpv(1).""" self.command('screenshot_to_file', filename.encode(fs_enc), includes)
python
def browse_home_listpage_url(self, state=None, county=None, zipcode=None, street=None, **kwargs): """ Construct an url of home list page by...
java
public DatabaseAccountListReadOnlyKeysResultInner getReadOnlyKeys(String resourceGroupName, String accountName) { return getReadOnlyKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); }
python
def compute_cusum_ts(self, ts): """ Compute the Cumulative Sum at each point 't' of the time series. """ mean = np.mean(ts) cusums = np.zeros(len(ts)) cusum[0] = (ts[0] - mean) for i in np.arange(1, len(ts)): cusums[i] = cusums[i - 1] + (ts[i] - mean) assert(...
java
public Collection<Expression> expressions(ExpressionFilter filter) { return get(Expression.class, (filter != null) ? filter : new ExpressionFilter()); }
java
public static void writeEscapedAttrValue(Writer w, String value) throws IOException { int i = 0; int len = value.length(); do { int start = i; char c = '\u0000'; for (; i < len; ++i) { c = value.charAt(i); if (c == ...
python
def _example_from_array_spec(self, prop_spec): """Get an example from a property specification of an array. Args: prop_spec: property specification you want an example of. Returns: An example array. """ # if items is a list, then each item has its own sp...
java
public static InputArchive fromInputStream(InputStream stream) throws IOException { if (stream instanceof ObjectInput) { return new InputArchive((ObjectInput) stream); } else { return new InputArchive(new ObjectInputStream(stream)); } }
python
def plot(self, figsize=(12, 6), xscale='auto-gps', **kwargs): """Plot the data for this `Spectrogram` Parameters ---------- **kwargs all keyword arguments are passed along to underlying functions, see below for references Returns ------- ...
java
public List<Node> getConnectedNodes() { List<Node> nodes = new ArrayList<>(); for (Link l : links) { if (l.getElement() instanceof Node) { nodes.add((Node) l.getElement()); } } return nodes; }
python
def fromString( cls, strdata ): """ Restores a color set instance from the inputed string data. :param strdata | <str> """ if ( not strdata ): return None from xml.etree import ElementTree xelem = ElementTree.fromstr...
java
@SuppressWarnings("static-method") public Integer findIntValue(JvmAnnotationReference reference) { assert reference != null; for (final JvmAnnotationValue value : reference.getValues()) { if (value instanceof JvmIntAnnotationValue) { for (final Integer intValue : ((JvmIntAnnotationValue) value).getValues())...
java
public static void invertLower( double L[] , int m ) { for( int i = 0; i < m; i++ ) { double L_ii = L[ i*m + i ]; for( int j = 0; j < i; j++ ) { double val = 0; for( int k = j; k < i; k++ ) { val += L[ i*m + k] * L[ k*m + j ]; ...
java
public void rollbackImage(NamespaceInfo nsInfo) throws IOException { Preconditions.checkState(nsInfo.getLayoutVersion() != 0, "can't rollback with uninitialized layout version: %s", nsInfo.toColonSeparatedString()); LOG.info("Rolling back image " + this.getJournalId() + " with namespace ...
java
public static List<StartEndPair> scan(String input, String splitStart, String splitEnd, boolean useEscaping) { List<StartEndPair> result = new ArrayList<StartEndPair>(); int fromIndex = 0; while (true) { int exprStart = input.indexOf(splitStart, fromIndex); if (exprStart == -1) { break; } ...
python
def _partialParseTimeStd(self, s, sourceTime): """ test if giving C{s} matched CRE_TIMEHMS, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the bas...
python
def _delete(self, url): """Wrapper around request.delete() to use the API prefix. Returns a JSON response.""" req = self._session.delete(self._api_prefix + url) return self._action(req)
java
public static String getString(JSONValue value) { if (value == null) return null; if (!(value instanceof JSONString)) throw new JSONException(NOT_A_STRING); return ((JSONString)value).toString(); }