language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void sendMessage(String handler, List<?> arguments) { if (so != null) { beginUpdate(); try { so.sendMessage(handler, arguments); } catch (Exception ex) { log.warn("Exception on so.sendMessage", ex); } finally { ...
java
private static void replaceWord(StringBuilder input, String word, String replace, boolean ignoreCase) { // The string where we look for (lower case if ignoreCase) StringBuilder workInput; // The string to find (lower case if ignoreCase) String workWord; if (input == null || word...
python
def on_connection_open_error(self, connection, error): """Invoked if the connection to RabbitMQ can not be made. :type connection: pika.TornadoConnection :param Exception error: The exception indicating failure """ LOGGER.critical('Could not connect to RabbitMQ (%s): %r', ...
java
@Override public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { JMeterVariables vars = getVariables(); String res = ((CompoundVariable) values[0]).execute().trim(); if (vars != null) { Object var = v...
python
def is_possible_number(numobj): """Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible...
java
private JsonObject createJson() { JsonObject json = new JsonObject(); addProperty(json, "cancel", cancel); addProperty(json, "continuous", continuous); addProperty(json, "filter", filter); if (queryParams != null) { json.add("query_params", queryParams); } ...
java
private <T> Provider<T> lookupProvider(Key<T> key) { BindingInject<T> bean = findBean(key); if (bean != null) { return bean.provider(); } BindingAmp<T> binding = findBinding(key); if (binding != null) { return binding.provider(); } binding = findObjectBinding(key); if ...
java
protected ClusterMutex getClusterMutexInternal(final String mutexName) { final TransactionOperations transactionOperations = this.getTransactionOperations(); return transactionOperations.execute( new TransactionCallback<ClusterMutex>() { @Override ...
python
def nvmlDeviceSetDriverModel(handle, model): r""" /** * Set the driver model for the device. * * For Fermi &tm; or newer fully supported devices. * For windows only. * Requires root/admin permissions. * * On Windows platforms the device driver can run in either WDDM or WDM (TC...
java
public java.util.List<String> getTargetIds() { if (targetIds == null) { targetIds = new com.amazonaws.internal.SdkInternalList<String>(); } return targetIds; }
java
protected final String shaveOffNonJavaIdentifierStartChars( String str ) { String str2 = str; // shave off first char if not valid boolean ready = false; while( !ready ){ if( !Character.isJavaIdentifierStart( str2.charAt( 0 ) ) ){ str2 = str2.substring( 1 ); if( ...
python
def remove_this_predicateAnchor(self,predAnch_id): """ Removes the predicate anchor for the given predicate anchor identifier @type predAnch_id: string @param predAnch_id: the predicate anchor identifier to be removed """ for predAnch in self.get_predicateAnchors(): ...
java
private boolean isElementPresent_internal() throws WidgetException { try { try { final boolean isPotentiallyXpathWithLocator = (locator instanceof EByFirstMatching) || (locator instanceof EByXpath); if (isPotentiallyXpathWithLocator && isElementPresentJavaXPath()) return true; }...
python
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): """This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined...
java
public static ChainableStatement attr(String key, JsScope computedValue) { return new DefaultChainableStatement("attr", JsUtils.quotes(key), computedValue.render()); }
java
public void deletePushRules(Object projectIdOrPath) throws GitLabApiException { delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "push_rule"); }
java
public static ByteBuffer slice(ByteBuffer buffer, int length) { final int l = buffer.limit(); buffer.limit(buffer.position() + length); final ByteBuffer slice = buffer.slice(); buffer.limit(l); buffer.position(buffer.position() + length); return slice; }
python
def union(self, other, ignore_conflicts=False): """Return a new definition from the union of the definitions.""" result = self.copy() result.union_update(other, ignore_conflicts) return result
python
def index(self, fields, name=None, table=None, **kwargs): ''' Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param coll...
python
def get_distutils_display_options(): """ Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form d...
python
def instance_contains(container, item): """Search into instance attributes, properties and return values of no-args methods.""" return item in (member for _, member in inspect.getmembers(container))
python
def pp_xml(body): """Pretty print format some XML so it's readable.""" pretty = xml.dom.minidom.parseString(body) return pretty.toprettyxml(indent=" ")
java
public void defineField(int modifier, String fieldName, Class<?> type) { defineField(modifier, fieldName, Typ.getTypeFor(type)); }
python
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to str. The string format is specified by the 'format' parameter. Parameters ---------- format : str The format to output the string. Default format is "...
java
public ListRet listLive(String prefix, int limit, String marker) throws PiliException { return list(true, prefix, limit, marker); }
python
def _check_request(self): '''Check new task queue''' # check _postpone_request first todo = [] for task in self._postpone_request: if task['project'] not in self.projects: continue if self.projects[task['project']].task_queue.is_processing(task['ta...
java
@WithBridgeMethods(value = OracleQuery.class, castRequired = true) public C orderSiblingsBy(Expression<?> path) { return addFlag(Position.BEFORE_ORDER, ORDER_SIBLINGS_BY, path); }
java
public SIBUuid12 getStreamID() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getStreamID"); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getStreamID", _streamSet.getStreamID()); return _streamSet.getStreamID(); ...
java
private boolean isDownloadPDF(Map<String, String> map) { return StringUtils.hasText(map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR)) && map.get(RequestElements.REQ_PARAM_ENTITY_SELECTOR).equalsIgnoreCase(ContentTypes.PDF.name()); }
python
def clean(self): """drop regularization and prior information observation from the jco """ if self.pst_arg is None: self.logger.statement("linear_analysis.clean(): not pst object") return if not self.pst.estimation and self.pst.nprior > 0: self.drop_pr...
python
def consultar_numero_sessao(self, numero_sessao): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_numero_sessao`. :return: Uma resposta SAT que irá depender da sessão consultada. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('consultarnumerosessao', ...
java
public static GsonBuilder registerDuration(GsonBuilder builder) { if (builder == null) { throw new NullPointerException("builder cannot be null"); } builder.registerTypeAdapter(DURATION_TYPE, new DurationConverter()); return builder; }
java
@Test public void MPJwtNoMpJwtConfig_formLoginInWebXML_notInApp() throws Exception { genericLoginConfigFormLoginVariationTest( MpJwtFatConstants.LOGINCONFIG_FORM_LOGIN_IN_WEB_XML_SERVLET_NOT_IN_APP_ROOT_CONTEXT, ...
python
def ceph_is_installed(module): """ A helper callback to be executed after the connection is made to ensure that Ceph is installed. """ ceph_package = Ceph(module.conn) if not ceph_package.installed: host = module.conn.hostname raise RuntimeError( 'ceph needs to be ins...
python
def encode(self, data, size): """ Encode a stream of bytes into an armoured string. Returns the armoured string, or NULL if there was insufficient memory available to allocate a new string. """ return return_fresh_string(lib.zarmour_encode(self._as_parameter_, data, size))
python
def ndiagquad(funcs, H: int, Fmu, Fvar, logspace: bool=False, **Ys): """ Computes N Gaussian expectation integrals of one or more functions using Gauss-Hermite quadrature. The Gaussians must be independent. :param funcs: the integrand(s): Callable or Iterable of Callables that operates elementw...
java
@Override public CreateProductResult createProduct(CreateProductRequest request) { request = beforeClientExecution(request); return executeCreateProduct(request); }
java
public void addFileRepositoryCollectionClass( Class<? extends FileRepositoryCollection> clazz, Set<String> fileExtensions) { for (String extension : fileExtensions) { fileRepositoryCollections.put(extension.toLowerCase(), clazz); } }
python
def _default_output_dir(): """Default output directory.""" try: dataset_name = gin.query_parameter("inputs.dataset_name") except ValueError: dataset_name = "random" dir_name = "{model_name}_{dataset_name}_{timestamp}".format( model_name=gin.query_parameter("train.model").configurable.name, d...
python
def TrimVariableTable(self, new_size): """Trims the variable table in the formatted breakpoint message. Removes trailing entries in variables table. Then scans the entire breakpoint message and replaces references to the trimmed variables to point to var_index of 0 ("buffer full"). Args: new...
python
def _tag_cmds(self, *cmds): """ Yields tagged commands. """ for (method, args) in cmds: tagged_cmd = [method, args, self._tag] self._tag = self._tag + 1 yield tagged_cmd
java
public CompiledScript compile(String scriptSource) throws ScriptException { try { return new GroovyCompiledScript(this, getScriptClass(scriptSource)); } catch (SyntaxException e) { throw new ScriptException(e.getMessage(), e.getSourceLocato...
python
def session(self) -> BaseFileWriterSession: '''Return the File Writer Session.''' return self.session_class( self._path_namer, self._file_continuing, self._headers_included, self._local_timestamping, self._adjust_extension, self._co...
python
def decrypt(text): 'Decrypt a string using an encryption key based on the django SECRET_KEY' crypt = EncryptionAlgorithm.new(_get_encryption_key()) return crypt.decrypt(text).rstrip(ENCRYPT_PAD_CHARACTER)
java
public boolean isSupported(ICalVersion version) { for (ICalVersion supportedVersion : supportedVersions) { if (supportedVersion == version) { return true; } } return false; }
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ opt = "incremental"...
java
public static InsnList tryCatchBlock(TryCatchBlockNode tryCatchBlockNode, Type exceptionType, InsnList tryInsnList, InsnList catchInsnList) { Validate.notNull(tryInsnList); // exceptionType can be null Validate.notNull(catchInsnList); if (exceptionType != null) { ...
python
def _recall_prec(self, record, count): """ get recall and precision from internal records """ record = np.delete(record, np.where(record[:, 1].astype(int) == 0)[0], axis=0) sorted_records = record[record[:,0].argsort()[::-1]] tp = np.cumsum(sorted_records[:, 1].astype(int) == 1) ...
python
def filter(self, **filters): """ Add a filter to this query. Appends to any previous filters set. :rtype: Query """ q = self._clone() for key, value in filters.items(): filter_key = re.split('__', key) filter_attr = filter_key[0] ...
python
def detect_unused_return_values(self, f): """ Return the nodes where the return value of a call is unused Args: f (Function) Returns: list(Node) """ values_returned = [] nodes_origin = {} for n in f.nodes: for ir in ...
python
def set_policy(self, name, rules): """Add a new or update an existing policy. Once a policy is updated, it takes effect immediately to all associated users. Supported methods: PUT: /sys/policy/{name}. Produces: 204 (empty body) :param name: Specifies the name of the policy...
java
public static double max(DoubleTuple t) { return DoubleTupleFunctions.reduce( t, Double.NEGATIVE_INFINITY, Math::max); }
java
public Observable<Map<String,Object>> getUserData(BackendUser backendUser){ return getWebService().getUserData(isLoggedIn(), backendUser.getOwnerId() + "") .subscribeOn(config.subscribeOn()).observeOn(config.observeOn()); }
python
def generate_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (deva...
java
public static base_responses unset(nitro_service client, String prefix[], String args[]) throws Exception { base_responses result = null; if (prefix != null && prefix.length > 0) { nsxmlnamespace unsetresources[] = new nsxmlnamespace[prefix.length]; for (int i=0;i<prefix.length;i++){ unsetresources[i] = n...
python
def get_coeffs(expr, expand=False, epsilon=0.): """Create a dictionary with all Operator terms of the expression (understood as a sum) as keys and their coefficients as values. The returned object is a defaultdict that return 0. if a term/key doesn't exist. Args: expr: The operator express...
java
public Observable<ServiceResponse<List<DetectedFace>>> detectWithUrlWithServiceResponseAsync(String url, DetectWithUrlOptionalParameter detectWithUrlOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and c...
python
def on_server_start(self): """Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts. """ self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params) self.sig...
python
def dstationarystate(self, k, param): """See docs for `Model` abstract base class.""" assert param not in self.distributionparams assert param in self.freeparams or param == self.distributedparam ds = self._models[k].dstationarystate(param) return ds
python
def d2Sbr_dV2(Cbr, Ybr, V, lam): """ Computes 2nd derivatives of complex power flow w.r.t. voltage. """ nb = len(V) diaglam = spdiag(lam) diagV = spdiag(V) A = Ybr.H * diaglam * Cbr B = conj(diagV) * A * diagV D = spdiag(mul((A*V), conj(V))) E = spdiag(mul((A.T * conj(V)), V)) ...
java
public static <S, E> void applyAll(Query filterTree, GraphTraversal<S, E> q) { if (filterTree == null) { return; } QueryTranslationState state = new QueryTranslationState(); applyAll(filterTree, q, false, state); }
java
@Nullable @SuppressWarnings("unchecked") // findPathToEnclosing guarantees that the type is from |classes| @SafeVarargs public final <T extends Tree> T findEnclosing(Class<? extends T>... classes) { TreePath pathToEnclosing = findPathToEnclosing(classes); return (pathToEnclosing == null) ? null : (T) path...
java
@GetMapping("/employees/{id}") public EntityModel<Employee> findOne(@PathVariable Integer id) { Class<EmployeeController> controllerClass = EmployeeController.class; // Start the affordance with the "self" link, i.e. this method. Link findOneLink = linkTo(methodOn(controllerClass).findOne(id)).withSelfRel(); /...
java
@RequestMapping(value = "api/servergroup", method = RequestMethod.POST) public @ResponseBody ServerGroup createServerGroup(Model model, @RequestParam(value = "name") String name, @RequestParam(value = "profileId", required = false) Integer ...
java
@SuppressWarnings("unchecked") public String getDisplayName(boolean setAttr) throws Exception { String displayName = null; String securityName = getSecurityName(false); displayName = getDisplayNameForEntity(securityName); if (!((displayName == null) || (displayName.trim().length() =...
java
@Override public void finishStage(ResponseBuilder rb) { // System.out // .println(System.nanoTime() + " - " + Thread.currentThread().getId() // + " - " + rb.req.getParams().getBool(ShardParams.IS_SHARD, false) // + " FINISHRESPONSES " + rb.stage + " " + rb.req.getParamString()); MtasSolrStatus solrStatu...
java
public static FilterCriteriaType createAndRegister(String name, boolean collection, boolean map) { FilterCriteriaType type = create(name, collection, map); register(type); return type; }
java
@Override public ListIPSetsResult listIPSets(ListIPSetsRequest request) { request = beforeClientExecution(request); return executeListIPSets(request); }
java
@Override public <SN,N,V> MutationResult insert(final K key, final String cf, final HSuperColumn<SN,N,V> superColumn) { addInsertion(key, cf, superColumn); return execute(); }
java
public GetPersonTrackingResult withPersons(PersonDetection... persons) { if (this.persons == null) { setPersons(new java.util.ArrayList<PersonDetection>(persons.length)); } for (PersonDetection ele : persons) { this.persons.add(ele); } return this; }
java
public static CPInstance fetchByC_ST_First(long CPDefinitionId, int status, OrderByComparator<CPInstance> orderByComparator) { return getPersistence() .fetchByC_ST_First(CPDefinitionId, status, orderByComparator); }
python
def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requirements of all the types of the resource. """ rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id==resource_attr...
python
def add(self, host, filename, data, f_type, f_other_type=None, f_text=''): """ Add evidence :param host: db.t_hosts.id :param filename: Filename :param data: Content of file :param f_type: Evidence type :param f_other_type: If f_type is 'Other' what type it is ...
java
public void setNS(java.util.Collection<String> nS) { if (nS == null) { this.nS = null; return; } java.util.List<String> nSCopy = new java.util.ArrayList<String>(nS.size()); nSCopy.addAll(nS); this.nS = nSCopy; }
java
@Override public void write(byte[] bts) throws IOException { try { int len = bts != null ? bts.length : 0; beforeWrite(len); out.write(bts); afterWrite(len); } catch (IOException e) { handleIOException(e); } }
java
@Override public boolean matches(IAtom atom) { String symbol = atom.getSymbol(); int group = PeriodicTable.getGroup(symbol); return group == this.groupNumber; }
java
@Nullable public static InputStream getMappedInputStream (@Nonnull final File aFile) { ValueEnforcer.notNull (aFile, "File"); // Open regular final FileInputStream aFIS = FileHelper.getInputStream (aFile); if (aFIS == null) return null; // Try to memory map it final InputStream aIS =...
java
private Statement renderCallNode( Label parametersReattachPoint, CallNode node, Expression calleeExpression) { Statement initAppendable = Statement.NULL_STATEMENT; Statement clearAppendable = Statement.NULL_STATEMENT; Expression appendable; FieldRef currentCalleeField = variables.getCurrentCalleeF...
python
def generate_authors(git_dir): """Create AUTHORS file using git commits.""" authors = [] emails = [] git_log_cmd = ['git', 'log', '--format=%aN|%aE'] tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n') for author_str in tmp_authors: author, email = author_str.split('|') ...
java
@Pure public boolean contains(FunctionalPoint3D point) { return containsTrianglePoint( this.getP1().getX(), this.getP1().getY(), this.getP1().getZ(), this.getP2().getX(), this.getP2().getY(), this.getP2().getZ(), this.getP3().getX(), this.getP3().getY(), this.getP3().getZ(), point.getX(), point.get...
java
public ShippingAddress getShippingAddress(final String accountCode, final long shippingAddressId) { return doGET(Accounts.ACCOUNTS_RESOURCE + "/" + accountCode + ShippingAddresses.SHIPPING_ADDRESSES_RESOURCE + "/" + shippingAddressId, ShippingAddress.class); }
java
public Observable<OrchestratorVersionProfileListResultInner> listOrchestratorsAsync(String location) { return listOrchestratorsWithServiceResponseAsync(location).map(new Func1<ServiceResponse<OrchestratorVersionProfileListResultInner>, OrchestratorVersionProfileListResultInner>() { @Override ...
java
public static base_responses update(nitro_service client, vpnsessionaction resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { vpnsessionaction updateresources[] = new vpnsessionaction[resources.length]; for (int i=0;i<resources.length;i++){ updat...
python
def get_apps_json(self, url, timeout, auth, acs_url, ssl_verify, tags, group): """ The dictionary containing the apps is cached during collection and reset at every `check()` call. """ if self.apps_response is not None: return self.apps_response # Marathon ap...
python
def is_state(self, state): """ Test if this conversation is in the given state. """ state = state.format(relation_name=self.relation_name) value = _get_flag_value(state) if not value: return False return self.key in value['conversations']
python
def squeeze(self): """ Remove single-dimensional axes from images. """ axis = tuple(range(1, len(self.shape) - 1)) if prod(self.shape[1:]) == 1 else None return self.map(lambda x: x.squeeze(axis=axis))
java
@Patch public OperationOutcome patientPatch(@IdParam IdType theId, PatchTypeEnum thePatchType, @ResourceParam String theBody) { if (thePatchType == PatchTypeEnum.JSON_PATCH) { // do something } if (thePatchType == PatchTypeEnum.XML_PATCH) { // do something } OperationOutcome retVal = new OperationO...
java
public static SoyValue applyPrintDirective( SoyJavaPrintDirective directive, SoyValue value, List<SoyValue> args) { value = value == null ? NullData.INSTANCE : value; for (int i = 0; i < args.size(); i++) { if (args.get(i) == null) { args.set(i, NullData.INSTANCE); } } return d...
java
@Override public void updateStatisticOnRequest(int dataId) { if(si!=null){ SessionStats temp =SessionMonitor.getSessionStatsOB(si.getName()); if (dataId == ACTIVE_SESSIONS) { activeCount.set(temp.getActiveCount()); } if (dataId == LIVE_SESSIONS...
java
public final void commitInternal(final PersistentTransaction transaction) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "commitInternal", transaction); getLink().internalCommitAdd(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())...
java
public static Method getSAMMethod(Class<?> c) { // SAM = single public abstract method // if the class is not abstract there is no abstract method if (!Modifier.isAbstract(c.getModifiers())) return null; if (c.isInterface()) { Method[] methods = c.getMethods(); //...
python
def loadFromStream(self, stream, name=None): """Return a WSDL instance loaded from a stream object.""" document = DOM.loadDocument(stream) wsdl = WSDL() if name: wsdl.location = name elif hasattr(stream, 'name'): wsdl.location = stream.name wsdl.lo...
python
def _has_actions(self, event): """Check if a notification type has any enabled actions.""" event_actions = self._aconfig.get(event) return event_actions is None or bool(event_actions)
java
private IAuthorizationPrincipal[] getPrincipalsFromPermissions(IPermission[] permissions) throws AuthorizationException { Set principals = new HashSet(); for (int i = 0; i < permissions.length; i++) { IAuthorizationPrincipal principal = getPrincipal(permissions[i]); p...
java
public void assign(final cern.colt.function.DoubleFunction function) { copy().forEachPair( new cern.colt.function.IntDoubleProcedure() { public boolean apply(int key, double value) { put(key,function.apply(value)); return true; } } ); }
python
def job(): "Generate a job title, http://www.cubefigures.com/job.html" j1 = random.choice(phrases.jobs1) j2 = random.choice(phrases.jobs2) j3 = random.choice(phrases.jobs3) return '%s %s %s' % (j1, j2, j3)
java
private <S, E1, E2> GraphTraversal<S, E2> choose( GraphTraversal<S, E1> traversal, GraphTraversal<E1, ?> traversalPredicate, GraphTraversal<E1, ? extends E2> trueChoice, GraphTraversal<E1, ? extends E2> falseChoice) { // This is safe. The generics for `GraphTraversal#choose` are more re...
java
protected static void append(StringBuilder builder, String caption, Object value) { builder.append(caption).append(StrUtil.nullToDefault(Convert.toStr(value), "[n/a]")).append("\n"); }
java
public static Key of(Object... values) { // A literal Key.of(null) results in a null array being passed. Provide a clearer error. checkNotNull( values, "'values' cannot be null. For a literal key containing a single null value, " + "call Key.of((Object) null)."); Builder b = ne...
java
public FieldCounter<Double> extract(String jsonString, String recordId) { return extract(jsonString, recordId, false); }