language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected boolean isSameConnectionForEntireSession(Session session) { // The best we can do is to assume we're safe. if (!(session instanceof TransactionContext)) return true; ConnectionReleaseMode releaseMode = ((TransactionContext) session).getConnectionReleaseMode(); return ConnectionReleaseMode.ON_C...
python
def parse_runway_config(self): """Read and parse runway.yml.""" if not os.path.isfile(self.runway_config_path): LOGGER.error("Runway config file was not found (looking for " "%s)", self.runway_config_path) sys.exit(1) with...
java
private void displayError(String message, boolean showForgotPassword, boolean showTime) { message = message.replace("\n", "<br />"); if (showForgotPassword) { message += "<br /><br /><a href=\"" + getResetPasswordLink() + "\">" + CmsVaadinUtil...
python
def decode(self, ids, strip_extraneous=False): """Transform a sequence of int ids into a human-readable string. EOS is not expected in ids. Args: ids: list of integers to be converted. strip_extraneous: bool, whether to strip off extraneous tokens (EOS and PAD). Returns: s: ...
java
Optional<String> writeTimeGauge(TimeGauge timeGauge) { double value = timeGauge.value(getBaseTimeUnit()); if (!Double.isFinite(value)) { return Optional.empty(); } return Optional.of(write(timeGauge.getId(), "timeGauge", Fields.Value.tag(), decimal(value))); }
java
FunctionTypeBuilder inferKind(@Nullable JSDocInfo info) { if (info != null) { if (!NodeUtil.isMethodDeclaration(errorRoot)) { isConstructor = info.isConstructor(); isInterface = info.isInterface(); isRecord = info.usesImplicitMatch(); makesStructs = info.makesStructs(); ...
java
public static LocalDateTime from(TemporalAccessor temporal) { if (temporal instanceof LocalDateTime) { return (LocalDateTime) temporal; } else if (temporal instanceof ZonedDateTime) { return ((ZonedDateTime) temporal).toLocalDateTime(); } else if (temporal instanceof Offs...
python
def values(self, *fields): """ Ask the collection to return a list of dict of given fields for each instance found in the collection. If no fields are given, all "simple value" fields are used. """ if not fields: fields = self._get_simple_fields() fie...
java
public Observable<ServiceResponse<DataLakeStoreAccountInfoInner>> getDataLakeStoreAccountWithServiceResponseAsync(String resourceGroupName, String accountName, String dataLakeStoreAccountName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is requi...
python
def archs(self, _args): """List the target architectures available to be built for.""" print('{Style.BRIGHT}Available target architectures are:' '{Style.RESET_ALL}'.format(Style=Out_Style)) for arch in self.ctx.archs: print(' {}'.format(arch.arch))
python
def wait_key(keys=None): ''' Waits for a keypress at the console and returns it. "Where's the any key?" Arguments: keys - if passed, wait for this specific key, e.g. ESC. may be a tuple. Returns: char or ESC - depending on key hit. None...
python
def get_permissions(self): """ Permissions of the user. Returns: List of Permission objects. """ user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role return user_role.get_permissions()
python
def identify(s): """Identify what kind of Chinese characters a string contains. *s* is a string to examine. The string's Chinese characters are tested to see if they are compatible with the Traditional or Simplified characters systems, compatible with both, or contain a mixture of Traditional and S...
java
public static GraphRole[] getRelatedElementsRoles(GraphEntity element, String relationshipname, String role) { Vector rels = element.getAllRelationships(); Enumeration enumeration = rels.elements(); Vector related = new Vector(); while (enumeration.hasMoreElements()) { ...
python
def max(self) -> int: """ Get the maximum value this immediate can have :return: Maximum value of this immediate """ if self.signed: v = (1 << (self.bits - 1)) - 1 else: v = (1 << self.bits) - 1 if self.lsb0: v = v - (v % 2) ...
python
def Serialize(self, val, info): """ Serialize an object """ self._Serialize(val, info, self.defaultNS)
java
public short getLowestMessagePriority() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getLowestMessagePriority"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Joined resource:", joinedResource); final short res...
java
public String principal() { if (getSubject() != null) { // Get the principal to print out Object principal = getSubject().getPrincipal(); return principal.toString(); } return "Guest"; }
java
@Override public IPortalUrlBuilder getDefaultUrl(HttpServletRequest request) { final IUrlNodeSyntaxHelper urlNodeSyntaxHelper = this.urlNodeSyntaxHelperRegistry.getCurrentUrlNodeSyntaxHelper(request); final String defaultLayoutNodeId = urlNodeSyntaxHelper.getDefaultLayoutNodeId(reque...
python
def p_expression_times(self, p): 'expression : expression TIMES expression' p[0] = Times(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
java
public AzureFirewallInner getByResourceGroup(String resourceGroupName, String azureFirewallName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, azureFirewallName).toBlocking().single().body(); }
java
public static File writeStringToTempFile(String contents, String path, String encoding) throws IOException { OutputStream writer = null; File tmp = File.createTempFile(path,".tmp"); if (path.endsWith(".gz")) { writer = new GZIPOutputStream(new FileOutputStream(tmp)); } else { writer = new BufferedOu...
java
public File getWorkareaFile(String relativeServerWorkareaPath) { if (relativeServerWorkareaPath == null) return workarea; else return new File(workarea, relativeServerWorkareaPath); }
java
public InstanceNetworking withPorts(InstancePortInfo... ports) { if (this.ports == null) { setPorts(new java.util.ArrayList<InstancePortInfo>(ports.length)); } for (InstancePortInfo ele : ports) { this.ports.add(ele); } return this; }
python
def _conv_name(x): ''' If this XML tree has an xmlns attribute, then etree will add it to the beginning of the tag, like: "{http://path}tag". ''' if '}' in x: comps = x.split('}') name = comps[1] return name return x
java
public static ScmConnector create(String scmType, String url, String privateKey, String username, String password, String branch, String tag) { ScmConnector scmConnector = null; if (StringUtils.isNotBlank(scmType)) { ScmType type = ScmType.getValue(scmType); if (type == null) { ...
java
public boolean put(final T key, final T val, final PutFlags... op) { if (SHOULD_CHECK) { requireNonNull(key); requireNonNull(val); checkNotClosed(); txn.checkReady(); txn.checkWritesAllowed(); } kv.keyIn(key); kv.valIn(val); final int mask = mask(op); final int rc =...
java
private static LogPriorType intToType(int intPrior) { LogPriorType[] values = LogPriorType.values(); for (LogPriorType val : values) { if (val.ordinal() == intPrior) { return val; } } throw new IllegalArgumentException(intPrior + " is not a legal LogPrior."); }
java
public void setStackSetAccounts(java.util.Collection<String> stackSetAccounts) { if (stackSetAccounts == null) { this.stackSetAccounts = null; return; } this.stackSetAccounts = new java.util.ArrayList<String>(stackSetAccounts); }
java
public static void pushContext(final UIContext uic) { if (DebugUtil.isDebugFeaturesEnabled()) { ALL_ACTIVE_CONTEXTS.put(getPrimaryUIContext(uic), null); } getStack().push(uic); }
java
protected LoginContext getLoginContext(final UsernamePasswordCredential credential) throws GeneralSecurityException { val callbackHandler = new UsernamePasswordCallbackHandler(credential.getUsername(), credential.getPassword()); if (this.loginConfigurationFile != null && StringUtils.isNotBlank(this.logi...
java
public <T> Future<T> submit(Callable<T> callable) { return mService.submit(callable); }
python
def post_comment(self, sharekey=None, comment=None): """ Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (str): Sharekey of the SharedFile to which you'd like to post a comment. comment (str):...
java
@Nullable protected static String rtrim (@Nullable final String sStr) { if (StringHelper.hasNoText (sStr)) return sStr; int pos = sStr.length (); while (pos > 0 && Character.isWhitespace (sStr.charAt (pos - 1))) { --pos; } return sStr.substring (0, pos); }
python
def create(dataset, features=None, distance=None, radius=1., min_core_neighbors=10, verbose=True): """ Create a DBSCAN clustering model. The DBSCAN method partitions the input dataset into three types of points, based on the estimated probability density at each point. - **Core** points ...
java
public static boolean checkExampleEntityClass(Object parameter, String entityFullName) { if (parameter != null && parameter instanceof Example && StringUtil.isNotEmpty(entityFullName)) { Example example = (Example) parameter; Class<?> entityClass = example.getEntityClass(); i...
python
def monitor_session_span_command_dest_vlan_val(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_number_key = ...
python
def dump(obj, fp=None, indent=None, sort_keys=False, **kw): """ Dump object to a file like object or string. :param obj: :param fp: Open file like object :param int indent: Indent size, default 2 :param bool sort_keys: Optionally sort dictionary keys. :return: Yaml serialized data. """ ...
python
def getServiceEndpoints(self, yadis_url, service_element): """Generate all endpoint objects for all of the subfilters of this filter and return their concatenation.""" endpoints = [] for subfilter in self.subfilters: endpoints.extend( subfilter.getServiceEndpo...
python
def node_setup(name, master, ticket): ''' Setup the icinga2 node. name The domain name for which this certificate will be saved master Icinga2 master node for which this certificate will be saved ticket Authentication ticket generated on icinga2 master ''' ret = {'...
java
public static final void closeWriter(Writer w) { if (w != null) { try { w.close(); } catch (Exception e) { logger.warn(e.toString()); } } }
java
public RuntimeManager build(KnowledgeRuntimeManagerType type, String identifier) { final RuntimeManager runtimeManager; final RuntimeEnvironment runtimeEnvironment = _runtimeEnvironmentBuilder.build(); final RemoteManifest remoteManifest = RemoteManifest.removeFromEnvironment(runtimeEnvironment....
java
private int addJobPart(List<DataSource> bodyPartContents, URI jobURI, int contentId) throws JAXBException { int jobContentId = contentId; validateJobOperation(); for (EntityBatchOperation entityBatchOperation : entityBatchOperations) { DataSource bodyPartContent = null; ...
python
def retrieve_mtm_results(self, book_id, asset_manager_id, paramaters): """ parameters is a dictionary of all the mtm result filter parameters """ self.logger.info('Retrieving mtm Positions - Asset Manager: %s', asset_manager_id) url = '%s/mtm/%s' % (self.endpoint, asset_manager_i...
python
def __deactivate_recipes(self, plugin, *args, **kwargs): """ Deactivates/unregisters all recipes of the current plugin, if this plugin gets deactivated. """ recipes = self.get() for recipe in recipes.keys(): self.unregister(recipe)
java
public void setChannelOptions(final Map<ChannelOption, Object> channelOptions) { this.channelOptions = channelOptions == null ? Collections.<ChannelOption, Object> emptyMap() : channelOptions; }
python
def flush(self): """Flush the write buffer of the serial port, blocking until all bytes are written. Raises: SerialError: if an I/O or OS error occurs. """ try: termios.tcdrain(self._fd) except termios.error as e: raise SerialError(e....
java
Rule FieldParts() { return Sequence(String("P:"), ZeroOrMore(WSP()).suppressNode(), PartsPlayOrder(), HeaderEol()).label(FieldParts); }
python
def delete_policy(vhost, name, runas=None): ''' Delete a policy based on rabbitmqctl clear_policy. Reference: http://www.rabbitmq.com/ha.html CLI Example: .. code-block:: bash salt '*' rabbitmq.delete_policy / HA ''' if runas is None and not salt.utils.platform.is_windows(): ...
python
def set_input_by_xpath(self, xpath, value): """ Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element """ elem = self.select(xpath).node() if self._lxml_form is None: # Explicitly set the ...
java
public void marshall(VideoMetadata videoMetadata, ProtocolMarshaller protocolMarshaller) { if (videoMetadata == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(videoMetadata.getCodec(), CODEC_BINDING)...
python
def simple_predictive_probability_multistate( self, M_c, X_L_list, X_D_list, Y, Q): """Calculate probability of a cell taking a value given a latent state. :param Y: A list of constraints to apply when querying. Each constraint is a triplet of (r,d,v): r is the row index, d is ...
python
def redirect_from_callback(self): '''Redirect to the callback URL after a successful authentication.''' state = toolkit.request.params.get('state') came_from = get_came_from(state) toolkit.response.status = 302 toolkit.response.location = came_from
java
public static Panel grid(int columns, Component... components) { Panel panel = new Panel(); panel.setLayoutManager(new GridLayout(columns)); for(Component component: components) { panel.addComponent(component); } return panel; }
python
def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress...
java
public List<Annotation> get(AnnotationType type, @NonNull Span span) { return annotationSet.select(span, a -> a.isInstance(type) && a.overlaps(span)); }
java
public static boolean isLong (@Nullable final String sStr) { if (sStr != null) try { Long.parseLong (sStr, DEFAULT_RADIX); return true; } catch (final NumberFormatException ex) { // fall through } return false; }
python
def totalNumberOfTiles(self, minZoom=None, maxZoom=None): "Return the total number of tiles for this instance extent" nbTiles = 0 minZoom = minZoom or 0 if maxZoom: maxZoom = maxZoom + 1 else: maxZoom = len(self.RESOLUTIONS) for zoom in xrange(minZ...
python
def evalsha(self, sha, numkeys, *keys_and_args): """Emulates evalsha""" if not self.script_exists(sha)[0]: raise RedisError("Sha not registered") script_callable = Script(self, self.shas[sha], self.load_lua_dependencies) numkeys = max(numkeys, 0) keys = keys_and_args[...
java
private void scheduleAlarm(long timeOut) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "scheduleAlarm timeOut=" + timeOut); // NB PM27294 implementation now means you cannot decrease the the timeOut if an alarm is already scheduled. // This...
java
private void processFiles(File[] files) { phaseOutput(format("=== %s ===", getApplicationName())); phaseOutput(format("Compiling %d BEL Document(s)", files.length)); boolean pedantic = withPedantic(); boolean verbose = withVerbose(); int validated = 0; for (int i = 1; ...
python
def register(self, func, order): """ Add a function to the filter chain. :param func: A callable which is to be added to the filter chain. :param order: An object indicating the ordering of the function relative to the others. :return: Token representing th...
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 """ options = super(Upd...
java
private boolean addTangents(Grid grid, int rowA, int colA, int rowB, int colB) { EllipseRotated_F64 a = grid.get(rowA,colA); EllipseRotated_F64 b = grid.get(rowB,colB); if( a == null || b == null ) { return false; } if( !tangentFinder.process(a,b, A0, A1, A2, A3, B0, B1, B2, B3) ) { return false; } ...
java
public EventBus emitAsync(ActEvent event, Object... args) { return _emitWithOnceBus(eventContextAsync(event, args)); }
python
def import_file(self, record, field, fname, fobj, event=None, return_format='json'): """ Import the contents of a file represented by fobj to a particular records field Parameters ---------- record : str record ID field : str f...
python
def get_block_indentation(self, block_nb): """Return line indentation (character number)""" text = to_text_string(self.document().findBlockByNumber(block_nb).text()) text = text.replace("\t", " "*self.tab_stop_width_spaces) return len(text)-len(text.lstrip())
java
public static String[] split(String input, char delimiter) { return split(input, String.valueOf(delimiter)); }
java
@Override public IMonomer getMonomer(String monName, String strandName) { Strand strand = (Strand) strands.get(strandName); if (strand != null) { return (Monomer) strand.getMonomer(monName); } else { return null; } }
java
public Router head(@NotNull final Pattern regex, @NotNull final IMiddleware... handlers) { addRegEx("HEAD", regex, handlers, headBindings); return this; }
java
private Class<? extends Constraint> getClassObject(final Element element) throws ClassNotFoundException { String className = element.getAttributeValue(XMLTags.CLASS); className = className.indexOf('.') > 0 ? className : getClass().getPackage().getName() + '.' + className; return Class.forName(className).asSubc...
python
def get_source(self, environment, template): """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate ...
python
def sync_auth(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync execution modules from ``salt://_auth`` to the master saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelis...
java
public List<Future<UpdateCenter.UpdateCenterJob>> prevalidateConfig(InputStream configXml) throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); List<Future<UpdateCenter.UpdateCenterJob>> jobs = new ArrayList<>(); UpdateCenter uc = Jenkins.getInstance().getUpdateCenter(...
java
public <R> AnimaQuery<T> where(TypeFunction<T, R> function) { String columnName = AnimaUtils.getLambdaColumnName(function); conditionSQL.append(" AND ").append(columnName); return this; }
python
def create_rule(self): """Get an instance of block rule services facade.""" return BlockRule( self.networkapi_url, self.user, self.password, self.user_ldap)
python
def preview(self): """ Access the Preview Twilio Domain :returns: Preview Twilio Domain :rtype: twilio.rest.preview.Preview """ if self._preview is None: from twilio.rest.preview import Preview self._preview = Preview(self) return self._pr...
java
public ServiceCall<Void> deleteWord(DeleteWordOptions deleteWordOptions) { Validator.notNull(deleteWordOptions, "deleteWordOptions cannot be null"); String[] pathSegments = { "v1/customizations", "words" }; String[] pathParameters = { deleteWordOptions.customizationId(), deleteWordOptions.word() }; Requ...
java
public EClass getDrawingOrderSubset() { if (drawingOrderSubsetEClass == null) { drawingOrderSubsetEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(491); } return drawingOrderSubsetEClass; }
java
@Override public ResourceSet<Device> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
java
public EntryStream<T, Long> runLengths() { return new EntryStream<>(collapseInternal(Objects::equals, t -> new ObjLongBox<>(t, 1L), (acc, t) -> { acc.b++; return acc; }, (e1, e2) -> { e1.b += e2.b; return e1; }), context); }
java
@Override public com.liferay.commerce.product.model.CPDefinitionOptionValueRel getCPDefinitionOptionValueRelByUuidAndGroupId( String uuid, long groupId) throws com.liferay.portal.kernel.exception.PortalException { return _cpDefinitionOptionValueRelLocalService.getCPDefinitionOptionValueRelByUuidAndGroupId(uuid, ...
python
def form_url(i): """ Input: { (url) - if type=='remote' or 'git', URL of remote repository or git repository (hostname) - if !='', automatically form url above (add http:// + /ck?) (port) - if !='', automatically...
java
public static List<IItem> getAllItems(final IItemAdapter adapter, boolean countHeaders) { return getAllItems(adapter.getAdapterItems(), countHeaders, false, null); }
java
public void registerFileResource(final String file) { try { _resourceMap.put(file, new File(file).toURI().toURL()); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static ArtifactCoordinates fromString(String string) { final Matcher matcher = VALID_PATTERN.matcher(string); if (matcher.matches()) { if (matcher.group(4) != null) { return new ArtifactCoordinates(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4))...
python
def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the servi...
python
def to_superuser(email_class, **data): """ Email superusers """ for user in get_user_model().objects.filter(is_superuser=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_lan...
python
def discriminator(self, frames): """3-D SNGAN discriminator. Args: frames: a list of batch-major tensors indexed by time. Returns: logits: 1-D Tensor with shape=batch_size. Positive logits imply that the discriminator thinks that it belongs to the true class. ""...
java
public void setTextOrientation(final TextOrientation ORIENTATION) { if (null == textOrientation) { _textOrientation = ORIENTATION; redraw(); } else { textOrientation.set(ORIENTATION); } }
java
@Override public void init(JawrConfig config, List<JoinableResourceBundle> globalBundles, List<JoinableResourceBundle> contextBundles) { if (null == mainScriptTemplate) { mainScriptTemplate = loadScriptTemplate(SCRIPT_TEMPLATE); } if (null == debugScriptTemplate) { debugScriptTemplate = loadScriptTempl...
python
def get_attachment(self, ticket_id, attachment_id): """ Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType ...
java
protected Framework startFramework(BootstrapConfig config) throws BundleException { // Set the default startlevel of the framework. We want the framework to // start at our bootstrap level (i.e. Framework bundle itself will start, and // it will pre-load and re-start any previously known bundles...
java
public java.util.Map<String, java.util.List<String>> getSecretVersionsToStages() { return secretVersionsToStages; }
java
@Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) { return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); } else if ( lockMode == LockMode.PESSIMISTIC_WRITE ) { return new InfinispanPessim...
python
def list_entitlements(owner, repo, page, page_size, show_tokens): """Get a list of entitlements on a repository.""" client = get_entitlements_api() with catch_raise_api_exception(): data, _, headers = client.entitlements_list_with_http_info( owner=owner, repo=repo, ...
java
public UserProfile findUserProfileByName(String userName) throws Exception { UserProfile profile = getFromCache(userName); if (profile != null) { return profile; } Session session = service.getStorageSession(); try { profile = readProfile(session, userName...
java
public StringType addExcludeElement() {//2 StringType t = new StringType(); if (this.exclude == null) this.exclude = new ArrayList<StringType>(); this.exclude.add(t); return t; }
python
def display(self, *amplExpressions): """ Writes on the current OutputHandler the outcome of the AMPL statement. .. code-block:: ampl display e1, e2, .., en; where e1, ..., en are the strings passed to the procedure. Args: amplExpressions: Expressions t...
java
private String escapeUnrecognizedCharacters(String s) { // TODO(yitingwang) Move this method to a suitable place StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { // From the SingleEscapeCharacter grammar production. ...