language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mRecyclerView == null) { return; } final int count = mRecyclerView.getAdapter().getItemCount(); if (count == 0) { return; } // mCurrentPage is -1 on first star...
python
def create_main_synopsis(self, parser): """ create synopsis from main parser """ self.add_usage(parser.usage, parser._actions, parser._mutually_exclusive_groups, prefix='') usage = self._format_usage(None, parser._actions, parser._mutuall...
python
def update_or_append_line(filename, prefix, new_line, keep_backup=True, append=True): '''Search in file 'filename' for a line starting with 'prefix' and replace the line by 'new_line'. If a line starting with 'prefix' not exists 'new_line' will be appended. If the file not exi...
python
def _query(self): # pylint: disable=E0202 """ Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`. """ formated_property_names = ",".join(self.property_names) wql = "Select {property_names} from {class_name}{f...
python
def accept(self): """Accept a connection. The socket must be bound to an address and listening for connections. The return value is a new socket object usable to send and receive data on the connection.""" socket = Socket(self._llc, None) socket._tco = self.llc.accept(sel...
java
private boolean visitColumnsAndColumnFacets(VisitContext context, VisitCallback callback, boolean visitRows) { if (visitRows) { setRowIndex(-1); } if (getChildCount() > 0) { fo...
java
private static boolean isInternetReachable() { try { final URL url = new URL("http://www.google.com"); final HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection(); urlConnect.setConnectTimeout(1000); urlConnect.getContent(); urlCon...
python
def serialize_bytes(data): """Write bytes by using Telegram guidelines""" if not isinstance(data, bytes): if isinstance(data, str): data = data.encode('utf-8') else: raise TypeError( 'bytes or str expected, not {}'.format(type(d...
java
public static String normalize(String path) { if (path == null) { return null; } // 兼容Spring风格的ClassPath路径,去除前缀,不区分大小写 String pathToUse = StrUtil.removePrefixIgnoreCase(path, URLUtil.CLASSPATH_URL_PREFIX); // 去除file:前缀 pathToUse = StrUtil.removePrefixIgnoreCase(pathToUse, URLUtil.FILE_URL_PREFIX...
java
protected void fillResource(CmsObject cms, Element element, CmsResource res) { String xpath = element.getPath(); int pos = xpath.lastIndexOf("/" + XmlNode.GroupContainers.name() + "/"); if (pos > 0) { xpath = xpath.substring(pos + 1); } CmsRelationType type = getHand...
java
public static List<String> childrenText(Element parentElement, String tagname) { final Iterable<Element> children = children(parentElement, tagname); List<String> result = new ArrayList<String>(); for (Element element : children) { result.add(elementText(element)); } ...
python
def _get_migrate_funcs(cls, orig_version, target_version): """ >>> @Manager.register ... def v1_to_2(manager, doc): ... doc['foo'] = 'bar' >>> @Manager.register ... def v2_to_1(manager, doc): ... del doc['foo'] >>> @Manager.register ... def v2_to_3(manager, doc): ... doc['foo'] = doc['fo...
python
def _update_noise(self, peak_num): """ Update live noise parameters """ i = self.peak_inds_i[peak_num] self.noise_amp_recent = (0.875*self.noise_amp_recent + 0.125*self.sig_i[i]) return
python
def setup(self): """Setup.""" self.context_visible_first = self.config['context_visible_first'] self.delimiters = [] self.escapes = None self.line_endings = self.config['normalize_line_endings'] escapes = [] for delimiter in self.config['delimiters']: ...
python
def set_display_name(self, display_name): """Sets a display name. A display name is required and if not set, will be set by the provider. arg: display_name (string): the new display name raise: InvalidArgument - ``display_name`` is invalid raise: NoAccess - ``Metad...
python
def clean_sequences(self): """Removes reads/contigs that contain plasmids, and masks phage sequences.""" logging.info('Removing plasmids and masking phages') plasmid_db = os.path.join(self.reffilepath, 'plasmidfinder', 'plasmid_database.fa') phage_db = os.path.join(self.reffilepath, 'pro...
python
def network_profiles(self): """Instance depends on the API version: * 2018-08-01: :class:`NetworkProfilesOperations<azure.mgmt.network.v2018_08_01.operations.NetworkProfilesOperations>` """ api_version = self._get_api_version('network_profiles') if api_version == '2018-08-01'...
java
public boolean unresolveType(final Class<? extends Entity> type) { return resolved.remove(Objects.requireNonNull(type)) != null; }
python
def wait_for_ready(self, instance_id, limit=14400, delay=10, pending=False): """Determine if a Server is ready. A server is ready when no transactions are running on it. :param int instance_id: The instance ID with the pending transaction :param int limit: The maximum amount of seconds...
java
private void updateTail() { // Either tail already points to an active node, or we keep // trying to cas it to the last node until it does. Node<E> t, p, q; restartFromTail: while ((t = tail).item == null && (p = t.next) != null) { for (;;) { if ((q = ...
java
private static Set<CmsResource> getAllResourcesInModule(CmsObject cms, CmsModule module) throws CmsException { Set<CmsResource> result = new HashSet<>(); for (CmsResource resource : CmsModule.calculateModuleResources(cms, module)) { result.add(resource); if (resource.isFolder())...
java
public DescribeWorkspaceImagesResult withImages(WorkspaceImage... images) { if (this.images == null) { setImages(new com.amazonaws.internal.SdkInternalList<WorkspaceImage>(images.length)); } for (WorkspaceImage ele : images) { this.images.add(ele); } retur...
python
def get_all_build_configs_by_labels(self, label_selectors): """ Returns all builds matching a given set of label selectors. It is up to the calling function to filter the results. """ labels = ['%s=%s' % (field, value) for field, value in label_selectors] labels = ','.joi...
python
def generate_cache_key(value): """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(to_bytes(text=value)) elif is_boolean(value) or is_null(value) or is_number(value): ...
java
public static MappedByteBuffer mapExistingFile( final File location, final String descriptionLabel, final long offset, final long length) { return mapExistingFile(location, READ_WRITE, descriptionLabel, offset, length); }
python
def collect_vocab(qp_pairs): ''' Build the vocab from corpus. ''' vocab = set() for qp_pair in qp_pairs: for word in qp_pair['question_tokens']: vocab.add(word['word']) for word in qp_pair['passage_tokens']: vocab.add(word['word']) return vocab
python
def string_tokenizer(self, untokenized_string: str, include_blanks=False): """ This function is based off CLTK's line tokenizer. Use this for strings rather than .txt files. input: '20. u2-sza-bi-la-kum\n1. a-na ia-as2-ma-ah-{d}iszkur#\n2. qi2-bi2-ma\n3. um-ma {d}utu-szi-{d}iszk...
python
def getTraitCovarStdErrors(self,term_i): """ Returns standard errors on trait covariances from term_i (for the covariance estimate \see getTraitCovar) Args: term_i: index of the term we are interested in """ assert self.init, 'GP not initialised' a...
java
private String getAbsoluteName() { File f = getAbsoluteFile(); String name = f.getPath(); if (f.isDirectory() && name.charAt(name.length() - 1) != separatorChar) { // Directories must end with a slash name = name + "/"; } if (separatorChar != '/') { // Mus...
java
public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; this.xmlReader.setResourceLoader(resourceLoader); this.scanner.setResourceLoader(resourceLoader); }
python
def _set_base_dn(self): """Get Base DN from LDAP""" results = self._search( 'cn=config', '(objectClass=*)', ['nsslapd-defaultnamingcontext'], scope=ldap.SCOPE_BASE ) if results and type(results) is list: dn, attrs = results[0] ...
java
protected boolean invisibleHydrogen(IAtom atom, RendererModel model) { return isHydrogen(atom) && !(Boolean) model.get(ShowExplicitHydrogens.class); }
python
def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T: """From json string to instance :param data: Json string :param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True :param force_cast: Cast forcib...
java
public static void addJob( String jobName, Class<? extends Job> jobClass, Map<String, Object> params, boolean isConcurrencyAllowed) throws SundialSchedulerException { try { JobDataMap jobDataMap = new JobDataMap(); if (params != null) { for (Entry<String,...
python
def prior_tuples(self): """ Returns ------- priors: [(String, Prior))] """ return [prior for tuple_prior in self.tuple_prior_tuples for prior in tuple_prior[1].prior_tuples] + self.direct_prior_tuples + [prior for prior_model in ...
java
public void marshall(EsamManifestConfirmConditionNotification esamManifestConfirmConditionNotification, ProtocolMarshaller protocolMarshaller) { if (esamManifestConfirmConditionNotification == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try {...
python
def disable(self): """Disables the entity at this endpoint.""" self.post("disable") if self.service.restart_required: self.service.restart(120) return self
java
public void put(String keyStr, SoyData value) { List<String> keys = split(keyStr, '.'); int numKeys = keys.size(); CollectionData collectionData = this; for (int i = 0; i <= numKeys - 2; ++i) { SoyData nextSoyData = collectionData.getSingle(keys.get(i)); if (nextSoyData != null && !(nextS...
java
public synchronized Widget measureChild(final int dataIndex, boolean calculateOffset) { Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "measureChild dataIndex = %d", dataIndex); Widget widget = mContainer.get(dataIndex); if (widget != null) { synchronized (mMeasuredChildren) { mMe...
java
public int getRowStart(int rowIndex) { if (isCompacted) { throw new IllegalStateException( "Illegal Invocation of the method after compact()"); } if (rowIndex < 0 || rowIndex > rows) { throw new IllegalArgumentException("rowIndex out of bound!"); ...
python
def handle_onchain_secretreveal( target_state: TargetTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, ) -> TransitionResult[TargetTransferState]: """ Validates and handles a ContractReceiveSecretReveal state change. """ valid_secret = is_valid...
python
def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. """ if isinstance(s, binary_type): s = s.decode('latin-1') if not isinstance(s...
python
def register_model(self, model): """ Register ``model`` to this group :param model: model name :return: None """ assert isinstance(model, str) if model not in self.all_models: self.all_models.append(model)
python
def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(al...
java
public ResultList<Keyword> getTVKeywords(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.KEYWORDS).buildUrl(parameters); WrapperGenericList<Keyword> wrap...
python
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationEr...
java
private static boolean parseInputArgs(String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(OPTIONS, args); } catch (ParseException e) { System.out.println("Failed to parse input args: " + e); return false; } sHelp = cmd.hasO...
python
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield ...
java
public GetAggregateConfigRuleComplianceSummaryResult withAggregateComplianceCounts(AggregateComplianceCount... aggregateComplianceCounts) { if (this.aggregateComplianceCounts == null) { setAggregateComplianceCounts(new com.amazonaws.internal.SdkInternalList<AggregateComplianceCount>(aggregateComplia...
java
public static Pipeline watchers(MavenSession session, File baseDir, Mojo mojo, boolean pomFileMonitoring) { return new Pipeline(mojo, baseDir, Watchers.all(session), pomFileMonitoring); }
java
public static <T extends UIObject> String animate(final T widget, final String animation, final int count) { return animate(widget, animation, count, -1, -1); }
java
public JsStatement warningDialog(String message) { JsStatement statement = new JsStatement(); statement.append("$.ui.dialog.wiquery.warningDialog("); statement.append("" + Session.get().nextSequenceValue() + ", "); statement.append(DialogUtilsLanguages.getDialogUtilsLiteral(DialogUtilsLanguages .getDialogUt...
java
public static byte[] getBytes(Object obj) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); oos.close(); bos.close(); byte[] data = bos.toByteArray(); return data; }
python
def rlmf_tictactoe(): """Base set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.game = "tictactoe" hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0" # Since we don't have any no-op actions, otherwise we have to have an # attribute called `get_action_meanings`. hparams.eval_max_num_noops...
python
def _check_markers(task_ids, offset=10): """Returns a flag for markers being found for the task_ids. If all task ids have markers True will be returned. Otherwise it will return False as soon as a None result is hit. """ shuffle(task_ids) has_errors = False for index in xrange(0, len(task_...
java
protected Long doResourceReplayCachedContent( IPortletWindow portletWindow, HttpServletRequest httpServletRequest, CacheState<CachedPortletResourceData<Long>, Long> cacheState, PortletResourceOutputHandler portletOutputHandler, long baseExecutionTime) ...
java
static boolean polygonRelateMultiPoint_(Polygon polygon_a, MultiPoint multipoint_b, double tolerance, String scl, ProgressTracker progress_tracker) { RelationalOperationsMatrix relOps = new RelationalOperationsMatrix(); relOps.resetMatrix_(); relOps.setPredicates_(scl); relOps.setAreaPointPredicates_(); ...
python
def set_censor(self, character): """Replaces the original censor character '*' with ``character``.""" # TODO: what if character isn't str()-able? if isinstance(character, int): character = str(character) self._censor_char = character
python
def prepare_for_submission(self, folder): """This method is called prior to job submission with a set of calculation input nodes. The inputs will be validated and sanitized, after which the necessary input files will be written to disk in a temporary folder. A CalcInfo instance will be returned...
python
def coerce_many(schema=str): """Expect the input to be a sequence of items which conform to `schema`.""" def validate(val): """Apply schema check/version to each item.""" return [volup.Coerce(schema)(x) for x in val] return validate
python
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
python
def get_surface_as_bytes(self, order=None): """Returns the surface area as a bytes encoded RGB image buffer. Subclass should override if there is a more efficient conversion than from generating a numpy array first. """ arr8 = self.get_surface_as_array(order=order) return...
java
public com.google.api.ads.adwords.axis.v201809.cm.BudgetBudgetDeliveryMethod getDeliveryMethod() { return deliveryMethod; }
java
private double initScore() { double score = 0; final int n = atoms.length; for (int i = 0; i < n; i++) { final Point2d p1 = atoms[i].getPoint2d(); for (int j = i + 1; j < n; j++) { if (contribution[i][j] < 0) continue; final Point2d p2 = at...
java
@Override public final IoBuffer putDouble(int index, double value) { autoExpand(index, 8); buf().putDouble(index, value); return this; }
java
public JobDetails getJobByJobID(String cluster, String jobId) throws IOException { return getJobByJobID(cluster, jobId, false); }
java
public void addFile(String zipEntry, byte[] data) throws IOException { stream.putNextEntry(new ZipEntry(zipEntry)); stream.write(data); }
python
def refresh(func): """ Decorator that can be applied to model method that forces a refresh of the model. Note this decorator ensures the state of the model is what is currently within the database and therefore overwrites any current field changes. For example, assume we have the following...
python
def restrict(self, ava, sp_entity_id, metadata=None): """ Identity attribute names are expected to be expressed in the local lingo (== friendlyName) :return: A filtered ava according to the IdPs/AAs rules and the list of required/optional attributes according to the SP. ...
java
public DataSetBuilder sequence(String column, Timestamp initial, long step) { ensureArgNotNull(initial); return sequence(column, initial, ts -> new Timestamp(ts.getTime() + step)); }
java
public static SimpleModule getModule(final ObjectMapper mapper) { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDe...
python
def xview(self, *args): """Update inplace widgets position when doing horizontal scroll""" self.after_idle(self.__updateWnds) ttk.Treeview.xview(self, *args)
python
def GetDataAsObject(self): """Retrieves the data as an object. Returns: object: data as a Python type or None if not available. Raises: WinRegistryValueError: if the value data cannot be read. """ if not self._data: return None if self._data_type in self._STRING_VALUE_TYPES:...
java
public boolean beforeUpdateAll(Class<?> clazz, String sql, List<String> customsSets, List<Object> customsParams, List<Object> args) { return true; }
java
public static CommercePriceEntry removeByC_ERC(long companyId, String externalReferenceCode) throws com.liferay.commerce.price.list.exception.NoSuchPriceEntryException { return getPersistence().removeByC_ERC(companyId, externalReferenceCode); }
java
public void highlightElement() { if (m_highlighting == null) { m_highlighting = new CmsHighlightingBorder(m_position, CmsHighlightingBorder.BorderColor.red); RootPanel.get().add(m_highlighting); } else { m_highlighting.setPosition(CmsPositionBean.getBoundingClientRec...
java
private static IndexedInts getRow(ColumnValueSelector s) { if (s instanceof DimensionSelector) { return ((DimensionSelector) s).getRow(); } else if (s instanceof NilColumnValueSelector) { return ZeroIndexedInts.instance(); } else { throw new ISE( "ColumnValueSelector[%s], only ...
python
def complex_median(complex_list): """ Get the median value of a list of complex numbers. Parameters ---------- complex_list: list List of complex numbers to calculate the median. Returns ------- a + 1.j*b: complex number The median of the real and imaginary parts. """ ...
python
def updateSocialTone(user, socialTone, maintainHistory): """ updateSocialTone updates the user with the social tones interpreted based on the specified thresholds @param user a json object representing user information (tone) to be used in conversing with the Conversation Service @param socialTo...
java
@Deprecated public List<List<String>> getParsedArgs(String[] args) throws InvalidFormatException { for (int i = 0; i < args.length; i++) { if (!args[i].startsWith("-")) { if (this.params.size() > 0) { List<String> option = new ArrayList<String>(); option.add(this.params.get(0).longOption); t...
java
@BetaApi public final HealthCheck getHealthCheck(ProjectGlobalHealthCheckName healthCheck) { GetHealthCheckHttpRequest request = GetHealthCheckHttpRequest.newBuilder() .setHealthCheck(healthCheck == null ? null : healthCheck.toString()) .build(); return getHealthCheck(request)...
python
def del_svc_comment(self, comment_id): """Delete a service comment Format of the line that triggers function call:: DEL_SVC_COMMENT;<comment_id> :param comment_id: comment id to delete :type comment_id: int :return: None """ for svc in self.daemon.servic...
java
private boolean skipBlankAndComma() { boolean commaFound = false; while (!isEOS()) { int c = str.charAt(idx); if (c == ',') { if (commaFound) return true; else commaFound = true; ...
java
public boolean update(String tableName, Record record) { return update(tableName, config.dialect.getDefaultPrimaryKey(), record); }
java
private SAXParserFactory getSAXParserFactory() { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(this.namespaceAware); factory.setSchema(this.schema); return factory; }
python
def get(self, section, key): """get function reads the config value for the requested section and key and returns it Parameters: * **section (string):** the section to look for the config value either - oxd, client * **key (string):** the key for the config value require...
java
private File subDirForId(String id) { File subDir = new File(objs, id.substring(0, SUBDIR_POLICY)); if (!subDir.exists()) { subDir.mkdirs(); } return subDir; }
python
def parse_qaml(self): """ Parse the GenomeQAML report, and populate metadata objects """ logging.info('Parsing GenomeQAML outputs') # A dictionary to store the parsed excel file in a more readable format nesteddictionary = dict() # Use pandas to read in the CSV fi...
python
def url_for(*args, **kw): """Build the URL for a target route. The target is the first positional argument, and can be any valid target for `Mapper.path`, which will be looked up on the current mapper object and used to build the URL for that route. Additionally, it can be one o...
python
def _get_provisioning_state(self, response): """ Attempt to get provisioning state from resource. :param requests.Response response: latest REST call response. :returns: Status if found, else 'None'. """ if self._is_empty(response): return None body = ...
python
def waiver2mef(sciname, newname=None, convert_dq=True, writefits=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ if isinstance(sciname, fits.HDUList): ...
python
def endpoint_delete(endpoint_id): """ Executor for `globus endpoint delete` """ client = get_client() res = client.delete_endpoint(endpoint_id) formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
java
private void runTasks() { // Execute any tasks that were queue during execution of the command. if (!tasks.isEmpty()) { for (Runnable task : tasks) { log.trace("Executing task {}", task); task.run(); } tasks.clear(); } }
python
def set_layer(self, layer=None, keywords=None): """Set layer and update UI accordingly. :param layer: A QgsVectorLayer. :type layer: QgsVectorLayer :param keywords: Keywords for the layer. :type keywords: dict, None """ if self.field_mapping_widget is not None: ...
java
public List<String> getLockedResources(CmsDbContext dbc, CmsResource resource, CmsLockFilter filter) throws CmsException { List<String> lockedResources = new ArrayList<String>(); // get locked resources Iterator<CmsLock> it = m_lockManager.getLocks(dbc, resource.getRootPath(), filter).itera...
java
public static byte[] executeJsp( CmsObject cms, HttpServletRequest request, HttpServletResponse response, CmsResource jsp, CmsResource content) throws Exception { CmsTemplateLoaderFacade loaderFacade = new CmsTemplateLoaderFacade( OpenCms.getResourceManager()...
python
def gen_schema(data, **options): """ Generate a node represents JSON schema object with type annotation added for given object node. :param data: Configuration data object (dict[-like] or namedtuple) :param options: Other keyword options such as: - ac_schema_strict: True if more strict (pr...
java
public static Matrix random(int M, int N) { Matrix A = new Matrix(M, N); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { A.data[i][j] = Math.random(); } } return A; }
python
def update_probes(self, progress): """ update the probe tree """ new_values = self.read_probes.probes_values probe_count = len(self.read_probes.probes) if probe_count > self.tree_probes.topLevelItemCount(): # when run for the first time, there are no probes i...
java
public String getDisplayName(TextStyle style, Locale locale) { return new DateTimeFormatterBuilder().appendChronologyText(style).toFormatter(locale).format(new DefaultInterfaceTemporalAccessor() { @Override public boolean isSupported(TemporalField field) { return false; ...