language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_json_results(self, response): ''' Parses the request result and returns the JSON object. Handles all errors. ''' try: # return the proper JSON object, or error code if request didn't go through. self.most_recent_json = response.json() json_resu...
python
def call(self, **kwargs): """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written an...
java
private Set<String> evaluateScope(String scope, CmsXmlContentDefinition definition) { Set<String> evaluatedScopes = new HashSet<String>(); if (scope.contains("*")) { // evaluate wildcards to get all allowed permutations of the scope // a path like Paragraph*/Image should result ...
java
public PersistedFace getFace(String personGroupId, UUID personId, UUID persistedFaceId) { return getFaceWithServiceResponseAsync(personGroupId, personId, persistedFaceId).toBlocking().single().body(); }
python
def is_installed(self, bug: Bug) -> bool: """ Determines whether or not the Docker image for a given bug has been installed onto this server. See: `BuildManager.is_installed` """ return self.__installation.build.is_installed(bug.image)
java
public void reset() { checkPermission(); synchronized (this) { props = new Hashtable<>(); // Since we are doing a reset we no longer want to initialize // the global handlers, if they haven't been initialized yet. initializedGlobalHandlers = true; ...
python
def WriteFlowResponses(self, responses): """Writes FlowMessages and updates corresponding requests.""" status_available = set() requests_updated = set() task_ids_by_request = {} for response in responses: flow_key = (response.client_id, response.flow_id) if flow_key not in self.flows: ...
java
public synchronized boolean updateNode(int streamID, NODE_STATUS status, WRITE_COUNT_ACTION writeCountAction, H2WriteQEntry entry) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { if (entry == null) { Tr.debug(tc, "updateNode entry: null" + " streamID: " + stream...
python
def createAddress(self, prefix, type, network_id, callback=None, errback=None, **kwargs): """ Create a new Address For the list of keywords available, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addresses.PASSTHRU_FIELDS` :param str prefix: CIDR prefix of the...
java
private void processDatabaseMappingCollection(final Object databaseMappingCollection) { if (databaseMappingCollection == null || !isCastable("java.util.Collection", databaseMappingCollection.getClass())) { return; } final Collection<?> c = (Collection<?>) databaseMappingCollection; ...
java
public void translate(float x, float y, float z) { NativeTransform.translate(getNative(), x, y, z); }
python
def conditional_expected_number_of_purchases_up_to_time(self, m_periods_in_future, frequency, recency, n_periods): r""" Conditional expected purchases in future time period. The expected number of future transactions across the next m_periods_in_future transaction opportunities by ...
java
public static String removeControlCharacters(String s, boolean removeCR) { String ret = s; if(ret != null) { ret = ret.replaceAll("_x000D_",""); if(removeCR) ret = ret.replaceAll("\r",""); } return ret; }
java
public static ParameterizedType newParameterizedType( final Class<?> raw, Iterable<? extends Type> typeArgs) { TypeResolver resolver = new TypeResolver(); final List<TypeVariable<?>> vars = new ArrayList<TypeVariable<?>>(); for (Type arg : typeArgs) { TypeVariable<?> var = TypeVariableGenerator....
python
def ddtohms(xsky,ysky,verbose=False,precision=6): """ Convert sky position(s) from decimal degrees to HMS format. """ xskyh = xsky /15. xskym = (xskyh - np.floor(xskyh)) * 60. xskys = (xskym - np.floor(xskym)) * 60. yskym = (np.abs(ysky) - np.floor(np.abs(ysky))) * 60. yskys = (yskym - np.floor(...
java
public static CellConstraints xywh(int col, int row, int colSpan, int rowSpan, String encodedAlignments) { return new CellConstraints().xywh(col, row, colSpan, rowSpan, encodedAlignments); }
python
def post_build(self, p, pay): """Called implicitly before a packet is sent. """ p += pay if self.auxdlen != 0: print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).") print(" Subsequent Group Records are lost!") return ...
python
def get_active_geometry(self): """ Get the geometry of the currently active window Usage: C{window.get_active_geometry()} @return: a 4-tuple containing the x-origin, y-origin, width and height of the window (in pixels) @rtype: C{tuple(int, int, int, int)} ...
python
def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = '/usr/sbin/svcadm restart {0}'.format(name) if not __salt__['cmd.retcode'](cmd, python_shell=False): # calling restart doesn't clear mainten...
python
def subset_sum(x, R): """Subsetsum by splitting :param x: table of values :param R: target value :returns bool: if there is a subsequence of x with total sum R :complexity: :math:`O(n^{\\lceil n/2 \\rceil})` """ k = len(x) // 2 # divide input Y = [v for v in part_sum(x[:k])]...
java
public void addLine(int startLine, String sourceFile, int repeatCount, int outputLine, int outputIncrement) { _lines.add(new Line(startLine, sourceFile, repeatCount, outputLine, outputIncrement)); }
java
@Override public Client header(String name, Object... values) { if (values == null) { throw new IllegalArgumentException(); } if (HttpHeaders.CONTENT_TYPE.equals(name)) { if (values.length > 1) { throw new IllegalArgumentException("Content-Type can hav...
java
@Override public IEntityGroup newGroup(Class type, Name serviceName) throws GroupsException { return getComponentService(serviceName).newGroup(type); }
java
@Override public void handle(StopTransactionRequestedEvent event, CorrelationToken correlationToken) { LOG.info("OCPP 1.2 StopTransactionRequestedEvent"); if (event.getTransactionId() instanceof NumberedTransactionId) { NumberedTransactionId transactionId = (NumberedTransactionId) event...
java
@Override public String getProperty(String name) { loadProperties(); return properties == null ? null : properties.getProperty(name); }
java
public PendingIntent getActionIntent(NotificationEntry entry, NotificationEntry.Action act) { Intent intent = new Intent(ACTION_ACTION); intent.putExtra(KEY_ENTRY_ID, entry.ID); intent.putExtra(KEY_ACTION_ID, entry.mActions.indexOf(act)); return PendingIntent.getBroadcast(mContext, genId...
java
public void waitForReady() { if (!isLoaded) { synchronized (LOAD_LOCK) { if (!isLoaded) { try { long start = Runtime.getActorTime(); LOAD_LOCK.wait(); Log.d(TAG, "Waited for startup in " + (Ru...
java
private List<AdvancedModelWrapper> performEOModelUpdate(EngineeringObjectModelWrapper model, EKBCommit commit) { ModelDiff diff = createModelDiff(model.getUnderlyingModel(), model.getCompleteModelOID(), edbService, edbConverter); boolean referencesChanged = diff.isForeignKeyChanged(); ...
python
def get_members_by_source(base_url=BASE_URL_API): """ Function returns which members have joined each activity. :param base_url: It is URL: `https://www.openhumans.org/api/public-data`. """ url = '{}members-by-source/'.format(base_url) response = get_page(url) return response
java
private List<String> collectProcessResults(Process process, ProcessBuilder builder, SubProcessIOFiles outPutFiles) throws Exception { List<String> results = new ArrayList<>(); try { LOG.debug(String.format("Executing process %s", createLogEntryFromInputs(builder.command()))); // If process...
java
@Override public EEnum getIfcConstructionEquipmentResourceTypeEnum() { if (ifcConstructionEquipmentResourceTypeEnumEEnum == null) { ifcConstructionEquipmentResourceTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE .getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(943); } return ifcConstructi...
python
def assoc(m, *args, **kw): ''' assoc(m, k1, v1, k2, v2...) yields a map equivalent to m without the arguments k1, k2, etc. associated with the values v1, v2, etc. If m is a mutable python dictionary, this is equivalent to using m[k] = v for all the given key-value pairs then returning m itself. If m...
python
def _get_search_result(self, query_url, **query_params): """ Get search results helper. """ param_q = query_params.get('q') param_query = query_params.get('query') # Either q or query parameter is required if bool(param_q) == bool(param_query): raise CloudantArgumentE...
python
def _set_hide_intf_loopback_holder(self, v, load=False): """ Setter method for hide_intf_loopback_holder, mapped from YANG variable /hide_intf_loopback_holder (container) If this variable is read-only (config: false) in the source YANG file, then _set_hide_intf_loopback_holder is considered as a private...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: _dict['request'] = self.request._to_dict() if hasattr(self, 'response') and self.response is not None: _dict['response'...
java
@Override public void parse(ParseContext context) throws MonetaryParseException { if (!context.consume(token)) { throw new MonetaryParseException(context.getOriginalInput(), context.getErrorIndex()); } }
java
public void marshall(StartTaskExecutionRequest startTaskExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (startTaskExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(star...
java
public CORSConfigBuilder withAllowedHeaders(Collection<String> headerNames) { Mutils.notNull("headerNames", headerNames); this.allowedHeaders = headerNames; return this; }
java
@Override public final void setup() { // Setup mandatory environment facets try { if (log.isDebugEnabled()) { log.debug("ToolExecutionEnvironment setup -- Starting."); } // Build the ClassLoader as required for the JAXB tools holder ...
python
def contains_no(self, prototype): """ Ensures no item of :attr:`subject` is of class *prototype*. """ for element in self._subject: self._run(unittest_case.assertNotIsInstance, (element, prototype)) return ChainInspector(self._subject)
java
private void orderPolicies(PoliciesBean policies) { int idx = 1; for (PolicyBean policy : policies.getPolicies()) { policy.setOrderIndex(idx++); } }
python
def add_record(self, is_sslv2=None, is_tls13=None): """ Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out. """ if is_sslv2 is None and is_tls13 is None: v = (self.cur_session.tls_version or self.cur_session.advertised_tls_version) ...
java
@SafeVarargs public static ScannerSupplier fromBugCheckerClasses( Class<? extends BugChecker>... checkerClasses) { return fromBugCheckerClasses(Arrays.asList(checkerClasses)); }
python
def collaborators(self): """The collaborators for this app.""" return self._h._get_resources( resource=('apps', self.name, 'collaborators'), obj=Collaborator, app=self )
java
static String getClassSimpleName(String className) { int lastPeriod = className.lastIndexOf("."); if (lastPeriod != -1) { return className.substring(lastPeriod + 1); } return className; }
java
public X getPrimaryID(T entity) { if(mappingContext == null || conversionService == null) { fetchMappingContextAndConversionService(); } MongoPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(entity.getClass()); MongoPersistentProperty idProperty = persistentEntity.getIdProperty(); ...
java
@Override public CPDisplayLayout[] findByUuid_PrevAndNext(long CPDisplayLayoutId, String uuid, OrderByComparator<CPDisplayLayout> orderByComparator) throws NoSuchCPDisplayLayoutException { CPDisplayLayout cpDisplayLayout = findByPrimaryKey(CPDisplayLayoutId); Session session = null; try { session = open...
java
public void setConfigurations(java.util.Collection<Configuration> configurations) { if (configurations == null) { this.configurations = null; return; } this.configurations = new java.util.ArrayList<Configuration>(configurations); }
java
public int getTotalLeased(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections(); } return total; }
java
private void checkCircularity(State state, Obligation obligation, int basicBlockId) throws ObligationAcquiredOrReleasedInLoopException { if (state.getPath().hasComponent(basicBlockId)) { throw new ObligationAcquiredOrReleasedInLoopException(obligation); } }
java
public float getQuote(String stock_name) throws Exception { System.out.print("Getting quote for " + stock_name + ": "); Float retval=stocks.get(stock_name); if(retval == null) { System.out.println("not found"); throw new Exception("Stock " + stock_name + " not found"); ...
python
def save_as_gif(self, gif_path, duration=0.25): """Package the selected slices into a single GIF for easy sharing and display (on web etc). You must install imageio module separately to use this feature. Parameters ---------- gif_path : str Output path for the GIF i...
java
@JsonValue @Override public String value() { return isCuried() ? String.format("%s:%s", curie, localPart) : localPart; }
java
@Override public GenericRecord parse(ByteBuffer bytes) { if (bytes.remaining() < 5) { throw new ParseException("record must have at least 5 bytes carrying version and schemaId"); } byte version = bytes.get(); if (version != V1) { throw new ParseException("found record of arbitrary versi...
python
def _get(self, key, parser_result): """ Given a type and a dict of parser results, return the items as a list. """ try: list_data = parser_result[key].asList() if any(isinstance(obj, str) for obj in list_data): txt_lines = [''.join(list_data)] ...
python
def relative_startup_config_file(self): """ Returns the startup-config file relative to the project directory. It's compatible with pre 1.3 projects. :returns: path to startup-config file. None if the file doesn't exist """ path = os.path.join(self.working_dir, 'startup...
python
def load(self, text, fieldnames=None): """Item from TSV representation.""" lines = text.split('\n') fieldnames = load_line(lines[0]) values = load_line(lines[1]) self.__dict__ = dict(zip(fieldnames, values))
java
public AwsSecurityFindingFilters withResourceAwsIamAccessKeyStatus(StringFilter... resourceAwsIamAccessKeyStatus) { if (this.resourceAwsIamAccessKeyStatus == null) { setResourceAwsIamAccessKeyStatus(new java.util.ArrayList<StringFilter>(resourceAwsIamAccessKeyStatus.length)); } for (...
java
private void sendSnapshotTxnId(SnapshotInfo toRestore) { long txnId = toRestore != null ? toRestore.txnId : 0; String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}"; LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes"); try { m_...
java
private static void setField(final Object instance, final Field field, final Object value) { final boolean accessability = field.isAccessible(); try { field.setAccessible(true); field.set(instance, value); } catch (Exception e) { InjectionException.reth...
python
async def loadCoreModule(self, ctor, conf=None): ''' Load a single cortex module with the given ctor and conf. Args: ctor (str): The python module class path conf (dict):Config dictionary for the module ''' if conf is None: conf = {} ...
java
protected TreeNode dfs(Object cell, Object parent, Set<Object> visited) { if (visited == null) { visited = new HashSet<Object>(); } TreeNode node = null; mxIGraphModel model = graph.getModel(); if (cell != null && !visited.contains(cell) && (!isVertexIgnored(cell) || isBoundaryEvent(...
java
public void putClientMetrics(ClientMetrics clientMetrics) throws GalaxyFDSClientException { URI uri = formatUri(fdsConfig.getBaseUri(), "", (SubResource[]) null); ContentType contentType = ContentType.APPLICATION_JSON; HashMap<String, String> params = new HashMap<String, String>(); params.put("cli...
java
static void write(List<AccessLogComponent> format, RequestLog log) { final VirtualHost host = ((ServiceRequestContext) log.context()).virtualHost(); final Logger logger = host.accessLogger(); if (!format.isEmpty() && logger.isInfoEnabled()) { logger.info(format(format, log)); ...
java
public static Dictionary read(InputStream fsaStream, InputStream metadataStream) throws IOException { return new Dictionary(FSA.read(fsaStream), DictionaryMetadata.read(metadataStream)); }
java
static <T extends FunctionMeta> Map<T, IDataModel> toMetaFunctions(IDataModel book, Class<T> metaClass) { return toMetaFunctions(DataModelConverters.toWorkbook(book), metaClass); }
java
static File getOutputDirectory(MavenProject rootModule) { String directoryName = rootModule.getBuild().getDirectory() + "/" + OUTPUT_DIRECTORY; File directory = new File(directoryName); directory.mkdirs(); return directory; }
java
public void addSummaryLinkComment(AbstractMemberWriter mw, Element member, Content contentTree) { List<? extends DocTree> tags = utils.getFirstSentenceTrees(member); addSummaryLinkComment(mw, member, tags, contentTree); }
python
def list(self): """Lists all sessions in the store. .. versionadded:: 0.6 """ before, after = self.filename_template.split('%s', 1) filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before), re.escape(after))) resul...
java
public static Validator<CharSequence> maxLength(@NonNull final Context context, final int maxLength) { return new MaxLengthValidator(context, R.string.default_error_message, maxLength); }
python
def probably_identical(self): """ :returns: Whether or not these two functions are identical. """ if len(self._unmatched_blocks_from_a | self._unmatched_blocks_from_b) > 0: return False for (a, b) in self._block_matches: if not self.blocks_probably_identic...
python
def delete_relation(sender, instance, **kwargs): """Delete the Relation object when the last Entity is removed.""" def process_signal(relation_id): """Get the relation and delete it if it has no entities left.""" try: relation = Relation.objects.get(pk=relation_id) except Rel...
java
public com.google.api.ads.adwords.axis.v201809.cm.Bid getFirstPositionCpc() { return firstPositionCpc; }
python
def mark_seen(self): """ Mark the selected message or comment as seen. """ data = self.get_selected_item() if data['is_new']: with self.term.loader('Marking as read'): data['object'].mark_as_read() if not self.term.loader.exception: ...
python
def renderbuffer(self, size, components=4, *, samples=0, dtype='f1') -> 'Renderbuffer': ''' :py:class:`Renderbuffer` objects are OpenGL objects that contain images. They are created and used specifically with :py:class:`Framebuffer` objects. Args: size (tuple...
python
def SecurityCheck(self, func, request, *args, **kwargs): """Wrapping function.""" request.user = u"" authorized = False try: auth_type, authorization = request.headers.get("Authorization", " ").split(" ", 1) if auth_type == "Basic": ...
python
def add_field(self, name, data): """ Add a new field to the datamat. Parameters: name : string Name of the new field data : list Data for the new field, must be same length as all other fields. """ if name in self._fields: ...
python
def get_cloud_init_mime(cloud_init): ''' Get a mime multipart encoded string from a cloud-init dict. Currently supports boothooks, scripts and cloud-config. CLI Example: .. code-block:: bash salt myminion boto.get_cloud_init_mime <cloud init> ''' if isinstance(cloud_init, six.stri...
python
def done(self): """Returns True if the call was successfully cancelled or finished running, False otherwise. This function updates the executionQueue so it receives all the awaiting message.""" # Flush the current future in the local buffer (potential deadlock # otherwise) ...
python
def list(self, sleep=1): ''' List the windows. Sleep is useful to wait some time before obtaining the new content when something in the window has changed. This also sets L{self.windows} as the list of windows. @type sleep: int @param sleep: sleep in seconds bef...
python
def dump(destination, ms, single=False, pretty_print=False, **kwargs): """ Serialize Xmrs objects to the Prolog representation and write to a file. Args: destination: filename or file object where data will be written ms: an iterator of Xmrs objects to serialize (unless the *sin...
java
public synchronized static void read(int fd, Collection<ByteBuffer> collection) throws IOException{ collection.add(ByteBuffer.wrap(read(fd))); }
python
def job_info(self, **kwargs): """ Get the information about the jobs returned by a particular search. See the [GetJobs][] documentation for more info. [GetJobs]: http://casjobs.sdss.org/casjobs/services/jobs.asmx?op=GetJobs """ search = ";".join(["%s : %s"%(k, str(kwarg...
python
def remove(self, id_equipamento, id_egrupo): """Remove a associacao de um grupo de equipamento com um equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :param id_equipamento: Identificador do equipamento. :return: None :raise E...
java
@Override public Record nextRecord() { Record next = sequenceRecordReader.nextRecord(); next.setRecord(transformProcess.execute(next.getRecord())); return next; }
python
def createCertRequest(pkey, digest="sha256"): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible ...
java
private IBatchServiceBase getService(Name serviceType) throws BatchContainerServiceException { String sourceMethod = "getService"; if (logger.isLoggable(Level.FINE)) logger.entering(sourceClass, sourceMethod + ", serviceType=" + serviceType); initIfNecessary(); IBatchServic...
java
@Override public void setContentHandler(ContentHandler handler) { if (handler == null) { handler = base; } contentHandler = handler; }
python
def _set_environment_variables(self): """Initializes the correct environment variables for spark""" cmd = [] # special case for driver JVM properties. self._set_launcher_property("driver-memory", "spark.driver.memory") self._set_launcher_property("driver-library-path", "spark.dr...
python
def add_flooded_field(self, shapefile_path): """Create the layer from the local shp adding the flooded field. .. versionadded:: 3.3 Use this method to add a calculated field to a shapefile. The shapefile should have a field called 'count' containing the number of flood reports ...
java
public Map<String, String> getMetatags() { Map<String, String> result = new HashMap<>(); for (Map.Entry<String, String> entry : _metatags.entrySet()) { String key = entry.getKey(); if (!ReservedField.isReservedField(key)) { result.put(key, entry.getValue()); ...
java
protected String getNonNamespacedNodeName(Node node) { String name = node.getLocalName(); if (name == null) { return node.getNodeName(); } return name; }
java
@Override public SchemaManager getSchemaManager(Map<String, Object> externalProperty) { if (schemaManager == null) { initializePropertyReader(); schemaManager = new CassandraSchemaManager(ThriftClientFactory.class.getName(), externalProperties, kundera...
java
@Override public boolean canRunInOneFragment() { assert(getScanPartitioning() != null); assert(m_subqueryStmt != null); if (getScanPartitioning().getCountOfPartitionedTables() == 0) { return true; } // recursive check for its nested subqueries that require coord...
python
def match(pattern, data, **parse_kwargs): """Returns all matched values of pattern in data""" return [m.value for m in parse(pattern, **parse_kwargs).find(data)]
python
def set_power(self, power): """Send Power command.""" req_url = ENDPOINTS["setPower"].format(self.ip_address, self.zone_id) params = {"power": "on" if power else "standby"} return request(req_url, params=params)
python
def create_datastore_for_topline(self, delete_first=0, path=None): # type: (int, Optional[str]) -> None """For tabular data, create a resource in the HDX datastore which enables data preview in HDX using the built in YAML definition for a topline. If path is not supplied, the file is first downl...
python
def make_interface_child(device_name, interface_name, parent_name): ''' .. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. ...
python
def create_identity_matcher(matcher='default', blacklist=None, sources=None, strict=True): """Create an identity matcher of the given type. Factory function that creates an identity matcher object of the type defined on 'matcher' parameter. A blacklist can also be added to i...
python
def encrypt(self, keys=None, cek="", iv="", **kwargs): """ Encrypt a payload :param keys: A set of possibly usable keys :param cek: Content master key :param iv: Initialization vector :param kwargs: Extra key word arguments :return: Encrypted message """ ...