language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("unchecked") public void deassociate(HttpServletRequest context) { Map<Descriptor<?>, Object> components = (Map<Descriptor<?>, Object>) context.getAttribute(COMPONENTS); for (Object component : components.values()) { try { Event.of(Passivated.class).on(component).fire(); } catch...
python
def updateCurrentView(self, oldWidget, newWidget): """ Updates the current view widget. :param oldWidget | <QtGui.QWidget> newWidget | <QtGui.QWidget> """ view = projexui.ancestor(newWidget, XView) if view is not None: view.se...
python
def HasDataStream(self, name, case_sensitive=True): """Determines if the file entry has specific data stream. Args: name (str): name of the data stream. case_sensitive (Optional[bool]): True if the name is case sensitive. Returns: bool: True if the file entry has the data stream. Ra...
java
@Activated public void activated() { logger.info("Importing core packages ['org.eiichiro.gig', 'org.eiichiro.bootleg', 'org.eiichiro.jaguar', 'org.eiichiro.jaguar.deployment'] into JavaScript context"); Context context = factory.enterContext(); try { context.evaluateString(scope, "importPackage(Packages.or...
java
public void marshall(Value value, ProtocolMarshaller protocolMarshaller) { if (value == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(value.getArrayValues(), ARRAYVALUES_BINDING); protoc...
python
def _message_in_range(self, message): """ Determine whether the given message is in the range or it should be ignored (and avoid loading more chunks). """ # No entity means message IDs between chats may vary if self.entity: if self.reverse: if ...
python
def _render_content(self, content, **settings): """ Perform widget rendering, but do not print anything. """ if not self.SETTING_WIDTH in settings or not settings[self.SETTING_WIDTH]: settings[self.SETTING_WIDTH] = TERMINAL_WIDTH s = {k: settings[k] for k in (self.SE...
python
def parse_command_line_parameters(argv=None): """ Parses command line arguments """ usage =\ 'usage: %prog [options] input_sequences_filepath' version = 'Version: %prog ' + __version__ parser = OptionParser(usage=usage, version=version) parser.add_option('-o', '--output_fp', action='store',...
java
private boolean add(Map<ClassDoc,List<ClassDoc>> map, ClassDoc superclass, ClassDoc cd) { List<ClassDoc> list = map.get(superclass); if (list == null) { list = new ArrayList<ClassDoc>(); map.put(superclass, list); } if (list.contains(cd)) { return fals...
python
def update(self, items): """ Updates the dependencies in the inverse relationship format, i.e. from an iterable or dict that is structured as `(item, dependent_items)`. The parent element `item` may occur multiple times. :param items: Iterable or dictionary in the format `(item, depende...
python
def get_default_config(self): """ Returns the default collector settings """ config = super(OneWireCollector, self).get_default_config() config.update({ 'path': 'owfs', 'owfs': '/mnt/1wire', # 'scan': {'temperature': 't'}, # 'id:24....
python
def returnTradeHistory(self, currencyPair, start=None, end=None): """Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters.""" return self._public('returnTradeHistory', currencyPair=curr...
python
def _build_dict(data): ''' Rebuild dict ''' result = {} # TODO: Add Metadata support when it is merged from develop result["jid"] = data[0] result["tgt_type"] = data[1] result["cmd"] = data[2] result["tgt"] = data[3] result["kwargs"] = data[4] result["ret"] = data[5] resu...
java
@Override public void removeByUuid(String uuid) { for (CPDefinition cpDefinition : findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpDefinition); } }
python
def get_locations(self, url): """Get valid location header values from responses. :param url: a URL address. If a HEAD request sent to it fails because the address has invalid schema, times out or there is a connection error, the generator yields nothing. :returns: valid redirec...
java
public static Double getMinY(Geometry geom) { if (geom != null) { return geom.getEnvelopeInternal().getMinY(); } else { return null; } }
java
protected ArtifactHandler getArtifactHandler() throws MojoExecutionException { final ArtifactHandlerBase.Builder builder; switch (this.getDeploymentType()) { case MSDEPLOY: builder = new MSDeployArtifactHandlerImpl.Builder().functionAppName(this.getAppName()); ...
python
def ispercolating(am, inlets, outlets, mode='site'): r""" Determines if a percolating clusters exists in the network spanning the given inlet and outlet sites Parameters ---------- am : adjacency_matrix The adjacency matrix with the ``data`` attribute indicating if a bond is occ...
python
def handle(self, environ, start_response): """WSGI handler function. The transport will serve a request by reading the message and putting it into an internal buffer. It will then block until another concurrently running function sends a reply using :py:meth:`send_reply`. The r...
python
def depth_soil_conductivity(self, value=None): """Corresponds to IDD Field `depth_soil_conductivity` Args: value (float): value for IDD Field `depth_soil_conductivity` Unit: W/m-K, if `value` is None it will not be checked against the specific...
java
public static boolean verifyDiscoverInfoVersion(String ver, String hash, DiscoverInfo info) { // step 3.3 check for duplicate identities if (info.containsDuplicateIdentities()) return false; // step 3.4 check for duplicate features if (info.containsDuplicateFeatures()) ...
python
def generate_uuid(): """Generate a UUID.""" r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) return r_uuid.decode().replace('=', '')
java
private boolean hasSameStatus(Plugin scanner, String status) { if (status.equals(Constant.messages.getString("ascan.policy.table.quality.all"))) { return true; } return status.equals(View.getSingleton().getStatusUI(scanner.getStatus()).toString()); }
java
@SuppressWarnings("unchecked") public <T> T getSelect(final SelectBuilder _selectBldr) throws EFapsException { final OneSelect oneselect = this.selectStmt2OneSelect.get(_selectBldr.toString()); return oneselect == null ? null : (T) oneselect.getObject(); }
python
def remove_assigned_resource(self, resource_type: str, value: Union[str, int, float, bool] = None, parameters: dict = None): """Remove assigned resources from the processing block. All matching resources will be removed. If only type is ...
java
public void sessionAttributeSet(ISession source, Object key, Object oldValue, Boolean oldIsListener, Object newValue, Boolean newIsListener) { // ArrayList sessionStateObservers = null; /* * Check to see if there is a non-empty list of sessionStateObservers. */ if (_sessionSta...
java
private Integer getToParameter(Map<String, String> parameters, Integer defaultValue) throws TransformationOperationException { return getSubStringParameter(parameters, toParam, defaultValue); }
java
private Content processParamTags(Element e, boolean isParams, List<? extends DocTree> paramTags, Map<String, String> rankMap, TagletWriter writer, Set<String> alreadyDocumented) { Messages messages = writer.configuration().getMessages(); Content result = writer.getOutputInstance(...
java
public boolean prepareAddActiveMessage() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this,tc, "prepareAddActiveMessage"); boolean messageAccepted = true; // If we're a member of a ConsumerSet, inform them of the prepare if(classifyingMessages) mes...
python
def next_frame_sv2p_tiny(): """Tiny SV2P model.""" hparams = next_frame_sv2p_atari_softmax() hparams.batch_size = 2 hparams.tiny_mode = True hparams.num_masks = 1 hparams.video_modality_loss_cutoff = 0.4 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 return hparams
python
def clear_cache(self, items=None, topic=EVENT_TOPIC): """ expects event object to be in the format of a session-stop or session-expire event, whose results attribute is a namedtuple(identifiers, session_key) """ try: for realm in self.realms: i...
python
def demote(self, move: chess.Move) -> None: """Moves a variation one down in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i < len(self.variations) - 1: self.variations[i + 1], self.variations[i] = self.variations[i], self.variation...
python
def encode(cls, d): """ Internal: encode a string for url representation """ warnings.warn( 'The `encode` class method of APIRequestor is deprecated and ' 'will be removed in version 2.0.' 'If you need public access to this function, please email us ' ...
java
private Object readResolve() throws ObjectStreamException { LexLocation existing = uniqueLocations.get(this); if (existing == null) { return this; } else { return existing; } }
python
def element_for_value(cls, attrname, value): """Serialize the given value into an XML `Element` with the given tag name, returning it. The value argument may be: * a `Resource` instance * a `Money` instance * a `datetime.datetime` instance * a string, integer, or...
python
def rapid_upload(self): '''快速上传. 如果失败, 就自动调用分片上传. ''' info = pcs.rapid_upload(self.cookie, self.tokens, self.row[SOURCEPATH_COL], self.row[PATH_COL], self.upload_mode) if info and info['md5'] and info['fs_id']: ...
java
public ServiceFuture<Void> failoverAsync(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(failoverWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName), ser...
java
protected void view(Map values){ for(Object key:values.keySet() ){ assign(key.toString(), values.get(key)); } }
java
public Circle fit(Circle initCircle, DenseMatrix64F points) { initCenter.data[0] = initCircle.getX(); initCenter.data[1] = initCircle.getY(); radius = initCircle.getRadius(); fit(points); return this; }
python
def set_threshold_override(self, limit_name, warn_percent=None, warn_count=None, crit_percent=None, crit_count=None): """ Override the default warning and critical thresholds used to evaluate the specified limit's usage. Theresholds c...
python
def set_jac(self, m, val, row, col): """ Set the values at (row, col) to val in Jacobian m :param m: Jacobian name :param val: values to set :param row: row indices :param col: col indices :return: None """ assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx...
java
public DelimitedStringParser extractBoolean(String key, Consumer<Boolean> consumer) { this.extractors.put(key, new Extractor<>(consumer, value -> { value = value.trim().toLowerCase(); return value.equals("true") || value.equals("yes") || value.equals("1");...
java
@Override public final Object instantiateItem(final ViewGroup container, final int position) { if (Constants.DEBUG) { Log.i("InfiniteViewPager", String.format("instantiating position %s", position)); } final PageModel<T> model = createPageModel(position); mPageModels[posi...
python
async def auth_crypt(wallet_handle: int, sender_vk: str, recipient_vk: str, msg: bytes) -> bytes: """ **** THIS FUNCTION WILL BE DEPRECATED USE pack_message INSTEAD **** Encrypt a message by authenticated-encryption scheme. Sender can encr...
java
public void fireHistoricActivityInstanceUpdate() { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); HistoryLevel historyLevel = configuration.getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.ACTIVITY_INSTANCE_UPDATE, this)) { // publis...
java
private static String getStyleClasses(AbstractNavLink link, boolean isResponsive) { StringBuilder sb; sb = new StringBuilder(20); // optimize int String look = null; if (link instanceof Link) { look = ((Link) link).getLook(); } else if (link instanceof CommandLink) { look = ((CommandLink) link).getLook...
python
def generate_env(fname=None): """Generate file with exports. By default this is in .config/genomepy/exports.txt. Parameters ---------- fname: strs, optional Name of the output file. """ config_dir = user_config_dir("genomepy") if os.path.exists(config_dir): fname = os....
python
def transfer(self, volume: Union[float, Sequence[float]], source, dest, **kwargs) -> 'InstrumentContext': # source: Union[Well, List[Well], List[List[Well]]], # dest: Union[Well, List[Well], List[List[Well]]], # TODO: Reach cons...
python
def insert_record_by_dict(self, table: str, valuedict: Dict[str, Any]) -> Optional[int]: """Inserts a record into database, table "table", using a dictionary containing field/value mappings. Returns the new PK (or None).""" if not value...
java
public Observable<ManagementLockObjectInner> getByResourceGroupAsync(String resourceGroupName, String lockName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, lockName).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() { @Override ...
python
def _expand_vector(self,x): ''' Takes a value x in the subspace of not fixed dimensions and expands it with the values of the fixed ones. :param x: input vector to be expanded by adding the context values ''' x = np.atleast_2d(x) x_expanded = np.zeros((x.shape[0],self.spa...
python
def read(self, entity=None, attrs=None, ignore=None, params=None): """Get information about the current entity. 1. Create a new entity of type ``type(self)``. 2. Call :meth:`read_json` and capture the response. 3. Populate the entity with the response. 4. Return the entity. ...
python
def RLS_SDR(anchors, W, r, print_out=False): """ Range least squares (RLS) using SDR. Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to point x. :return: estimated po...
java
@Override public DisassociateDRTLogBucketResult disassociateDRTLogBucket(DisassociateDRTLogBucketRequest request) { request = beforeClientExecution(request); return executeDisassociateDRTLogBucket(request); }
python
def stop(self): """! Stop all receving threads. """ if not self.isThreadsRunning: raise ThreadManagerException("Broker threads are already stopped") self.isThreadsRunning = False for client in self.clients: client.stop()
java
@Override public synchronized void rebuildDirtyBundles() { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Rebuild dirty bundles"); } StopWatch stopWatch = new StopWatch(); ThreadLocalJawrContext.setStopWatch(stopWatch); // Initialize the Thread local for the Jawr context ThreadLocalJawrContext.setJawrC...
java
public static <A, B, V> BaseCommand<A, B> withValue(@NotNull Command<A, B> cmd, Key<V> key, V value) { return new SetValueCommand<>(cmd, key, value); }
java
public static <T> T queryForObject(String sql, Class<T> clz, Object... args) { T result = null; List<T> list = queryForList(sql, clz, args); if (list.size() > 0) { result = list.get(0); } return result; }
java
public static TileGeomResult createTileGeom(List<Geometry> g, Envelope tileEnvelope, GeometryFactory geomFactory, MvtLayerParams mvtLayerParams, ...
python
def AuthenticatedOrRedirect(invocation): """ Middleware class factory that redirects if the user is not logged in. Otherwise, nothing is effected. """ class AuthenticatedOrRedirect(GiottoInputMiddleware): def http(self, request): if request.user: return request ...
java
public ScriptNode transformTree(AstRoot root) { currentScriptOrFn = root; this.inUseStrictDirective = root.isInStrictMode(); int sourceStartOffset = decompiler.getCurrentOffset(); if (Token.printTrees) { System.out.println("IRFactory.transformTree"); System.out.p...
java
public ClientResponseImpl call(Object... paramListIn) { m_perCallStats = m_statsCollector.beginProcedure(); // if we're keeping track, calculate parameter size if (m_perCallStats != null) { StoredProcedureInvocation invoc = (m_txnState != null ? m_txnState.getInvocation() : null); ...
java
public void setReturnType(String type) { if (!Strings.isEmpty(type) && !Objects.equals("void", type) && !Objects.equals(Void.class.getName(), type)) { this.sarlAction.setReturnType(newTypeRef(container, type)); } else { this.sarlAction.setReturnType(null); } }
java
public V remove(K key) throws Exception { return invoke(REMOVE, key, null, true); }
python
def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. """ click.echo("Resetting OpenPGP data, don't remove your YubiKey...") ctx.obj['controller'].reset() click.echo('Success! All data has been cleared and defaul...
java
@SuppressWarnings("unchecked") private static HashMap<String, ArrayList<ArrayList<String>>> readHash(String fileName, boolean isInternalFile) throws SMatchException { try { return (HashMap<String, ArrayList<ArrayList<String>>>) MiscUtils.readObject(fileName, isInternalFile); } catch ...
java
public List<Cluster<M>> getAllClusters() { ArrayList<Cluster<M>> res = new ArrayList<>(hierarchy.size()); for(It<Cluster<M>> iter = hierarchy.iterAll(); iter.valid(); iter.advance()) { res.add(iter.get()); } Collections.sort(res, Cluster.BY_NAME_SORTER); return res; }
java
@Override public Uri insert(Uri uri, ContentValues values) { Uri result = null; if (!controller.hasPreinitialized()) { throw new IllegalStateException("Controller has not been initialized."); } int patternCode = controller.getUriMatcher().match(uri); MatcherPatt...
java
public static long hash64(final String text) { final byte[] bytes = text.getBytes(); return hash64(bytes, bytes.length); }
python
def set_tempo_event(self, bpm): """Calculate the microseconds per quarter note.""" ms_per_min = 60000000 mpqn = a2b_hex('%06x' % (ms_per_min / bpm)) return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
java
@InterfaceAudience.Public public Database getExistingDatabase(String name) throws CouchbaseLiteException { DatabaseOptions options = getDefaultOptions(name); return openDatabase(name, options); }
python
def cache(self, dependency: Dependency, value): """ Store an instance of dependency in the cache. Does nothing if dependency is NOT a threadlocal or a singleton. :param dependency: The ``Dependency`` to cache :param value: The value to cache for dependency :ty...
java
public Map<String, String> findMatches(String incoming) { String[] pieces = incoming.split(PATH_SEPARATOR); int i = 0; //too many matchers, short circuit if (path.size() > pieces.length) return null; Map<String, String> values = new HashMap<String, String>(); ...
python
def engine(self): """ Return an engine instance, creating it if it doesn't exist. Recreate the engine connection if it wasn't originally created by the current process. """ pid = os.getpid() conn = SQLAlchemyTarget._engine_dict.get(self.connection_string) ...
python
def line_count(fn): """ Get line count of file Args: fn (str): Path to file Return: Number of lines in file (int) """ with open(fn) as f: for i, l in enumerate(f): pass return i + 1
java
public boolean existsElement(String predicate) throws org.odmg.QueryInvalidException { DList results = (DList) this.query(predicate); if (results == null || results.size() == 0) return false; else return true; }
java
public boolean matchesFilter(String filter, int param) { filter = filter.toLowerCase(); return m_parameters[param].toLowerCase().contains(filter); }
java
public static List<CPSpecificationOption> findByUuid_C(String uuid, long companyId) { return getPersistence().findByUuid_C(uuid, companyId); }
java
public String[] getHeaderValues(final String pHeaderName) { List<String> values = headers.get(pHeaderName); return values == null ? null : values.toArray(new String[values.size()]); }
java
public void set(int index, double value) { if (isImmutable) throw new UnsupportedOperationException( "Cannot modify an immutable vector"); doubleVector.set(getIndex(index), value); }
java
protected final boolean handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateC...
java
private String readMangopayVersion() { try { Properties prop = new Properties(); InputStream input = getClass().getResourceAsStream("mangopay.properties"); prop.load(input); return prop.getProperty("version"); } catch (IOException ex) { ...
java
public static String getDefaultMimeByExtension(String filename) { String type = null; if (filename != null) { int i = -1; while (type == null) { i = filename.indexOf(".", i + 1); if (i < 0 || i >= filename.length()) break; ...
java
private JPanel getJPanel() { if (jPanel == null) { jPanel = new JPanel(); jPanel.setLayout(new GridBagLayout()); JLabel question = new JLabel(Constant.messages.getString("database.newsession.question")); jPanel.add(question, LayoutHelper.getGBC(0, 0, 2, 1.0D, new Insets(4, 4, 4, 4))); jPan...
python
def parse_GSE(filepath): """Parse GSE SOFT file. Args: filepath (:obj:`str`): Path to GSE SOFT file. Returns: :obj:`GEOparse.GSE`: A GSE object. """ gpls = {} gsms = {} series_counter = 0 database = None metadata = {} gse_name = None with utils.smart_open(f...
python
def getPrecision(self, result=None): """Returns the precision for the Analysis. - If ManualUncertainty is set, calculates the precision of the result in accordance with the manual uncertainty set. - If Calculate Precision from Uncertainty is set in Analysis Service, calcula...
python
def load_variables(defines, config_file): """Load all variables from cmdline args and/or a config file. Args: defines (list of str): A list of name=value pairs that define free variables. config_file (str): An optional path to a yaml config file that defines a single dic...
java
public Deployment build() { return new DeploymentImpl(identifier, name, archive, classLoader, metadata, activation, resourceAdapter, getConnectionFactories(), getAdminObjects(), classLoaderPlugin); }
java
@Override public void getUsersForGroup(List<String> grpMbrAttrs, int countLimit) throws WIMException { String securityName = null; try { securityName = getSecurityName(false); List<String> returnNames = urBridge.getUsersForGroup(securityName, countLimit).getList(); ...
java
public ArrayList<String> email_exchange_organizationName_service_exchangeService_account_GET(String organizationName, String exchangeService, OvhOvhLicenceEnum licence, Long number, OvhAccountQuotaEnum storageQuota) throws IOException { String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService...
java
final public void LambdaExpression() throws ParseException { /*@bgen(jjtree) LambdaExpression */ AstLambdaExpression jjtn000 = new AstLambdaExpression(JJTLAMBDAEXPRESSION); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); try { LambdaParameters(); ...
python
def bootstrap_executive_office_states(self, election): """ Create state page content exclusively for the U.S. president. """ content_type = ContentType.objects.get_for_model(election.race.office) for division in Division.objects.filter(level=self.STATE_LEVEL): PageCon...
python
def pick_best_methods(stochastic): """ Picks the StepMethods best suited to handle a stochastic variable. """ # Keep track of most competent methohd max_competence = 0 # Empty set of appropriate StepMethods best_candidates = set([]) # Loop over StepMethodRegistry for method in ...
python
def proxy_reconnect(proxy_name, opts=None): ''' Forces proxy minion reconnection when not alive. proxy_name The virtual name of the proxy module. opts: None Opts dictionary. Not intended for CLI usage. CLI Example: salt '*' status.proxy_reconnect rest_sample ''' ...
python
def update_iscsi_settings(self, iscsi_data): """Update iscsi data :param data: default iscsi config data """ self._conn.patch(self.path, data=iscsi_data)
java
public static boolean isHttpGetRequest(HttpServletRequest request) { boolean isSane = isSaneRequest(request); boolean isGet = isSane && request.getMethod().equals(HttpMethod.GET.toString()); return isSane && isGet; }
python
def main(): """ Show the intervention screen. """ application = Application(sys.argv, ignore_close=not SKIP_FILTER) platform.hide_cursor() with open(resource_filename(__name__, 'intervention.css')) as css: application.setStyleSheet(css.read()) # exec() is required for objc so we m...
java
private Nonce verifyUnknownNonce(final String nonce, final int nonceCount) { byte[] complete; int offset; int length; try { ByteBuffer decode = FlexBase64.decode(nonce); complete = decode.array(); offset = decode.arrayOffset(); length = dec...
java
private void _saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__saveActionPerformed int[] i = _oList.getSelectedRows(); String[] o = new String[i.length]; for (int j = 0; j < i.length; j++) { o[j] = (String) _oList.getValueAt(i[j], 0); } JFileCho...
python
def bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support at least o...