language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void updatePropertiesInternal( Iterable<Property> properties, Iterable<PropertyDeleteMutation> propertyDeleteMutations, Iterable<PropertySoftDeleteMutation> propertySoftDeleteMutations ) { if (propertyDeleteMutations != null) { this.propertyDeleteMutations = new...
python
def bind_sockets( port: int, address: str = None, family: socket.AddressFamily = socket.AF_UNSPEC, backlog: int = _DEFAULT_BACKLOG, flags: int = None, reuse_port: bool = False, ) -> List[socket.socket]: """Creates listening sockets bound to the given port and address. Returns a list of ...
python
def get(orcid_id): """ Get an author based on an ORCID identifier. """ resp = requests.get(ORCID_PUBLIC_BASE_URL + unicode(orcid_id), headers=BASE_HEADERS) json_body = resp.json() return Author(json_body)
java
@Override protected void handleEvents(final String EVENT_TYPE) { super.handleEvents(EVENT_TYPE); if ("RECALC".equals(EVENT_TYPE)) { range = gauge.getRange(); angleStep = -ANGLE_RANGE / range; redraw(); } else if ("VISIBILITY".equals(EVENT_TYPE)) { ...
java
private static boolean isLogicalListType(Type listType) { return !listType.isPrimitive() && listType.getOriginalType() != null && listType.getOriginalType().equals(OriginalType.LIST) && listType.asGroupType().getFieldCount() == 1 && listType.asGroupType().getFields().ge...
python
def set_mask_selection(self, selection, value, fields=None): """Modify a selection of individual items, by providing a Boolean array of the same shape as the array against which the selection is being made, where True values indicate a selected item. Parameters ---------- ...
python
def get_aggregation_propensity(self, seq, outdir, cutoff_v=5, cutoff_n=5, run_amylmuts=False): """Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity. Args: seq (str, Seq, SeqRecord): Amino acid sequence outdir (str): Direc...
python
def check_bot(task_type=SYSTEM_TASK): """ wxpy bot 健康检查任务 """ if glb.wxbot.bot.alive: msg = generate_run_info() message = Message(content=msg, receivers='status') glb.wxbot.send_msg(message) _logger.info( '{0} Send status message {1} at {2:%Y-%m-%d %H:%M:%S}'....
python
def vi_scale_score(self,x): """ The score of the scale, where scale = exp(x) - used for variational inference Parameters ---------- x : float A random variable Returns ---------- The gradient of the scale latent variable at x """ retu...
java
private static StringBuffer doAppendComment(StringBuffer buffer, String comment) { buffer.append(SEQUENCE__COMMENT__OPEN).append(comment).append(SEQUENCE__COMMENT__CLOSE); return buffer; }
python
def search(self, search_phrase, limit=None): """Search for datasets, and expand to database records""" from ambry.identity import ObjectNumber from ambry.orm.exc import NotFoundError from ambry.library.search_backends.base import SearchTermParser results = [] stp = Sear...
python
def from_hive_file(cls, fname, *args, **kwargs): """ Open a local JSON hive file and initialize from the hive contained in that file, paying attention to the version keyword argument. """ version = kwargs.pop('version', None) require = kwargs.pop('require_https', True) ...
java
public void marshall(CreateFunctionRequest createFunctionRequest, ProtocolMarshaller protocolMarshaller) { if (createFunctionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createFunctionRe...
python
def get_inner_keys(dictionary): """Gets 2nd-level dictionary keys :param dictionary: dict :return: inner keys """ keys = [] for key in dictionary.keys(): inner_keys = dictionary[key].keys() keys += [ key + " " + inner_key # concatenate for inner_key in...
python
def rightsibling(node): """ Return Right Sibling of `node`. >>> from anytree import Node >>> dan = Node("Dan") >>> jet = Node("Jet", parent=dan) >>> jan = Node("Jan", parent=dan) >>> joe = Node("Joe", parent=dan) >>> rightsibling(dan) >>> rightsibling(jet) Node('/Dan/Jan') >...
python
def Exp(self, m=None): """Exponentiates the probabilities. m: how much to shift the ps before exponentiating If m is None, normalizes so that the largest prob is 1. """ if not self.log: raise ValueError("Pmf/Hist not under a log transform") self.log = False ...
java
public static CompoundTag readFile(String path, boolean compressed, boolean littleEndian) throws IOException { return readFile(new File(path), compressed, littleEndian); }
python
def load_settings(file_path, module_name='', secret_key=''): ''' a method to load data from json valid files :param file_path: string with path to settings file :param module_name: [optional] string with name of module containing file path :param secret_key: [optional] string with key to decrypt...
java
public Optional<Issue> getOptionalIssue(Object projectIdOrPath, Integer issueIid) { try { return (Optional.ofNullable(getIssue(projectIdOrPath, issueIid))); } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } }
python
def update(self, data_set): """ Refresh the time of all specified elements in the supplied data set. """ now = time.time() for d in data_set: self.timed_data[d] = now self._expire_data()
java
public List<String> getExtraFieldNames() { List<String> result = new ArrayList<String>(); for (Method method : getExtraFieldMethods()) { ExtraField extraField = method.getAnnotation( ExtraField.class ); result.add( extraField.value() ); } return resu...
python
def encode_kv_node(keypath, child_node_hash): """ Serializes a key/value node """ if keypath is None or keypath == b'': raise ValidationError("Key path can not be empty") validate_is_bytes(keypath) validate_is_bytes(child_node_hash) validate_length(child_node_hash, 32) return KV_...
python
def ifilterfalse_items(item_iter, flag_iter): """ ifilterfalse_items Args: item_iter (list): flag_iter (list): of bools Example: >>> # ENABLE_DOCTEST >>> from utool.util_iter import * # NOQA >>> item_iter = [1, 2, 3, 4, 5] >>> flag_iter = [False, True, ...
java
private Node getNonProxyNode(IndexHits<Node> nodesFound) { Node node = null; if (nodesFound.hasNext()) { node = nodesFound.next(); } else { return null; } try { Object proxyNodeProperty = node.getProperty(PR...
python
def summarize(self): """Convert all of the values to their max values. This form is used to represent the summary level""" s = str(self.allval()) return self.parse(s[:2]+ ''.join(['Z']*len(s[2:])))
java
public ServiceFuture<Boolean> checkNameExistsAsync(String accountName, final ServiceCallback<Boolean> serviceCallback) { return ServiceFuture.fromResponse(checkNameExistsWithServiceResponseAsync(accountName), serviceCallback); }
python
def rotunicode(io_object, decode=False): """Rotate ASCII <-> non-ASCII characters in a file. :param io_object: The file object to convert. :type io_object: :class:`io.TextIOWrapper` :param decode: If True, perform a rotunicode-decode (rotate from non-ASCII to ASCII). Def...
python
def lookup(self, ip_address): """Try to do a reverse dns lookup on the given ip_address""" # Is this already in our cache if self.ip_lookup_cache.get(ip_address): domain = self.ip_lookup_cache.get(ip_address) # Is the ip_address local or special elif not self.lookup...
python
def BeginEdit(self, row, col, grid): """ Fetch the value from the table and prepare the edit control to begin editing. Set the focus to the edit control. *Must Override* """ # Disable if cell is locked, enable if cell is not locked grid = self.main_window.grid ...
java
public CLIConnectionFactory basicAuth(String userInfo) { return authorization("Basic " + new String(Base64.encodeBase64((userInfo).getBytes()))); }
java
@SuppressWarnings("unused") public void setOkColor(@ColorInt int color) { mOkColor = Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)); }
java
final public void MethodParameters() throws ParseException { /*@bgen(jjtree) MethodParameters */ AstMethodParameters jjtn000 = new AstMethodParameters(JJTMETHODPARAMETERS); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { jj_consume_token(LPAREN);...
java
public <R> R into(Function<? super _1, ? extends R> fn) { return fn.apply(head()); }
java
public static PersistenceManager openDB(String dbName) { DBTracer.logCall(ZooJdoHelper.class, dbName); ZooJdoProperties props = new ZooJdoProperties(dbName); PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(props); PersistenceManager pm = pmf.getPersistenceManager();...
java
private String addAndEncodeVariable(String originalValue, String newVariable, String newVariableName, boolean encode) { return addAndEncode(originalValue, newVariable, newVariableName, encode); }
java
public void cloneBranch(String branch) throws Exception { CloneCommand cloneCommand = Git.cloneRepository() .setURI(repositoryUrl) .setDirectory(localRepo.getDirectory().getParentFile()) .setBranchesToClone(Arrays.asList(branch)) .setCloneAllBranch...
java
private void processConstraintViolation(final Set<ConstraintViolation<Object>> violations, final CsvBindingErrors bindingErrors, final ValidationContext<Object> validationContext) { for(ConstraintViolation<Object> violation : violations) { final String field = ...
python
async def _async_render(self, *, url: str, script: str = None, scrolldown, sleep: int, wait: float, reload, content: Optional[str], timeout: Union[float, int], keep_page: bool): """ Handle page creation and js rendering. Internal use for render/arender methods. """ try: page = await self.bro...
python
def validate_ip_address(ip_address): """Validate the ip_address :param ip_address: (str) IP address :return: (bool) True if the ip_address is valid """ # Validate the IP address log = logging.getLogger(mod_logger + '.validate_ip_address') if not isinstance(ip_address, basestring): l...
java
@Deprecated public static URI getParentPath(PathCodec pathCodec, URI path) { Preconditions.checkNotNull(path); // Root path has no parent. if (path.equals(GCS_ROOT)) { return null; } StorageResourceId resourceId = pathCodec.validatePathAndGetId(path, true); if (resourceId.isBucket()) ...
python
def initiator(self): """ Retrieve the initiator parent of a match :param match: :type match: :return: :rtype: """ match = self while match.parent: match = match.parent return match
java
@Override public boolean handleMessage(SOAPMessageContext context) { if (!feslAuthZ) { return true; } String service = ((QName) context.get(SOAPMessageContext.WSDL_SERVICE)) .getLocalPart(); String operation = ((QNam...
python
def raw(body, status=200, headers=None, content_type='application/octet-stream'): ''' Returns response object without encoding the body. :param body: Response data. :param status: Response code. :param headers: Custom Headers. :param content_type: the content type (string) of the respons...
python
def virtual_host(self): """ Return request virtual host ("Host" header value) :return: None or str """ if self.headers() is not None: host_value = self.headers()['Host'] return host_value[0].lower() if host_value is not None else None
java
private void loadTileCollisions(MapTileCollision mapCollision, Tile tile) { final TileCollision tileCollision; if (!tile.hasFeature(TileCollision.class)) { tileCollision = new TileCollisionModel(tile); tile.addFeature(tileCollision); } else ...
java
@Override public StringBuffer getRequestURL() { try { collaborator.preInvoke(componentMetaData); return request.getRequestURL(); } finally { collaborator.postInvoke(); } }
python
def read(filename='cache'): """ parameter: file_path - path to cache file return: data after parsing json file""" cache_path = get_cache_path(filename) if not os.path.exists(cache_path) or os.stat(cache_path).st_size == 0: return None with open(cache_path, 'r') as file: return json.load(file)
java
public void setParameterObjects(java.util.Collection<ParameterObject> parameterObjects) { if (parameterObjects == null) { this.parameterObjects = null; return; } this.parameterObjects = new com.amazonaws.internal.SdkInternalList<ParameterObject>(parameterObjects); }
python
def addLimitedLogHandler(func): """ Add a custom log handler. @param func: a function object with prototype (level, object, category, message) where level is either ERROR, WARN, INFO, DEBUG, or LOG, and the rest of the arguments are strings or None. Use ge...
python
def get_lru_cache(max_size=5): """ Args: max_size (int): References: https://github.com/amitdev/lru-dict CommandLine: python -m utool.util_cache --test-get_lru_cache Example: >>> # DISABLE_DOCTEST >>> # UNSTABLE_DOCTEST >>> from utool.util_cache imp...
python
def normalize_surfs(in_file, transform_file, newpath=None): """ Re-center GIFTI coordinates to fit align to native T1 space For midthickness surfaces, add MidThickness metadata Coordinate update based on: https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceAp...
java
private List<ColumnRelation> getIndexedColumnRelations(String tableAlias, String foreignTableAlias, Map<String, String> tableAliases, ColumnRelationsStorage columnRelations) { List<ColumnRelation> ret = new ArrayList<>(); List<ColumnRelation> matchedRelations = columnRelations.getRelations(tableAlias, f...
python
def get_tunnels(self): """Retrieves all running tunnels for a specific user.""" method = 'GET' endpoint = '/rest/v1/{}/tunnels'.format(self.client.sauce_username) return self.client.request(method, endpoint)
java
public WorkflowRunInner get(String resourceGroupName, String workflowName, String runName) { return getWithServiceResponseAsync(resourceGroupName, workflowName, runName).toBlocking().single().body(); }
python
def make_user_config_dir(): """ Create the user s-tui config directory if it doesn't exist """ config_path = get_user_config_dir() if not user_config_dir_exists(): try: os.mkdir(config_path) os.mkdir(os.path.join(config_path, 'hooks.d')) except OSError: ...
java
protected void setMetaTypeService(ServiceReference<MetaTypeService> ref) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "setMetaTypeService", ref); metaTypeServiceRef.setReference(ref); }
python
def register_filter(filter_cls): """ Adds the ``filter_cls`` to our registry. """ if filter_cls.name is None: return elif filter_cls.name in FILTER_REGISTRY: raise RuntimeError( "Filter class already registered: {}".format(filter_cls.name)) else: FILTER_REGIST...
python
def get_objects(self): """Return iterable of "object descriptions", which are tuple with these items: * `name` * `dispname` * `type` * `docname` * `anchor` * `priority` For details on each item, see :py:meth:`~sphinx.domains.Domain.get_objects`. ...
java
public void reportError(Throwable t) { // set the exception, if it is the first (and the exception is non null) if (t != null && exception.compareAndSet(null, t) && toInterrupt != null) { toInterrupt.interrupt(); } }
python
def find_first(pred, lst): """Find the first result of a list of promises `lst` that satisfies a predicate `pred`. :param pred: a function of one argument returning `True` or `False`. :param lst: a list of promises or values. :return: a promise of a value or `None`. This is a wrapper around :f...
python
def majority(image, mask=None, iterations=1): '''A pixel takes the value of the majority of its neighbors ''' global majority_table if mask is None: masked_image = image else: masked_image = image.astype(bool).copy() masked_image[~mask] = False result = table_lookup(...
java
public static Filter populateFilter(final EntityManager entityManager, final Map<String, String> paramMap, final String filterName, final String tagPrefix, final String groupTagPrefix, final String categoryInternalPrefix, final String categoryExternalPrefix, final String localePrefix, final IFie...
python
def lower_backtrack_blocks(match_query, location_types): """Lower Backtrack blocks into (QueryRoot, MarkLocation) pairs of blocks.""" # The lowering works as follows: # 1. Upon seeing a Backtrack block, end the current traversal (if non-empty). # 2. Start new traversal from the type and location to ...
java
public static Iterable<ConfigurationPropertySource> from(PropertySource<?> source) { return Collections.singleton(SpringConfigurationPropertySource.from(source)); }
python
def as_tuning_range(self, name): """Represent the parameter range as a dicionary suitable for a request to create an Amazon SageMaker hyperparameter tuning job. Args: name (str): The name of the hyperparameter. Returns: dict[str, str]: A dictionary that contains...
java
public static byte[] readBytes(ByteBuffer buffer, int start, int end) { byte[] bs = new byte[end - start]; System.arraycopy(buffer.array(), start, bs, 0, bs.length); return bs; }
java
public static void grayToBitmap( GrayU8 input , Bitmap output , byte[] storage) { if( output.getWidth() != input.getWidth() || output.getHeight() != input.getHeight() ) { throw new IllegalArgumentException("Image shapes are not the same"); } if( storage == null ) storage = declareStorage(output,null); ...
python
def p_redirection(p): '''redirection : GREATER WORD | LESS WORD | NUMBER GREATER WORD | NUMBER LESS WORD | REDIR_WORD GREATER WORD | REDIR_WORD LESS WORD | GREATER_GREATER WORD | NUMB...
java
public void setRules(java.util.Collection<MappingRule> rules) { if (rules == null) { this.rules = null; return; } this.rules = new java.util.ArrayList<MappingRule>(rules); }
java
public Map<String, Long> getDataSourceCounts() { return dataSources.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().getNumSegments())); }
python
def _fit_models(options, core_results): """ Fit models to empirical result from a function in emp module Parameters ---------- options : dict Option names and values for analysis core_results : list of tuples Output of function in emp Returns ------- list of dicts ...
java
public void set(double x1, double y1, double z1, double w1) { double mag = (1.0/Math.sqrt( x1*x1 + y1*y1 + z1*z1 + w1*w1 )); this.x = x1*mag; this.y = y1*mag; this.z = z1*mag; this.w = w1*mag; }
python
def manage_aldb_record(self, control_code, control_flags, group, address, data1, data2, data3): """Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link...
python
def set_qos(self, port_name, type='linux-htb', max_rate=None, queues=None): """ Sets a Qos rule and creates Queues on the given port. """ queues = queues if queues else [] command_qos = ovs_vsctl.VSCtlCommand( 'set-qos', [port_name, type, max_rate]) ...
java
private Method findFindByPrimaryKey(Class c) { Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals("findByPrimaryKey")) { return methods[i]; } } return null; }
java
public static GaloisField getInstance(int fieldSize, int primitivePolynomial) { int key = ((fieldSize << 16) & 0xFFFF0000) + (primitivePolynomial & 0x0000FFFF); GaloisField gf; synchronized (instances) { gf = instances.get(key); if (gf == null) { gf = new GaloisField(fieldSize, pri...
python
def wait(self): """ Wait until all transferred events have been sent. """ if self.error: raise self.error if not self.running: raise ValueError("Unable to send until client has been started.") try: self._handler.wait() except (e...
python
def _wrap_type_instantiation(self, type_cls): """Wrap the creation of the type so that we can provide a null-stream to initialize it""" def wrapper(*args, **kwargs): # use args for struct arguments?? return type_cls(stream=self._null_stream) return wrapper
python
def save_draft(self, target_folder=OutlookWellKnowFolderNames.DRAFTS): """ Save this message as a draft on the cloud :param target_folder: name of the drafts folder :return: Success / Failure :rtype: bool """ if self.object_id: # update message. Attachments ...
java
public Observable<Page<NamespaceResourceInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<NamespaceResourceInner>>, Page<NamespaceResourceInner>>() { @Override ...
python
def other_args(cls): ''' Return args for ``-o`` / ``--output`` to specify where output should be written, and for a ``--args`` to pass on any additional command line args to the subcommand. Subclasses should append these to their class ``args``. Example: .. code-bl...
python
def reflectance_from_tbs(self, sun_zenith, tb_near_ir, tb_thermal, **kwargs): """ The relfectance calculated is without units and should be between 0 and 1. Inputs: sun_zenith: Sun zenith angle for every pixel - in degrees tb_near_ir: The 3.7 (or 3.9 or equivalent) IR Tb's...
python
def community_topic_subscription_show(self, topic_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-topic-subscription" api_path = "/api/v2/community/topics/{topic_id}/subscriptions/{id}.json" api_path = api_path.format(topic_id=topic_id, id=id) ...
python
def set_handler(self, handler): """ 设置异步回调处理对象 :param handler: 回调处理对象,必须是以下类的子类实例 =============================== ========================= 类名 说明 =============================== =================...
python
def print_tools(self, buf=sys.stdout, verbose=False, context_name=None): """Print table of tools available in the suite. Args: context_name (str): If provided, only print the tools from this context. """ def _get_row(entry): context_name_ = entry[...
python
def reload_data(self): """Reloads the configuration from the database Returns: `None` """ # We must force a rollback here to ensure that we are working on a fresh session, without any cache db.session.rollback() self.__data = {} try: for ...
python
def home(request): "Simple homepage view." context = {} if request.user.is_authenticated(): try: access = request.user.accountaccess_set.all()[0] except IndexError: access = None else: client = access.api_client context['info'] = client...
java
@Check protected void checkModifiers(SarlCapacity capacity) { this.capacityModifierValidator.checkModifiers(capacity, MessageFormat.format(Messages.SARLValidator_9, capacity.getName())); }
java
@Override public InputStream createResourceAsStream(GeneratorContext context) { InputStream is = null; if (FileNameUtils.hasImageExtension(context.getPath())) { is = helper.createStreamResource(context); } return is; }
java
public synchronized <T> Launch<T> newLaunch( final Class<? extends T> programClass, ExecutorService executorService) throws LaunchException { return new LaunchImpl<T>(programClass, executorService); }
java
public static <T> Iterator<T> drop(Iterator<T> self, int num) { while (num-- > 0 && self.hasNext()) { self.next(); } return self; }
java
public static boolean matches(final char[] assertedPassword, final ManagedUser user) { final char[] prehash = createSha512Hash(assertedPassword); // Todo: remove String when Jbcrypt supports char[] return BCrypt.checkpw(new String(prehash), user.getPassword()); }
java
public ContextUserAuthManager getContextUserAuthManager(int contextId) { ContextUserAuthManager manager = contextManagers.get(contextId); if (manager == null) { manager = new ContextUserAuthManager(contextId); contextManagers.put(contextId, manager); } return manager; }
java
public Object executeScript(String script, JSONArray args) { try { JSONArray arguments = processScriptArguments(args); JSONObject response = getScriptResponse(script, arguments); Object o = cast(response); return o; } catch (JSONException e) { throw new WebDriverException(e); ...
java
public Observable<PreValidateEnableBackupResponseInner> validateAsync(String azureRegion, PreValidateEnableBackupRequest parameters) { return validateWithServiceResponseAsync(azureRegion, parameters).map(new Func1<ServiceResponse<PreValidateEnableBackupResponseInner>, PreValidateEnableBackupResponseInner>() { ...
python
async def setnym(ini_path: str) -> int: """ Set configuration. Open pool, trustee anchor, and wallet of anchor whose nym to send. Register exit hooks to close pool and trustee anchor. Engage trustee anchor to send nym for VON anchor, if it differs on the ledger from configuration. :param ini_path:...
java
public static <T> ItemsUnion<T> getInstance(final int maxK, final Comparator<? super T> comparator) { return new ItemsUnion<>(maxK, comparator, null); }
java
public void _merge(AppConfigurator conf) { app.emit(SysEventId.CONFIG_PREMERGE); if (mergeTracker.contains(conf)) { return; } mergeTracker.add(conf); for (Method method : AppConfig.class.getDeclaredMethods()) { boolean isPrivate = Modifier.isPrivate(method...
java
public static TerminalOp<Integer, OptionalInt> makeInt(IntBinaryOperator operator) { Objects.requireNonNull(operator); class ReducingSink implements AccumulatingSink<Integer, OptionalInt, ReducingSink>, Sink.OfInt { private boolean empty; private int state; ...
java
@SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.MIORG__RG_LENGTH: setRGLength((Integer)newValue); return; case AfplibPackage.MIORG__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Tr...