language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def security_group_get(auth=None, **kwargs): ''' Get a single security group. This will create a default security group if one does not exist yet for a particular project id. filters A Python dictionary of filter conditions to push down CLI Example: .. code-block:: bash salt ...
python
def cmp_val_salt_hash(val, salt, str_hash): """ Given a string, salt, & hash validate the string The salt & val will be concatented as in gen_salt_and hash() & compared to the provided hash. This will only ever work with hashes derived from gen_salt_and_hash() :param val: clear-text string :pa...
java
public final void setGoods(final InvItem pGoods) { this.goods = pGoods; if (this.itsId == null) { this.itsId = new GoodsAdviseCategoriesId(); } this.itsId.setGoods(this.goods); }
python
def wrap_prompts_class(Klass): """ Wrap an IPython's Prompt class This is needed in order for Prompt to inject the correct escape sequences at the right positions for shell integrations. """ try: from prompt_toolkit.token import ZeroWidthEscape except ImportError: return K...
python
def changelog(since, to, write, force): """ Generates a markdown file containing the list of checks that changed for a given Agent release. Agent version numbers are derived inspecting tags on `integrations-core` so running this tool might provide unexpected results if the repo is not up to date wit...
java
@Override public Object getValueAt(final List<Integer> row, final int col) { Object rowBean = getRowBean(row); if (rowBean == null) { return null; } // Row has renderer if (col == -1) { return rowBean; } int lvlIndex = getLevelIndex(row); LevelDetails level = levels.get(lvlIndex); if (col >=...
java
public List<ValidationMessage<Origin>> getMessages(String messageKey, Severity severity) { List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>(); for (ValidationResult result : results) { for (ValidationMessage<Origin> message : result.getMessages()) { ...
java
public static List<CommerceDiscount> findByLtE_S(Date expirationDate, int status) { return getPersistence().findByLtE_S(expirationDate, status); }
java
public static CurrencyFunction currency(String fieldName, @Nullable String currencyCode) { Assert.hasText(fieldName, "FieldName for currency function must not be 'empty'."); return currency(new SimpleField(fieldName), currencyCode); }
python
def colour_for_point(mlog, point, instance, options): global colour_expression_exceptions, colour_source_max, colour_source_min '''indicate a colour to be used to plot point''' source = getattr(options, "colour_source", "flightmode") if source == "flightmode": return colour_for_point_flightmode(...
python
def _fake_deletequalifier(self, namespace, **params): """ Implements a server responder for :meth:`~pywbem.WBEMConnection.DeleteQualifier` Deletes a single qualifier if it is in the repository for this class and namespace Raises; CIMError: CIM_ERR_INVALID_N...
java
public void marshall(Source source, ProtocolMarshaller protocolMarshaller) { if (source == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(source.getType(), TYPE_BINDING); protocolMarshall...
java
@Override protected void processImage(ImageBase image) { // The data type of 'image' was specified in onCreate() function // The line below will compute the gradient and store it in two images. One for the // gradient along the x-axis and the other along the y-axis gradient.process((GrayU8)image,derivX,derivY)...
java
@Override public void dumpResponse(Map<String, Object> result) { this.statusCodeResult = String.valueOf(exchange.getStatusCode()); this.putDumpInfoTo(result); }
python
def _split_hostport(self, hostport, default_port=None): """Split a string in the format of '<host>:<port>' into it's component parts default_port will be used if a port is not included in the string Args: str ('<host>' or '<host>:<port>'): A string to split into it's parts ...
java
@SuppressWarnings("MagicNumber") protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) throws IOException { if (!rootDir.exists()) { // Silently skip non-existing directories. return Collections.emptySet(); } if (!rootDir.isDirectory()) { ...
java
@Pure public int getColor(int defaultColor) { final Integer c = getRawColor(); if (c != null) { return c; } final BusContainer<?> container = getContainer(); if (container != null) { return container.getColor(); } return defaultColor; }
python
def event_dispatcher(nameko_config, **kwargs): """ Return a function that dispatches nameko events. """ amqp_uri = nameko_config[AMQP_URI_CONFIG_KEY] serializer, _ = serialization.setup(nameko_config) serializer = kwargs.pop('serializer', serializer) ssl = nameko_config.get(AMQP_SSL_CONFIG_KEY...
java
private static void sort(byte[] byteArray, int start, int end, boolean descending) { if(start == end) { return ; } int middle = (start + end) >> 1; Merge.sort(byteArray, start, middle, descending); Merge.sort(byteArray, middle + 1, end, descending); ...
python
def write_gps_datum(self, code=None, gps_datum=None): """ Write the mandatory GPS datum header:: writer.write_gps_datum() # -> HFDTM100GPSDATUM:WGS-1984 writer.write_gps_datum(33, 'Guam-1963') # -> HFDTM033GPSDATUM:Guam-1963 Note that the defaul...
python
def stdout(self): """ The job stdout :return: string or None """ streams = self._payload.get('streams', None) return streams[0] if streams is not None and len(streams) >= 1 else ''
python
def _make_new_contig_from_nucmer_and_spades(self, original_contig, hits, circular_spades, log_fh=None, log_outprefix=None): '''Tries to make new circularised contig from contig called original_contig. hits = list of nucmer hits, all with ref=original contg. circular_spades=set of query contig names that spades ...
python
def setLayout(self, value): """ Sets the worksheet layout, keeping it sorted by position :param value: the layout to set """ new_layout = sorted(value, key=lambda k: k['position']) self.getField('Layout').set(self, new_layout)
python
def seek(self, position): """Seek to the specified position (byte offset) in the S3 key. :param int position: The byte offset from the beginning of the key. """ self._position = position range_string = make_range_string(self._position) logger.debug('content_length: %r ra...
java
@Override public boolean remove(Object o) { if (elements.remove(o)) { ordered.remove(o); return true; } else { return false; } }
java
List<PyExpr> execOnChildren(ParentSoyNode<?> node) { Preconditions.checkArgument(isComputableAsPyExprVisitor.execOnChildren(node)); pyExprs = new ArrayList<>(); visitChildren(node); return pyExprs; }
java
public ZoneRulesBuilder addWindowForever(ZoneOffset standardOffset) { return addWindow(standardOffset, LocalDateTime.MAX, TimeDefinition.WALL); }
python
def _symmetrize_correlograms(correlograms): """Return the symmetrized version of the CCG arrays.""" n_clusters, _, n_bins = correlograms.shape assert n_clusters == _ # We symmetrize c[i, j, 0]. # This is necessary because the algorithm in correlograms() # is sensitive to the order of identical...
java
public void checkTableName(final String name) { if (name.charAt(0) == SINGLE_QUOTE) { throw new IllegalArgumentException( "Table name should not start with " + SINGLE_QUOTE + ": " + name); } for (int i = 0; i < name.length(); i++) { final char c ...
python
def _bind_device(self): """ This method implements ``_bind_device`` from :class:`~lewis.core.devices.InterfaceBase`. It binds Cmd and Var definitions to implementations in Interface and Device. """ patterns = set() self.bound_commands = [] for cmd in self.comman...
java
@ManyToOne(targetEntity = org.openprovenance.prov.sql.QualifiedName.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "GENERATION") public org.openprovenance.prov.model.QualifiedName getGeneration() { return generation; }
java
public void remove(K k) { if (cache.containsKey(k)) { cache.remove(k); locks.remove(k); } }
java
public static JsonNode remove(ObjectNode obj, String fieldName) { JsonNode result = null; if (obj != null) { result = obj.remove(fieldName); } return result; }
java
public void addListener(RunListener listener) { if (listener == null) { throw new NullPointerException("Cannot add a null listener"); } listeners.add(wrapIfNotThreadSafe(listener)); }
python
def concatenate_variables(scope, variables, container): ''' This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation. ''' # Check if it's possible to concatenate those inputs. ...
python
def _request_raw_content(self, url, timeout): """ Send the request to get raw content. """ request = Request(url) if self.referer is not None: request.add_header('Referer', self.referer) raw_xml = self._call_geocoder( request, timeou...
java
@Test(groups = {SAMPLES}) public void getDE1MonitoringStatsForLastHourGroupedByServers() { List<MonitoringStatsEntry> stats = statisticsService .monitoringStats() .forDataCenters( new DataCenterFilter() .dataCenters(DE_FRANKFURT) ) ...
java
public String findString(String uri) throws IOException { String fullUri = path + uri; URL resource = getResource(fullUri); if (resource == null) { throw new IOException("Could not find a resource in : " + fullUri); } return readContents(resource); }
java
@Override public void prepare(Map storm_conf) { int timeout = Utils.getInt(storm_conf.get(Config.STORM_GROUP_MAPPING_SERVICE_CACHE_DURATION_SECS)); cachedGroups = new TimeCacheMap<String, Set<String>>(timeout); }
python
def vcsNodeState_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs") originator_switch_info = ET.SubElement(vcsNodeState, "...
java
public final void selectNavigationPreference( @Nullable final NavigationPreference navigationPreference, @Nullable final Bundle arguments) { selectNavigationPreference(navigationPreference == null ? -1 : indexOfNavigationPreference(navigationPreference), arguments); }
python
def help(self, command=None): """ help [command] Display a list of available commands. If the command is specified, display help for this command. """ cmd = 'help' if command: cmd += ' %s' % command return self.fetch(cmd)[1]
java
public void setMediaConnectFlows(java.util.Collection<MediaConnectFlow> mediaConnectFlows) { if (mediaConnectFlows == null) { this.mediaConnectFlows = null; return; } this.mediaConnectFlows = new java.util.ArrayList<MediaConnectFlow>(mediaConnectFlows); }
java
public void marshall(ModifyEndpointRequest modifyEndpointRequest, ProtocolMarshaller protocolMarshaller) { if (modifyEndpointRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(modifyEndpointRe...
java
private static boolean processRadicals(CharIter iter, CxSmilesState state) { if (state.atomRads == null) state.atomRads = new TreeMap<>(); CxSmilesState.Radical rad; switch (iter.next()) { case '1': rad = CxSmilesState.Radical.Monovalent; b...
java
public static String createId(Entity vcfEntity) { String idStr = StringUtils.strip(vcfEntity.get(CHROM).toString()) + "_" + StringUtils.strip(vcfEntity.get(POS).toString()) + "_" + StringUtils.strip(vcfEntity.get(REF).toString()) + "_" ...
java
public static boolean hasBackground(Element element) { String backgroundColor = CmsDomUtil.getCurrentStyle(element, Style.backgroundColor); String backgroundImage = CmsDomUtil.getCurrentStyle(element, Style.backgroundImage); if ((isTransparent(backgroundColor)) && ((backgroundImage ...
python
def identify_marker_genes_corr(self, labels=None, n_genes=4000): """ Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str...
java
public Object preInvokeMdbActivate(EJSWrapperBase wrapper, int methodId, EJSDeployedSupport s) throws Exception { EJBMethodInfoImpl methodInfo = mapMethodInfo(s, wrapper, methodId, null); if (TraceComponent.isAnyTracingEnable...
python
def timTuVi(cuc, ngaySinhAmLich): """Tìm vị trí của sao Tử vi Args: cuc (TYPE): Description ngaySinhAmLich (TYPE): Description Returns: TYPE: Description Raises: Exception: Description """ cungDan = 3 # Vị trí cung Dần ban đầu là 3 cucBanDau = cuc if c...
java
public void removeRequirement(Requirement requirement) throws GreenPepperServerException { try { sessionService.startSession(); sessionService.beginTransaction(); documentDao.removeRequirement(requirement); sessionService.commitTransaction(); log.deb...
java
private void addPostParams(final Request request) { if (assetVersions != null) { for (String prop : assetVersions) { request.addPostParam("AssetVersions", prop); } } if (functionVersions != null) { for (String prop : functionVersions) { ...
python
def buffer(stream, buffer_size=BUFFER_SIZE): ''' Buffer the generator into byte strings of buffer_size samples Return a generator that outputs reasonably sized byte strings containing buffer_size samples from the generator stream. This allows us to outputing big chunks of the audio stream to disk at once for ...
java
public ServiceFuture<NamespaceResourceInner> createOrUpdateAsync(String resourceGroupName, String namespaceName, NamespaceCreateOrUpdateParameters parameters, final ServiceCallback<NamespaceResourceInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupNa...
java
public final void createdName() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:609:5: ( ID ( typeArguments )? ( DOT ID ( typeArguments )? )* | primitiveType ) int alt71=2; int LA71_0 = input.LA(1); if ( (LA71_0==ID) ) { int LA71_1 = input.LA(2); ...
java
@View(name = "by_recordDate", map = "function(doc) { if (doc.principal && doc.deviceFingerprint && doc.recordDate) { emit(doc.recordDate, doc) } }") public List<CouchDbMultifactorAuthenticationTrustRecord> findOnOrBeforeDate(final LocalDateTime recordDate) { return db.queryView(createQuery("by_recordDate")....
python
def relabel_atoms(self, start=1): """Relabels all `Atoms` in numerical order. Parameters ---------- start : int, optional Offset the labelling by `start` residues. """ counter = start for atom in self.get_atoms(): atom.id = counter ...
python
def get_package_data(): """ Returns the packages with static files of HaTeMiLe for Python. :return: The packages with static files of HaTeMiLe for Python. :rtype: dict(str, list(str)) """ package_data = { '': ['*.xml'], 'js': ['*.js'], LOCALES_DIRECTORY: ['*'] } ...
java
@Override public boolean purgeRelationship(String pid, String relationship, String object, boolean isLiteral, String datatype) { LOG.debug("start: purgeRelation...
python
def addStreamingListener(self, streamingListener): """ Add a [[org.apache.spark.streaming.scheduler.StreamingListener]] object for receiving system events related to streaming. """ self._jssc.addStreamingListener(self._jvm.JavaStreamingListenerWrapper( self._jvm.Pytho...
python
def from_string(string): """ Construct an AdfKey object from the string. Parameters ---------- string : str A string. Returns ------- adfkey : AdfKey An AdfKey object recovered from the string. Raises ------ ...
java
public String rate(RateCondition condition) { String description; if (condition.getContext() != null && condition.getContext().get(CONTEXT_PROPERTY_DESCRIPTION) != null) { description = condition.getContext().get(CONTEXT_PROPERTY_DESCRIPTION); } else { description = condi...
python
def show_help_text(self, name, help_txt, wsname='right'): """ Show help text in a closeable tab window. The title of the window is set from ``name`` prefixed with 'HELP:' """ tabname = 'HELP: {}'.format(name) group = 1 tabnames = self.ds.get_tabnames(group) ...
python
def simple_pairing_rand(self): """Simple Pairing Randomizer R. Received and transmitted as EIR type 0x0F. Set to None if not received or not to be transmitted. Raises nfc.ndef.DecodeError if the received value or nfc.ndef.EncodeError if the assigned value is not a sequence of 16 ...
python
def configure_google_analytics(): """An optional task; if run, this will switch on Google Analystics, reporting documentation usage to Aviser. This is meant to be run only by Aviser when producing HTML for the main web site. """ f = open(os.path.join("doc", "_templates", "google-analytics.html"...
java
public void addConstraint (Shutdowner lhs, Constraint constraint, Shutdowner rhs) { switch (constraint) { case RUNS_BEFORE: _cycle.addShutdownConstraint(lhs, Lifecycle.Constraint.RUNS_BEFORE, rhs); break; case RUNS_AFTER: _cycle.addShutdownConstraint(lhs, ...
python
def insert(self, database, key, value, callback=None): """ Insert an item into the given database. :param database: The database into which to insert the value. :type database: .BlobDatabaseID :param key: The key to insert. :type key: uuid.UUID :param value: The ...
java
public static String privateKeyEncrypt(String key, String plainText) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException { PrivateKey privateKey = commonGetPriv...
python
def create_dscp_marking_rule(self, policy, body=None): """Creates a new DSCP marking rule.""" return self.post(self.qos_dscp_marking_rules_path % policy, body=body)
python
def altitudes(self): ''' A list of the altitudes of each vertex [AltA, AltB, AltC], list of floats. An altitude is the shortest distance from a vertex to the side opposite of it. ''' a = self.area * 2 return [a / self.a, a / self.b, a / self.c]
java
public com.google.api.ads.admanager.axis.v201805.LinkStatus getLinkStatus() { return linkStatus; }
python
def save_configs(self): """ Saves the startup-config and private-config to files. """ if self.startup_config_content or self.private_config_content: startup_config_content, private_config_content = self.extract_configs() if startup_config_content: ...
java
public void marshall(CreateTableRequest createTableRequest, ProtocolMarshaller protocolMarshaller) { if (createTableRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createTableRequest.getCat...
java
@NotNull public OptionalInt mapToInt(@NotNull ToIntFunction<? super T> mapper) { if (!isPresent()) return OptionalInt.empty(); return OptionalInt.of(mapper.applyAsInt(value)); }
python
def engage(self, **kwargs): ''' Move the magnet to either: the default height for the labware loaded on magdeck [engage()] or a +/- 'offset' from the default height for the labware [engage(offset=2)] or a 'height' value specified as mm from magdeck h...
java
public Banners getBanners(String seriesId) throws TvDbException { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(BASE_URL) .append(apiKey) .append(SERIES_URL) .append(seriesId) .append("/banners.xml"); LO...
java
private void persistHistoricalData() { synchronized (mInstanceLock) { if (!mReadShareHistoryCalled) { throw new IllegalStateException("No preceding call to #readHistoricalData"); } if (!mHistoricalRecordsChanged) { return; } ...
java
public static <T> Iterable<T> wrap(Iterable<T> ts, String task) { return wrap(ts, new ProgressBarBuilder().setTaskName(task)); }
python
def list_themes(cls, path=THEMES): """ Compile all of the themes configuration files in the search path. """ themes, errors = [], OrderedDict() def load_themes(path, source): """ Load all themes in the given path. """ if os.path.is...
java
public static Tuple of( Collection<VarBindingDef> tupleBindings) { Tuple tuple = new Tuple(); boolean bindingsCompatible; Iterator<VarBindingDef> bindings; VarBindingDef nextBinding; for( bindings = tupleBindings.iterator(), bindingsCompatible = true; bindings.hasNext(...
python
def fetch(self): """ Fetch a UserChannelInstance :returns: Fetched UserChannelInstance :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
java
public String convertIfcEnergySequenceEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def on_accept(self, auto=False): """ Initiates acceptance procedure, gathering required data. @param auto: Set on_accept to automatic measure of source? """ if self.model.is_current_source_named(): provisional_name = self.model.get_current_source_name() else:...
python
def set_gateway(self, gateway): ''' :param crabpy.gateway.capakey.CapakeyGateway gateway: Gateway to use. ''' self.gateway = gateway if (self._gemeente is not None): self._gemeente.set_gateway(gateway)
python
def completer(*commands): """Decorate a function to be the completer function of commands. Arguments: commands: Names of command that should trigger this function object. ------------------------------ Interface of completer methods: @completer('some-other_command') def comple...
python
def from_string(cls, name, separator='-', reverse=False): """ Class constructor using a string with the artist and title. This should be used when parsing user input, since all the information must be specified in a single string formatted as: '{artist} - {title}'. """ re...
java
public static <R> Stream<R> zip(final double[] a, final double[] b, final double valueForNoneA, final double valueForNoneB, final DoubleBiFunction<R> zipFunction) { return zip(DoubleIteratorEx.of(a), DoubleIteratorEx.of(b), valueForNoneA, valueForNoneB, zipFunction); }
java
@Override public int compare(JoinableResourceBundle bundleA, JoinableResourceBundle bundleB) { Integer a = bundleA.getInclusionPattern().getInclusionOrder(); Integer b = bundleB.getInclusionPattern().getInclusionOrder(); return a.compareTo(b); }
java
public static List<String> to863(List<Term> termList) { List<String> posTagList = new ArrayList<String>(termList.size()); for (Term term : termList) { String posTag = posConverter.get(term.nature.toString()); if (posTag == null) posTag = term.nature.to...
python
def _write_to_graph(self): """Write the coverage results to a graph""" traces = [] for byte_code, trace_data in self.coverage.items(): traces += [list(trace_data.keys()), list(trace_data.values()), "r--"] plt.plot(*traces) plt.axis([0, self.end - self.begin, 0, 100])...
java
public byte[] toGzipByteArray() { String sitemap = this.toString(); ByteArrayInputStream inputStream = new ByteArrayInputStream(sitemap.getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream outputStream = gzipIt(inputStream); return outputStream.toByteArray(); }
python
def list_insert(lst, new_elements, index_or_name=None, after=True): """ Return a copy of the list with the new element(s) inserted. Args: lst (list): The original list. new_elements ("any" or list of "any"): The element(s) to insert in the list. index_or_name (int or str): The value...
java
protected void drawText(Graphics2D g, String text) { // top left corner int x = getAbsoluteContentX(); int y = getAbsoluteContentY(); //Align Y with baseline FontMetrics fm = g.getFontMetrics(); Rectangle2D rect = fm.getStringBounds(text, g); int ofs = getFir...
python
def chrootedSystemCall(chrootDir, cmd, sh=True, mountPseudoFs=True, log=None): '''Chrooted version of systemCall. Manages necessary pseudo filesystems.''' if log is None: log = conduct.app.log # determine mount points for pseudo fs proc = path.join(chrootDir, 'proc') sys = path.join(chrootD...
python
def quit(self): """ Send LMTP QUIT command, read the server response and disconnect. """ self._send('QUIT\r\n') resp = self._read() if not resp.startswith('221'): logger.warning('Unexpected server response at QUIT: ' + resp) self._socket.close() ...
java
public SendTemplatedEmailRequest withTags(MessageTag... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<MessageTag>(tags.length)); } for (MessageTag ele : tags) { this.tags.add(ele); } return this; }
java
public java.util.List<DirectoryDescription> getDirectoryDescriptions() { if (directoryDescriptions == null) { directoryDescriptions = new com.amazonaws.internal.SdkInternalList<DirectoryDescription>(); } return directoryDescriptions; }
java
public MigrateArgs<K> key(K key) { LettuceAssert.notNull(key, "Key must not be null"); this.keys.add(key); return this; }
python
def upload_job_chunk_list(self, upload_job_id, **kwargs): # noqa: E501 """List all metadata for uploaded chunks # noqa: E501 List all metadata for uploaded chunks # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass a...
java
public final Object put(Object key, Object value) { return internalData.put(key, value); }