language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _fill_cache(self): """Fill the cache from the `astropy.table.Table`""" for irow in range(len(self._table)): job_details = self.make_job_details(irow) self._cache[job_details.fullkey] = job_details
java
public static String parseMessage(int status) { String msg = null; if (status < 500) { if (status == 402 || (status > 417 && status < 421) || status > 424) { msg = ErrorMessage.getLocaleMessage(400); } else { ...
python
def update_currency_by_id(cls, currency_id, currency, **kwargs): """Update Currency Update attributes of Currency This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_currency_by_id(currency...
java
private Object getScriptResult(String script, ScriptEngine engine) throws ScriptException { String scriptToExecute = script.substring(script.indexOf(":") + 1); return engine.eval(scriptToExecute); }
java
private List<IAtomContainer> removeDuplicates(List<IAtomContainer> tautomers) throws CDKException { Set<String> cansmis = new HashSet<>(); List<IAtomContainer> result = new ArrayList<>(); for (IAtomContainer tautomer : tautomers) { if (cansmis.add(CANSMI.create(tautomer))) ...
java
protected JCClassDecl classDeclaration(JCModifiers mods, Comment dc) { int pos = token.pos; accept(CLASS); Name name = ident(); List<JCTypeParameter> typarams = typeParametersOpt(); JCExpression extending = null; if (token.kind == EXTENDS) { nextToken(); ...
java
public void addInt( @DoNotSub final int index, final int element) { checkIndexForAdd(index); @DoNotSub final int requiredSize = size + 1; ensureCapacityPrivate(requiredSize); if (index < size) { System.arraycopy(elements, index, elements, index +...
java
public static double getPvalue(TransposeDataList transposeDataList) { Object[] keys = transposeDataList.keySet().toArray(); if(keys.length!=2) { throw new IllegalArgumentException("The collection must contain observations from 2 groups."); } Object keyX = keys[0]; ...
java
public Post postReblog(String blogName, Long postId, String reblogKey, Map<String, ?> options) { if (options == null) { options = new HashMap<String, String>(); } Map<String, Object> soptions = JumblrClient.safeOptionMap(options); soptions.put("id", postId.toString()); ...
java
@Override public File call() throws Exception { try { latch.await(); if (isTimeoutEnabled()) { timedExecutor.schedule(new Runnable() { public void run() { try { if (abortableDownload.getState() !...
python
def _convert(self, datetime=False, numeric=False, timedelta=False, coerce=False, copy=True): """ Attempt to infer better dtype for object columns Parameters ---------- datetime : boolean, default False If True, convert to date where possible. ...
java
@Override public Object set(int index, Object obj) { State state = isState(obj); return set(index, obj, state); }
python
def load_nddata(self, ndd, naxispath=None): """Load from an astropy.nddata.NDData object. """ self.clear_metadata() # Make a header based on any NDData metadata ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) ...
python
def wait_for_setting_value(self, section, setting, value, wait_time=5.0): """Function to wait wait_time seconds to see a SBP_MSG_SETTINGS_READ_RESP message with a user-specified value """ expire = time.time() + wait_time ok = False while not ok and time.time() < expire: ...
python
def display_bounding_boxes(img, blocks, alternatecolors=False, color=Color("blue")): """ Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ draw = Drawing() draw.fill_color = Col...
python
def sanitize_ssl(self): """Use local installed certificate file if available. Tries to get system, then certifi, then the own installed certificate file.""" if self["sslverify"] is True: try: self["sslverify"] = get_system_cert_file() except ValueE...
java
public Matrix4f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, thisOrNew()); }
java
public DateIterator getDateIterator(ICalDate startDate, TimeZone timezone) { RecurrenceIterator iterator = Google2445Utils.createRecurrenceIterator(this, startDate, timezone); return DateIteratorFactory.createDateIterator(iterator); }
python
def delete_resource(self, resource_id): """Link a resource to an individual.""" resource_obj = self.resource(resource_id) logger.debug("Deleting resource {0}".format(resource_obj.name)) self.session.delete(resource_obj) self.save()
python
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
java
@Override public void close() throws Exception { // flag this as not running any more isRunning = false; // clean up in locked scope, so there is no concurrent change to the stream and client synchronized (lock) { // we notify first (this statement cannot fail). The notified thread will not continue // ...
java
public int accumulatorInfoCountOfMap(String mapName) { ConcurrentMap<String, AccumulatorInfo> accumulatorInfo = cacheInfoPerMap.get(mapName); if (accumulatorInfo == null) { return 0; } else { return accumulatorInfo.size(); } }
java
public static int floorDiv(int x, int y) { int r = x / y; // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (r * y != x)) { r--; } return r; }
java
@Override public void setData(final Object data) { // This override is necessary to maintain other internal state String value = data == null ? null : data.toString(); // Empty date is treated as null if (Util.empty(value)) { value = null; } // Check valid format PartialDateFieldModel model = getOrC...
python
def masters(self): """Get an iterator over master UFOs that match the given family_name. """ if self._sources: for source in self._sources.values(): yield source.font return # Store set of actually existing master (layer) ids. This helps with ...
python
def entry(argv): ''' Command entry ''' command_dic = { 'init': run_init, } try: # 这里的 h 就表示该选项无参数,i:表示 i 选项后需要有参数 opts, args = getopt.getopt(argv, "hi:") except getopt.GetoptError: print('Error: helper.py -i cmd') sys.exit(2) for opt, arg in opt...
java
public void merge(Properties properties) throws PropertiesException { if(isLocked()) { throw new PropertiesException("properties map is locked, its contents cannot be altered."); } assert properties != null; for(Entry<String, String> entry : properties.entrySet()) { this.put(entry.getKey(), entry.getV...
python
def resolve_data_objects(objects, project=None, folder=None, batchsize=1000): """ :param objects: Data object specifications, each with fields "name" (required), "folder", and "project" :type objects: list of dictionaries :param project: ID of project context; a data object's project...
java
public void printStackTrace(PrintStream s) { if (!isJDK14OrAbove && causeOnJDK13OrBelow != null) { printStackTrace0(new PrintWriter(s)); } else { super.printStackTrace(s); } }
java
public void buildAnnotationTypeSummary(XMLNode node, Content summaryContentTree) { String annotationtypeTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Annotation_Types_Summary"), configuration.getText("doclet.anno...
python
def unlocked(self): """``True`` if achievement is unlocked. :rtype: bool """ achieved = CRef.cbool() result = self._iface.get_ach(self.name, achieved) if not result: return False return bool(achieved)
java
public static PreparedStatement createWayNodeTable(Connection connection, String wayNodeTableName) throws SQLException{ try (Statement stmt = connection.createStatement()) { StringBuilder sb = new StringBuilder("CREATE TABLE "); sb.append(wayNodeTableName); sb.append("(ID_WAY...
python
def _make_ip_subnet_lookup(vpc_info): """ Updates the vpc-info object with a lookup for IP -> subnet. """ # We create a reverse lookup from the instances private IP addresses to the # subnets they are associated with. This is used later on in order to # determine whether routes should be set in...
java
public Object parseAs(Type dataType) throws IOException { if (!hasMessageBody()) { return null; } return request.getParser().parseAndClose(getContent(), getContentCharset(), dataType); }
java
public void setCodeBuffer(CodeBuffer code) { mCodeBuffer = code; mOldLineNumberTable = mLineNumberTable; mOldLocalVariableTable = mLocalVariableTable; mOldStackMapTable = mStackMapTable; mAttributes.remove(mLineNumberTable); mAttributes.remove(mLocalVariableTable); ...
python
def _get_linear_lookup_table_and_weight(nbits, wp): """ Generate a linear lookup table. :param nbits: int Number of bits to represent a quantized weight value :param wp: numpy.array Weight blob to be quantized Returns ------- lookup_table: numpy.array Lookup table ...
python
def get_tcntobj(go2obj, **kws): """Return a TermCounts object if the user provides an annotation file, otherwise None.""" # kws: gaf gene2go annots = read_annotations(**kws) if annots: return TermCounts(go2obj, annots)
python
def fit_freq_min_max(self, training_signal): """Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_weight = sum(...
java
public Observable<ServiceResponse<UsagesResultInner>> getUsagesWithServiceResponseAsync(String resourceGroupName, String accountName, String filter) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } ...
python
def _create_figure(self): """ Create Matplotlib figure and axes """ # Good for development if get_option('close_all_figures'): plt.close('all') figure = plt.figure() axs = self.facet.make_axes( figure, self.layout.layout, ...
python
def legal_node_coords(): """ Return all legal node coordinates on the grid """ nodes = set() for tile_id in legal_tile_ids(): for node in nodes_touching_tile(tile_id): nodes.add(node) logging.debug('Legal node coords({})={}'.format(len(nodes), nodes)) return nodes
python
def register_dependency(self, data_src, data_sink): """ registers a dependency of data_src -> data_sink by placing appropriate entries in provides_for and depends_on """ pdebug("registering dependency %s -> %s" % (data_src, data_sink)) if (data_src not in self._gettask(data...
python
def set_flashing(self, duration, hsv1, hsv2): """Turn the bulb on, flashing with two colors.""" self.set_transition_time(100) for step in range(0, int(duration/2)): self.set_color_hsv(hsv1[0], hsv1[1], hsv1[2]) time.sleep(1) self.set_color_hsv(hsv2[0], hsv2[1]...
java
public void getLink(String path, final I_CmsStringCallback callback) { m_apiRoot.getRpcHelper().executeRpc(CmsXmlContentUgcApi.SERVICE.getLink(path, new AsyncCallback<String>() { @SuppressWarnings("synthetic-access") public void onFailure(Throwable caught) { m_apiRoot....
python
def set_name(self, name): """Set a client name.""" if not name: name = '' self._client['config']['name'] = name yield from self._server.client_name(self.identifier, name)
java
public static Method getAccessor(Class<?> clazz, String field) { LOG.trace( "getAccessor({}, {})", clazz, field ); try { return clazz.getMethod( "get" + ucFirst( field ) ); } catch ( NoSuchMethodException e ) { try { return clazz.getMethod( field ); ...
python
def find_reactions_with_identical_genes(model): """ Return reactions that have identical genes. Identify duplicate reactions globally by checking if any two reactions have the same genes. This can be useful to curate merged models or to clean-up bulk model modifications, but also to identify pr...
python
def context_by_id(self, context_id, via_id=None, create=True, name=None): """ Messy factory/lookup function to find a context by its ID, or construct it. This will eventually be replaced by a more sensible interface. """ context = self._context_by_id.get(context_id) if co...
java
public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append('('); for (int i = 0; i < argumentTypes.length; ++i) { argumentTypes[i].appendDescriptor(stringBuilder); } stringBuilder.append...
java
public static void runExample( AdManagerServices adManagerServices, AdManagerSession session, long placementId) throws RemoteException { // Get the PlacementService. PlacementServiceInterface placementService = adManagerServices.get(session, PlacementServiceInterface.class); // Create a...
java
public void setTags(java.util.Collection<TagRef> tags) { if (tags == null) { this.tags = null; return; } this.tags = new java.util.ArrayList<TagRef>(tags); }
java
public boolean containsMembers(Address ... mbrs) { if(mbrs == null || members == null) return false; for(Address mbr: mbrs) { if(!containsMember(mbr)) return false; } return true; }
java
private void readCrlf() throws IOException { final int crsymbol = this.origin.read(); final int lfsymbol = this.origin.read(); if (crsymbol != '\r' || lfsymbol != '\n') { throw new IOException( String.format( "%s %d%s%d", "CRLF ...
java
public ServiceFuture<List<DetectorResponseInner>> listSiteDetectorResponsesSlotAsync(final String resourceGroupName, final String siteName, final String slot, final ListOperationCallback<DetectorResponseInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listSiteDetectorResponsesSl...
java
public PExp caseABooleanPattern(ABooleanPattern node) throws AnalysisException { ABooleanConstExp b = new ABooleanConstExp(); b.setValue(node.getValue().clone()); addPossibleType(b, node); return b; }
java
List<W3CEndpointReference> lookupEndpoints(QName serviceName, MatcherDataType matcherData) throws ServiceLocatorFault, InterruptedExceptionFault { SLPropertiesMatcher matcher = createMatcher(matcherData); List<String> names = null; List<W3CEndpointReference> result = new ...
python
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs): """Evaluates the surfinBH7dq2 model. """ chiA = np.array(chiA) chiB = np.array(chiB) # Warn/Exit if extrapolating allow_extrap = kwargs.pop('allow_extrap', False) self._check_param_limits(q, chiA, chiB, a...
java
public ConnectionOptions withUri(URI uri) throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException { factory.setUri(Assert.notNull(uri, "URI")); return this; }
java
protected void storeCommon(Activation a, XMLStreamWriter writer) throws Exception { if (a.getBeanValidationGroups() != null && !a.getBeanValidationGroups().isEmpty()) { writer.writeStartElement(CommonXML.ELEMENT_BEAN_VALIDATION_GROUPS); for (int i = 0; i < a.getBeanValidationGroups().si...
java
@Override protected FileBasedReader<KV<K, V>> createSingleFileReader(PipelineOptions options) { Set<String> serializationNames = Sets.newHashSet( keySerializationClass.getName(), valueSerializationClass.getName() ); return new SeqFileReader<>(this, keyClass, valueClass, serializati...
python
def run(self): """Execute the process""" env = dict(os.environ) file_path = self.file.real_path path_folders = self.pycore.project.get_source_folders() + \ self.pycore.project.get_python_path_folders() env['PYTHONPATH'] = os.pathsep.join(folder.real_path ...
python
def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = doc[pno].getDisplayList() dlist = dlist_ta...
python
def balance(self, account): """ Return the balance, a tuple with the eth and ocn balance. :param account: Account instance to return the balance of :return: Balance tuple of (eth, ocn) """ return Balance(self._keeper.get_ether_balance(account.address), ...
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLEquivalentDataPropertiesAxiomImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
public void marshall(LoadBalancerTlsCertificateRenewalSummary loadBalancerTlsCertificateRenewalSummary, ProtocolMarshaller protocolMarshaller) { if (loadBalancerTlsCertificateRenewalSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try {...
java
public SelectStatement getPreparedSelectStatement(Query query, ClassDescriptor cld) { SelectStatement sql = new SqlSelectStatement(m_platform, cld, query, logger); if (logger.isDebugEnabled()) { logger.debug("SQL:" + sql.getStatement()); } return sql; ...
python
def labels(self): """Retrieve or set labels assigned to this bucket. See https://cloud.google.com/storage/docs/json_api/v1/buckets#labels .. note:: The getter for this property returns a dict which is a *copy* of the bucket's labels. Mutating that dict has no ef...
python
def run(config_file): """load the config, create a population, evolve and show the result""" # Load configuration. config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) # Create the population, which is the top-level object for...
python
def connect_success(self, connection_id): """ Check to see if the successful connection is meant to be peered with. If not, it should be used to get the peers from the endpoint. """ endpoint = self._network.connection_id_to_endpoint(connection_id) endpoint_info = self._te...
java
private static boolean checkAnnotation(AnnotationsAttribute invisible, AnnotationsAttribute visible, String annotationName) { boolean exist1 = false; boolean exist2 = false; if (invisible != null) { exist1 = invisible.getAnnotation(annotationName) != null; } ...
java
public synchronized void removeDeferredReferenceData(DeferredReferenceData refData) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "removeDeferredReferenceData", "this=" + this, refData); } if (deferredReferenceDatas != null) { deferred...
python
def get_quote_or_rt_text(tweet): """ Get the quoted or retweeted text in a Tweet (this is not the text entered by the posting user) - tweet: empty string (there is no quoted or retweeted text) - quote: only the text of the quoted Tweet - retweet: the text of the retweet Args: tweet ...
python
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = ...
python
def _nemo_accpars(self,vo,ro): """ NAME: _nemo_accpars PURPOSE: return the accpars potential parameters for use of this potential with NEMO INPUT: vo - velocity unit in km/s ro - length unit in kpc OUTPUT: accpars str...
java
public int read(byte[] b, int off, int len) throws IOException { int c = super.read(b, off, len); if( c == -1 && filenames.hasNext() ) { cueStream(); return read(b,off,len); } return c; }
python
def correctly_signed_message(self, decoded_xml, msgtype, must=False, origdoc=None, only_valid_cert=False): """Check if a request is correctly signed, if we have metadata for the entity that sent the info use that, if not use the key that are in the message if any. :param decoded_xml: Th...
java
public View waitForView(Object tag, int index, int timeout, boolean scroll){ //Because https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java#L17005-L17007 if(tag == null) { return null; } Set<View> uniqueViewsMatchingId = new HashSet<View>(); long endTime = Syste...
python
def get_editor_widget(self, request, plugins, plugin): """ Returns the Django form Widget to be used for the text area """ cancel_url_name = self.get_admin_url_name('delete_on_cancel') cancel_url = reverse('admin:%s' % cancel_url_name) render_plugin_url_name = se...
java
public void unintern(InternTable table) { // This implementation is inherited by Identifier and Literal which have no children, // but is overridden in Operator, which does. refCount--; if (refCount < 0) throw new IllegalStateException(); if (refCount == 0) { Object res = table.rem...
python
def scenario(ctx, dependency_name, driver_name, lint_name, provisioner_name, role_name, scenario_name, verifier_name): # pragma: no cover """ Initialize a new scenario for use with Molecule. """ command_args = { 'dependency_name': dependency_name, 'driver_name': driver_name, ...
java
public void set(String key, String value) { cache.put(key, value); user.sendGlobal("JWWF-storageSet", "{\"key\":" + Json.escapeString(key) + ",\"value\":" + Json.escapeString(value) + "}"); }
python
def dict_value_hint(key, mapper=None): """Returns a function that takes a dictionary and returns value of particular key. The returned value can be optionally processed by `mapper` function. To be used as a type hint in :class:`OneOf`. """ if mapper is None: mapper = identity def h...
python
def create_wiki(self, wiki_create_params, project=None): """CreateWiki. Creates the wiki resource. :param :class:`<WikiCreateParametersV2> <azure.devops.v5_0.wiki.models.WikiCreateParametersV2>` wiki_create_params: Parameters for the wiki creation. :param str project: Project ID or proje...
java
public RelationshipPrefetcher createRelationshipPrefetcher(ClassDescriptor anOwnerCld, String aRelationshipName) { ObjectReferenceDescriptor ord; ord = anOwnerCld.getCollectionDescriptorByName(aRelationshipName); if (ord == null) { ord = anOwnerCld.getObje...
python
def iteritems(self): """Iterator across all the non-duplicate keys and their values. Only yields the first key of duplicates. """ keys_yielded = set() for k, v in self._pairs: if k not in keys_yielded: keys_yielded.add(k) ...
python
def resnet_imagenet_34_td_unit_no_drop(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.0 hp.keep_prob = 1.0 return hp
java
public boolean setAttributes(IAttributeStore attributes) { int successes = 0; for (Map.Entry<String, Object> entry : attributes.getAttributes().entrySet()) { if (scope.setAttribute(entry.getKey(), entry.getValue())) { successes++; } } // expect eve...
python
def rank_velocity_genes(data, vkey='velocity', n_genes=10, groupby=None, match_with=None, resolution=None, min_counts=None, min_r2=None, min_dispersion=None, copy=False): """Rank genes for velocity characterizing groups. Arguments ---------- data : :class:`~anndata.AnnData` ...
python
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = e...
java
static boolean doesParameterTypesMatchForVarArgsInvocation(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) { if (isVarArgs && arguments != null && arguments.length >= 1 && parameterTypes != null && param...
python
def get_next_objective(self): """Gets the next Objective in this list. return: (osid.learning.Objective) - the next Objective in this list. The has_next() method should be used to test that a next Objective is available before calling this method. ...
python
def add_profile_point(self, value, source='', reference='', method='', ticket='', campaign=None, confidence=None, ...
java
public void commitStacktraceMD5() throws IOException, ServiceException { listEntry.getCustomElements().setValueLocal(AcraReportHeader.STACK_TRACE_MD5.tagName(), getStacktraceMD5()); listEntry.update(); }
python
def items(self): """Return result values""" if self._result_cache: return self._result_cache.items return self.all().items
python
def find_rt_jar(javahome=None): """Find the path to the Java standard library jar. The jar is expected to exist at the path 'jre/lib/rt.jar' inside a standard Java installation directory. The directory is found using the following procedure: 1. If the javehome argument is provided, use the value a...
java
private void processFailedBlocks(Block []failed, int failedPendingRequests) { synchronized (receivedAndDeletedBlockList) { // We are adding to the front of a linked list and hence to preserve // order we should add the blocks in the reverse order. for (int i = failed.length - 1; i >= 0; i--...
java
public boolean abuts(Interval other) { Objects.requireNonNull(other, "other"); return end.equals(other.start) ^ start.equals(other.end); }
java
public static CommercePriceList fetchByCompanyId_First(long companyId, OrderByComparator<CommercePriceList> orderByComparator) { return getPersistence() .fetchByCompanyId_First(companyId, orderByComparator); }
java
private int countLines() { InputStream is = IO.buffered(IO.inputStream(file)); try { byte[] c = new byte[1024]; int readChars = is.read(c); if (readChars == -1) { // bail out if nothing to read return 0; } // m...
java
public Observable<DiskInner> beginCreateOrUpdateAsync(String resourceGroupName, String diskName, DiskInner disk) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, diskName, disk).map(new Func1<ServiceResponse<DiskInner>, DiskInner>() { @Override public DiskInner cal...