language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static String verifyReadFile(File file){ if (file == null){ return "The file is null."; } String absolutePath=file.getAbsolutePath(); if (!file.exists()){ return "The path '"+absolutePath+"' do not exits."; } if (!file.isFile()){ return "The path '"+absolutePath+"' is not a file...
java
public Set<String> names() { TreeSet<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (int i = 0, size = size(); i < size; i++) { result.add(name(i)); } return Collections.unmodifiableSet(result); }
python
def full_url(self): """Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object) """ if self.link == '': return None else: return Note._expand_url(self.link, self.sub...
python
def emoticons(string): '''emot.emoticons is use to detect emoticons from text >>> text = "I love python 👨 :-)" >>> emot.emoticons(text) >>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True} ''' __entities = [] flag = True try: p...
python
def basic_dependencies(self): """ Accesses basic dependencies from the XML output :getter: Returns the dependency graph for basic dependencies :type: corenlp_xml.dependencies.DependencyGraph """ if self._basic_dependencies is None: deps = self._element.xpath...
java
public void close() throws IOException { for (;;) { int state = this.state; if (isClosed(state)) { return; } // Once a close operation happens, the channel is considered shutdown. if (casState(state, state | STATE_ALL_MASK)) { ...
java
public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { while(true) { RangeMember best = findBestMember(); if(best == null) { throw new ResourceIndexNotAvailableException("Unable to find active...
python
def led_control_encode(self, target_system, target_component, instance, pattern, custom_len, custom_bytes): ''' Control vehicle LEDs target_system : System ID (uint8_t) target_component : Component ID (uint8_t) instanc...
java
public static QName tagToQName(final String tag, final Map<String, String> nsRegistry) { final String[] split = tag.split("\\:"); if (split.length <= 1) { return new QName(split[0]); } else { final String namespace = nsRegistry.get(split[0]); if (namespace != null) { return new QName(namespace, ...
java
public long write(short type, byte[][] data) throws InterruptedException, IOException { try { return super.put(type, data, true); } catch (InterruptedException e) { throw e; } catch (IOException e) { throw e; } catch (Throwable e) { ...
java
synchronized public OpenFileInfo[] iterativeGetOpenFiles( String prefix, int millis, String startAfter) { final long thresholdMillis = System.currentTimeMillis() - millis; // this flag is for subsequent calls that included a 'start' // parameter. in those cases, we need to throw out the first ...
python
def fill(duration, point): """ fills the subsequence of the point with repetitions of its subsequence and sets the ``duration`` of each point. """ point['sequence'] = point['sequence'] * (point[DURATION_64] / (8 * duration)) | add({DURATION_64: duration}) return point
python
def correct_html(self, root, children, div_math, insert_idx, text): """Separates out <div class="math"> from the parent tag <p>. Anything in between is put into its own parent tag of <p>""" current_idx = 0 for idx in div_math: el = markdown.util.etree.Element('p') ...
python
def get_by_id(self, id, change_notes=False): """ Get a :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Collection` by id :param (str) id: integer id of the :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Concept` :return: corresponding :class:`skosprovider.skos.C...
python
def dumps(cls, obj, protocol=0): """ Equivalent to pickle.dumps except that the HoloViews option tree is saved appropriately. """ cls.save_option_state = True val = pickle.dumps(obj, protocol=protocol) cls.save_option_state = False return val
python
def _run_serial_ops(state): ''' Run all ops for all servers, one server at a time. ''' for host in list(state.inventory): host_operations = product([host], state.get_op_order()) with progress_spinner(host_operations) as progress: try: _run_server_ops( ...
python
def _deep_value(*args, **kwargs): """ Drills down into tree using the keys """ node, keys = args[0], args[1:] for key in keys: node = node.get(key, {}) default = kwargs.get('default', {}) if node in ({}, [], None): node = default return node
java
public Criteria startsWith(Iterable<String> values) { Assert.notNull(values, "Collection must not be null"); for (String value : values) { startsWith(value); } return this; }
java
public static XID parse(String idString) { UUID uuid = UUID.fromString(idString); return new XID(uuid); }
python
def addproperties( names, bfget=None, afget=None, enableget=True, bfset=None, afset=None, enableset=True, bfdel=None, afdel=None, enabledel=True ): """Decorator in charge of adding python properties to cls. {a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matchin...
python
def complex_type(name=None): '''Decorator for registering complex types''' def wrapped(cls): ParseType.type_mapping[name or cls.__name__] = cls return cls return wrapped
java
private Object execute(Object o, Method m, Object... args) throws CommandActionExecutionException { Object result = null; try { m.setAccessible(true); // suppress Java language access if (isCompileWeaving() && metaHolder.getAjcMethod() != null) { result = invokeAj...
java
@Override public String quit() { checkIsInMultiOrPipeline(); client.quit(); String quitReturn = client.getStatusCodeReply(); client.disconnect(); return quitReturn; }
java
public static FsPermission deserializeWriterDirPermissions(State state, int numBranches, int branchId) { return new FsPermission(state.getPropAsShortWithRadix( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId), FsPermission.getDefault().toSho...
python
def _get_version(): """Return the project version from VERSION file.""" with open(os.path.join(os.path.dirname(__file__), PACKAGE_NAME, 'VERSION'), 'rb') as f: version = f.read().decode('ascii').strip() return version
java
public Structure getStructureForDomain(String scopId) throws IOException, StructureException { return getStructureForDomain(scopId, ScopFactory.getSCOP()); }
python
def forms(self, req, tag): """ Make and return some forms, using L{self.parameter.getInitialLiveForms}. @return: some subforms. @rtype: C{list} of L{LiveForm} """ liveForms = self.parameter.getInitialLiveForms() for liveForm in liveForms: liveForm.set...
java
@Override public boolean isValidGroup(String groupSecurityName) throws RegistryException { for (UserRegistry registry : delegates) { if (registry.isValidGroup(groupSecurityName)) { return true; } } return false; }
python
def map_cluster(events, cluster): """ Maps the cluster hits on events. Not existing hits in events have all values set to 0 """ cluster = np.ascontiguousarray(cluster) events = np.ascontiguousarray(events) mapped_cluster = np.zeros((events.shape[0], ), dtype=dtype_from_descr(data_struct.Cluster...
java
public void setResources(java.util.Collection<String> resources) { if (resources == null) { this.resources = null; return; } this.resources = new java.util.ArrayList<String>(resources); }
python
def salt(self): """ Generates a salt via pgcrypto.gen_salt('algorithm'). """ cursor = connections[PGCRYPTOAUTH_DATABASE].cursor() cursor.execute("SELECT gen_salt('%s')" % PGCRYPTOAUTH_ALGORITHM) return cursor.fetchall()[0][0]
java
@Override public synchronized void onFileCreate(File file) { final Set<DetectedWebJar> listOfDetectedWebJarLib = isWebJar(file); if (listOfDetectedWebJarLib != null) { JarFile jar = null; try { jar = new JarFile(file); List<FileWebJarLib> insta...
java
public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) { super.parse(iRequest); final int pos = parseFields(); if (pos == -1) throw new OCommandSQLParsingException("Traverse must have the field list. Use " + getSyntax()); int endPosition = text.length(); int endP = ...
java
private static Object injectAndPostConstruct(Object injectionProvider, Class Klass, List injectedBeanStorage) { Object instance = null; if (injectionProvider != null) { try { Object managedObject = _FactoryFinderProviderFactory.INJECTION_PROVIDER_INJE...
java
public static <A,S> Transition<A,S> create(S fromState, A action, S toState){ return new Transition<A, S>(fromState, action, toState); }
java
public Observable<ServiceResponse<HybridConnectionLimitsInner>> getHybridConnectionPlanLimitWithServiceResponseAsync(String resourceGroupName, String name) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } ...
python
def k_to_R_value(k, SI=True): r'''Returns the R-value of a substance given its thermal conductivity, Will return R-value in SI units unless SI is false. SI units are m^2 K/(W*inch); Imperial units of R-value are ft^2 deg F*h/(BTU*inch). Parameters ---------- k : float Thermal conductivi...
python
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceContext for this WorkspaceInstance :rtype: twilio.rest.taskrouter.v1.workspace.Workspace...
java
@Override public CreateBranchResult createBranch(CreateBranchRequest request) { request = beforeClientExecution(request); return executeCreateBranch(request); }
python
def locale_negotiator(request): """Locale negotiator base on the `Accept-Language` header""" locale = 'en' if request.accept_language: locale = request.accept_language.best_match(LANGUAGES) locale = LANGUAGES.get(locale, 'en') return locale
python
def connect_host(kwargs=None, call=None): ''' Connect the specified host system in this VMware environment CLI Example: .. code-block:: bash salt-cloud -f connect_host my-vmware-config host="myHostSystemName" ''' if call != 'function': raise SaltCloudSystemExit( 'T...
python
def _load_report(infile): '''Loads report file into a dictionary. Key=reference name. Value = list of report lines for that reference''' report_dict = {} f = pyfastaq.utils.open_file_read(infile) first_line = True for line in f: line = line.rstrip() ...
python
def _update_indexes_for_mutated_object(collection, obj): """If an object is updated, this will simply remove it and re-add it to the indexes defined on the collection.""" for index in _db[collection].indexes.values(): _remove_from_index(index, obj) _add_to_index(index, obj)
python
def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg)
python
def resize_matrix(usv, num_rows, num_cols): """Apply algorith 2 in https://arxiv.org/pdf/1901.08910.pdf. Args: usv: matrix to reduce given in SVD form with the spectrum s in increasing order. num_rows: number of rows in the output matrix. num_cols: number of columns in the output matrix. Return...
java
public static Class<?> getCollectionFieldType(Field collectionField, int nestingLevel) { return ResolvableType.forField(collectionField).getNested(nestingLevel).asCollection().resolveGeneric(); }
java
public static void logNoMoreArticles(final Logger logger, final ArchiveDescription archive) { logger.logMessage(Level.INFO, "Archive " + archive.toString() + " contains no more articles"); }
java
public static void initiateInstance(final String title, final String styleName) { INSTANCE = new ColorPicker(styleName, title, null); }
java
private synchronized Object invokeTarget(Object base, Object[] pars) throws Throwable { Reflect.logInvokeMethod("Invoking method (entry): ", this, pars); List<Object> params = collectParamaters(base, pars); Reflect.logInvokeMethod("Invoking method (after): ", this, params); i...
java
public List<Presence> getAvailablePresences(BareJid bareJid) { List<Presence> allPresences = getAllPresences(bareJid); List<Presence> res = new ArrayList<>(allPresences.size()); for (Presence presence : allPresences) { if (presence.isAvailable()) { // No need to clone...
java
private <T> Observable<PollingState<T>> updateStateFromAzureAsyncOperationHeaderOnPostOrDeleteAsync(final PollingState<T> pollingState) { return pollAsync(pollingState.azureAsyncOperationHeaderLink(), pollingState.loggingContext()) .flatMap(new Func1<Response<ResponseBody>, Observable<PollingSta...
java
public static byte[] i2cWriteRequest(byte slaveAddress, byte... bytesToWrite) { byte[] result = new byte[bytesToWrite.length * 2 + 5]; result[0] = START_SYSEX; result[1] = I2C_REQUEST; result[2] = slaveAddress; result[3] = I2C_WRITE; //TODO replace I2C_WRITE with generate...
python
def _init_map(self): """stub""" self.my_osid_object_form._my_map['zoneConditions'] = \ self._zone_conditions_metadata['default_object_values'][0] self.my_osid_object_form._my_map['coordinateConditions'] = \ self._coordinate_conditions_metadata['default_object_values'][0] ...
java
public int bump(CmsUUID id) { CmsDetailPageInfo info = m_infoById.get(id); if (info == null) { throw new IllegalArgumentException(); } String type = info.getType(); List<CmsDetailPageInfo> infos = m_map.get(type); int oldPos = infos.indexOf(info); inf...
java
private static void setupContextClassLoader(GroovyShell shell) { final Thread current = Thread.currentThread(); class DoSetContext implements PrivilegedAction { ClassLoader classLoader; public DoSetContext(ClassLoader loader) { classLoader = loader; }...
java
public static <K> void validateConfiguredTypes(CacheConfig cacheConfig, K key) throws ClassCastException { Class keyType = cacheConfig.getKeyType(); validateConfiguredKeyType(keyType, key); }
python
def send_email_sns(sender, subject, message, topic_ARN, image_png): """ Sends notification through AWS SNS. Takes Topic ARN from recipients. Does not handle access keys. Use either 1/ configuration file 2/ EC2 instance profile See also https://boto3.readthedocs.io/en/latest/guide/configur...
python
def list_ikepolicies(self, retrieve_all=True, **_params): """Fetches a list of all configured IKEPolicies for a project.""" return self.list('ikepolicies', self.ikepolicies_path, retrieve_all, **_params)
python
def user_process(self, input_data): """ :param input_data: :return: output_data, list of next model instance. For example, if model is :class:`~crawl_zillow.model.State`, then next model is :class:`~crawl_zillow.model.County`. """ url = input_data.doc.url ...
java
public Data readAsData(long sequence) { checkReadSequence(sequence); Object rbItem = readOrLoadItem(sequence); return serializationService.toData(rbItem); }
python
def _set_platform_specific_keyboard_shortcuts(self): """ QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts. This means that all default key combinations ("Save", "Quit", etc) have to be defined in code. """ self.action_new_phrase.setShort...
java
void submitForm(CmsForm formParam, final Map<String, String> fieldValues, Set<String> editedFields) { String modelGroupId = null; if (CmsInheritanceContainerEditor.getInstance() != null) { CmsInheritanceContainerEditor.getInstance().onSettingsEdited(); } if (m_contextsWidge...
java
public static BufferedImage resize(BufferedImage src, int targetSize, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException { return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize, targetSize, ops); }
python
def models_get(self, resource_url): """Get handle for model resource at given Url. Parameters ---------- resource_url : string Url for subject resource at SCO-API Returns ------- models.ModelHandle Handle for local copy of subject resourc...
java
PageFlowController popUntil( HttpServletRequest request, Class stopAt, boolean onlyIfPresent ) { if (onlyIfPresent && lastIndexOf(stopAt) == -1) { return null; } while ( ! isEmpty() ) { PageFlowController popped = pop( request ).getPageFlow(); ...
java
public static String unescape(String input, char escapeCharacter) { if (input == null) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < input.length(); ) { if (input.charAt(i) == escapeCharacter) { builder.append(input.charAt(i + 1))...
java
@Transactional @Override public PrincipalUser findUserByUsername(String userName) { requireNotDisposed(); requireArgument(userName != null && !userName.trim().isEmpty(), "User name cannot be null or empty."); PrincipalUser result = PrincipalUser.findByUserName(emf.get(), userName); ...
python
async def _read_messages(self): """Process messages received on the WebSocket connection. Iteration terminates when the client is stopped or it disconnects. """ while not self._stopped and self._websocket is not None: async for message in self._websocket: if ...
java
public Double getDouble(String column) { Number n = getNumber(column); return n != null ? n.doubleValue() : null; }
java
public static DataSet newDataSet(final String keyColumnName, final String valueColumnName, final Map<?, ?> m) { final List<Object> keyColumn = new ArrayList<>(m.size()); final List<Object> valueColumn = new ArrayList<>(m.size()); for (Map.Entry<?, ?> entry : m.entrySet()) { key...
python
def ng_set_ctrl_property(self, element, prop, value): """ :Description: Will set value of property of element's controller. :Warning: This will only work for angular.js 1.x. :Warning: Requires angular debugging to be enabled. :param element: Element for browser instance to target...
java
@SuppressWarnings("PMD.PreserveStackTrace") public Object extractObject(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts,boolean jsonify) throws AttributeNotFoundException { CompositeData cd = (CompositeData) pValue; String pathPart = pPathPa...
python
def seek(self, offset: int = 0, *args, **kwargs): """ A shortcut to ``self.fp.seek``. """ return self.fp.seek(offset, *args, **kwargs)
python
def Run(self, args): """Reads a buffer on the client and sends it to the server.""" # Make sure we limit the size of our output if args.length > constants.CLIENT_MAX_BUFFER_SIZE: raise RuntimeError("Can not read buffers this large.") data = vfs.ReadVFS(args.pathspec, args.offset, args.length) ...
java
public void marshall(UpdateIndexingConfigurationRequest updateIndexingConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (updateIndexingConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
java
@Override public Stream<Chunk<byte[], BytesReference>> chunks() { Iterator<Chunk<byte[], BytesReference>> iterator = new Iterator<Chunk<byte[], BytesReference>>() { Chunk<byte[], BytesReference> nextData = null; @Override public boolean hasNext() { if (ne...
java
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case XtypePackage.XFUNCTION_TYPE_REF__PARAM_TYPES: return ((InternalEList<?>)getParamTypes()).basicRemove(otherEnd, msgs); case XtypePackage.XFUNCTION_TYPE_REF__RETUR...
python
def unders_to_dashes_in_keys(self) -> None: """Replaces underscores with dashes in key names. For each attribute in a mapping, this replaces any underscores \ in its keys with dashes. Handy because Python does not \ accept dashes in identifiers, while some YAML-based formats use \ ...
python
def MakeProto(): """Make sure our protos have been compiled to python libraries.""" # Start running from one directory above the grr directory which is found by # this scripts's location as __file__. cwd = os.path.dirname(os.path.abspath(__file__)) # Find all the .proto files. protos_to_compile = [] for ...
python
def element_href_use_filter(name, _filter): """ Get element href using filter Filter should be a valid entry point value, ie host, router, network, single_fw, etc :param name: name of element :param _filter: filter type, unknown filter will result in no matches :return: element href (if found)...
java
protected void findRoot(Collection<CmsResource> resources) throws CmsException { m_commonRoot = getCommonSite(resources); String commonPath = getCommonAncestorPath(resources); try { m_rootResource = m_cms.readResource(m_commonRoot, m_filter); } catch (CmsVfsResourceNot...
java
private List<String> pruneSuggestions(final List<String> suggestions) { List<String> prunedSuggestions = new ArrayList<>(suggestions.size()); for (final String suggestion : suggestions) { if (suggestion.indexOf(' ') == -1) { prunedSuggestions.add(suggestion); } else { Str...
python
def _InvokeGitkitApi(self, method, params=None, need_service_account=True): """Invokes Gitkit API, with optional access token for service account. Args: method: string, the api method name. params: dict of optional parameters for the API. need_service_account: false if service account is not ...
java
public VarBindingDef bind( VarDef varDef, VarValueDef valueDef) { if( valueDef != null && !varDef.isApplicable( valueDef)) { throw new IllegalArgumentException( "Value=" + valueDef + " is not defined for var=" + varDef); } varDef_ = varDef; valueDef_ = valueDef; effCondition_ ...
java
public ApiResponse<List<CharacterContractsBidsResponse>> getCharactersCharacterIdContractsContractIdBidsWithHttpInfo( Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token) throws ApiException { com.squareup.okhttp.Call call = getCharactersCharacter...
java
public static <E> Object result(final Iterable<E> iterable, final Predicate<E> pred) { for (E element : iterable) { if (pred.test(element)) { if (element instanceof Map.Entry) { if (((Map.Entry) element).getValue() instanceof Supplier) { re...
java
public Matrix4f translation(Vector3fc offset) { return translation(offset.x(), offset.y(), offset.z()); }
java
public static P<String> fullTextMatch(String configuration,final String value){ return fullTextMatch(configuration,false, value); }
python
def get_field_kwargs(self, field_name, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everyth...
python
def __dict_to_pod_spec(spec): ''' Converts a dictionary into kubernetes V1PodSpec instance. ''' spec_obj = kubernetes.client.V1PodSpec() for key, value in iteritems(spec): if hasattr(spec_obj, key): setattr(spec_obj, key, value) return spec_obj
java
public ModuleInfoList filter(final ModuleInfoFilter filter) { final ModuleInfoList moduleInfoFiltered = new ModuleInfoList(); for (final ModuleInfo resource : this) { if (filter.accept(resource)) { moduleInfoFiltered.add(resource); } } return modul...
java
public static int findFirstNotOf(String container, String chars, int begin){ //find the first occurrence of characters not in the charSeq from begin forward for (int i = begin; i < container.length() && i >=0; ++i) if (!chars.contains("" + container.charAt(i))) return i; return -1; }
python
def set_burnstages_upgrade_massive(self): ''' Outputs burnign stages as done in burningstages_upgrade (nugridse) ''' burn_info=[] burn_mini=[] for i in range(len(self.runs_H5_surf)): sefiles=se(self.runs_H5_out[i]) burn_info.append(sefiles.burnstage_upgrade()) ...
java
public List<GitlabGroupMember> getGroupMembers(Integer groupId) { String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabGroupMember.URL + PARAM_MAX_ITEMS_PER_PAGE; return retrieve().getAll(tailUrl, GitlabGroupMember[].class); }
java
@Provides protected RendererAdapter<TvShowViewModel> provideTvShowRendererAdapter( LayoutInflater layoutInflater, TvShowCollectionRendererBuilder tvShowCollectionRendererBuilder, TvShowCollectionViewModel tvShowCollectionViewModel) { return new RendererAdapter<TvShowViewModel>(layoutInflater, tvSh...
java
public static int getHFTACount(File fileLocation) { Document qtree = getQTree(fileLocation); int count; count = qtree.getElementsByTagName("HFTA").getLength(); return count; }
python
def fetch(self, keyDict): """Like update(), but for retrieving values. """ for key in keyDict.keys(): keyDict[key] = self.tbl[key]
python
def _delete_collection(self, **kwargs): """wrapped with delete_collection, override that in a sublcass to customize """ error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg" try: if kwargs['requests_params']['params'].split(...
java
static public ObjectName registerMBean(final String serviceName, final String nameName, final Object theMbean) { final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = getMBeanName(serviceName, nameName); try { mbs.registerMBean(theMbean, name); ...
java
public void push(String name, String value, long timestamp) throws IOException { graphiteSender.send(name, value, timestamp); }