language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
async def unlock(self, key, value, *, flags=None, session): """Unlocks the Key with the given Session. Parameters: key (str): Key to set value (Payload): Value to set, It will be encoded by flags session (ObjectID): Session ID flags (int): Flags to set wi...
java
protected Color desaturate(Color color) { float[] tmp = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); tmp[1] /= 3.0f; tmp[2] = clamp(1.0f - (1.0f - tmp[2]) / 3f); return new Color((Color.HSBtoRGB(tmp[0], tmp[1], tmp[2]) & 0xFFFFFF)); }
python
def last_version(): """ Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode """ try: last_update, version, success = last...
java
public static String generateFullMethodName(String fullServiceName, String methodName) { return checkNotNull(fullServiceName, "fullServiceName") + "/" + checkNotNull(methodName, "methodName"); }
java
public ServiceFuture<Void> stopResizeAsync(String poolId, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(stopResizeWithServiceResponseAsync(poolId), serviceCallback); }
java
public void addFeatures(Map<VectorLayer, List<Feature>> featureMap, Criterion criterion) { if (showDetailsOnSingleResult && featureMap.size() == 1) { // sorting is never needed if only 1 entry List<Feature> features = featureMap.values().iterator().next(); if (features.size() == 1) { showFeatureDetailWin...
java
public static byte[] calculateHmacSha1(byte[] message, int offset, int length, byte[] key) throws IllegalArgumentException { try { // get an HMAC-SHA1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM); // get an HMAC-SHA1 Mac instance and initialize it with th...
python
def identify_ibids(line): """Find IBIDs within the line, record their position and length, and replace them with underscores. @param line: (string) the working reference line @return: (tuple) containing 2 dictionaries and a string: Dictionary: matched IBID text: (Key: position of IBI...
java
private void processStartTag(final StartElement paramElem) throws IOException, XMLStreamException, TTException { assert paramElem != null; // Initialize variables. initializeVars(); // Main algorithm to determine if same, insert or a delete has to be // made. al...
python
def run_suite(case, config, summary): """ Run the full suite of numerics tests """ m = importlib.import_module(config['module']) m.set_up() config["name"] = case analysis_data = {} bundle = livvkit.numerics_model_module model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) ...
python
def _poll_worker_result(self, group_id): """ 从队列里面获取worker的返回 """ while 1: try: msg = self.parent_input_dict[group_id].get() except KeyboardInterrupt: break except: logger.error('exc occur.', exc_info=Tru...
python
def decode_offset_fetch_response(cls, data): """ Decode bytes to an OffsetFetchResponse :param bytes data: bytes to decode """ ((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _i in range(num_...
python
def photo(self, args): """ Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id) """ rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0])) p = rsp['photo'] yield self._prep(p)
python
def rank(self, value): """Returns the rank and count of the value in the btree.""" i = 0 n = len(self._tree) rank = 0 count = 0 while i < n: cur = self._tree[i] if value < cur: i = 2 * i + 1 continue elif...
java
private ExpressionAndSubstitution convertIntoExpressionAndSubstitution(ImmutableExpression expression, ImmutableSet<Variable> leftVariables, ImmutableSet<Variable> rightV...
java
public boolean isOutputVertex() { if (this.forwardLinks.size() == 0) { return true; } final Iterator<ExecutionGroupEdge> it = this.forwardLinks.iterator(); while (it.hasNext()) { if (it.next().getTargetVertex().getStageNumber() == this.getStageNumber()) { return false; } } return true; }
java
public Map<String, Frame> prepareEncodingMap(Frame data, String targetColumnName, String foldColumnName, boolean imputeNAsWithNewCategory) { // Validate input data....
python
def tmdb_search_movies( api_key, title, year=None, adult=False, region=None, page=1, cache=True ): """ Search for movies using The Movie Database Online docs: developers.themoviedb.org/3/search/search-movies """ url = "https://api.themoviedb.org/3/search/movie" try: if year: ...
python
def fetch_user(query): """Get user by ``pk`` or ``username``. Raise error if it doesn't exist.""" user_filter = {'pk': query} if query.isdigit() else {'username': query} user_model = get_user_model() try: return user_model.objects.get(**user_filter) except user_model.DoesNotExist: r...
java
public final void deleteOperation(String name) { DeleteOperationRequest request = DeleteOperationRequest.newBuilder().setName(name).build(); deleteOperation(request); }
java
@Override public EClass getIfcIonConcentrationMeasure() { if (ifcIonConcentrationMeasureEClass == null) { ifcIonConcentrationMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(819); } return ifcIonConcentrationMeasureEClass; }
python
def transform(self, maps): """ This function transforms from aligned mass-weighted spins to cartesian spins aligned along the z-axis. Parameters ---------- maps : a mapping object Returns ------- out : dict A dict with key as parameter name a...
java
public void validateXMLString(String xml, String dtdFile, String docType) throws SAXException, IOException, ParserConfigurationException { validateInternal(xml, dtdFile, docType); }
python
def do_numberrep(self, line): """numberrep <number of replicas> Set preferred number of replicas for new objects If the preferred number of replicas is set to zero, replication is also disallowed.""" n_replicas = self._split_args(line, 1, 0)[0] self._command_processor.get_session...
java
public User getUserById(int id) { for (User u : users) if (u.getId() == id) return u; return null; }
python
def pdag_to_dag(pdag): """Completes a PDAG to a DAG, without adding v-structures, if such a completion exists. If no faithful extension is possible, some fully oriented DAG that corresponds to the PDAG is returned and a warning is generated. This is a static method. Parameters ...
java
@Override public Boolean executeCommand(int timeout, String componentName, Object... data) throws QTasteException { setData(data); long maxTime = System.currentTimeMillis() + 1000 * timeout; String buttonText = mData[0].toString(); component = null; while (System.currentTime...
java
public static Key make(FileStatus f) { Futures fs = new Futures(); Key key = make(f, fs); fs.blockForPending(); return key; }
java
public int getInt(String key, int defaultValue) { String value = get(key); if(value == null) return defaultValue; try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new IllegalArgumentException(key + " parameter should be a number"); }...
python
def mconsensus(args): """ %prog mconsensus *.consensus Call consensus along the stacks from cross-sample clustering. """ p = OptionParser(mconsensus.__doc__) p.add_option("--allele_counts", default="allele_counts", help="Directory to generate allele counts") add_consensus_o...
python
def shared_s3_app_bucket(self, include_region=False): """Generate shared s3 application bucket name. Args: include_region (bool): Include region in the name generation. """ if include_region: shared_s3_app_bucket = self.format['shared_s3_app_region_bucket'].forma...
java
@Override public void filtrate(DataBinder parameters) { first.filtrate(parameters); second.filtrate(parameters); }
python
def assure_directory_exists(path, is_file=False): """Assure that the directory pointed to by path exists. :param is_file: If True, path is assumed to be a file and handled correctly. Otherwise it must be a directory :return: True if the directory was created, False if it already existed""" if i...
java
public Completable addProduct(Product product) { List<Product> updatedShoppingCart = new ArrayList<>(); updatedShoppingCart.addAll(itemsInShoppingCart.getValue()); updatedShoppingCart.add(product); itemsInShoppingCart.onNext(updatedShoppingCart); return Completable.complete(); }
java
public static byte[] convertToXmlByteArray(List<PartETag> partETags) { XmlWriter xml = new XmlWriter(); xml.start("CompleteMultipartUpload"); if (partETags != null) { List<PartETag> sortedPartETags = new ArrayList<PartETag>(partETags); Collections.sort(sortedPartETags, ne...
java
public static Writer appendLine(Writer writer, String line) { return append(writer, line + JMString.LINE_SEPARATOR); }
java
void checkPermission(PermissionListener listener, String permission, Thread thread) { checkSinglePermission(listener, permission, thread); }
python
def _evalAndDer(self,x): ''' Returns the level and first derivative of the function at each value in x. Only called internally by HARKinterpolator1D.eval_and_der. ''' m = len(x) fx = np.zeros((m,self.funcCount)) for j in range(self.funcCount): fx[:,j]...
java
static <T> ItemsSketch<T> copy(final ItemsSketch<T> sketch) { final ItemsSketch<T> qsCopy = ItemsSketch.getInstance(sketch.k_, sketch.comparator_); qsCopy.n_ = sketch.n_; qsCopy.minValue_ = sketch.getMinValue(); qsCopy.maxValue_ = sketch.getMaxValue(); qsCopy.combinedBufferItemCapacity_ = sketch.get...
java
public static base_response create(nitro_service client, systembackup resource) throws Exception { systembackup createresource = new systembackup(); createresource.filename = resource.filename; createresource.level = resource.level; createresource.comment = resource.comment; return createresource.perform_oper...
java
static Object getRegisteredObject (Connection connection, int objectID) { ObjectSpace[] instances = ObjectSpace.instances; for (int i = 0, n = instances.length; i < n; i++) { ObjectSpace objectSpace = instances[i]; // Check if the connection is in this ObjectSpace. Connection[] connections = objectSpace.co...
java
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setPosition(final Position position) { this.position = position.getValue(); return (T) this; }
java
public void processRequest(RequestEvent requestEvent) { // This will be invoked only by external endpoint BalancerAppContent content=(BalancerAppContent)requestEvent.getSource(); boolean isIpv6 = content.isIpv6(); final SipProvider sipProvider = content.getProvider(); final Request req...
java
static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) { if (cmpValue == ParamPrefixEnum.APPROXIMATE) { return theValue.multiply(new BigDecimal(0.1)); } else { String plainString = theValue.toPlainString(); int dotIdx = plainString.indexOf('.'); if (dotIdx == -1) { retu...
python
def makeEndOfPrdvFunc(self,EndOfPrdvP): ''' Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal value of assets co...
java
public boolean saveEncryptionKeyData(KeyData data) { JSONObject objectToSave = new JSONObject(); try { objectToSave.put(KEY_DPK, DPKEncryptionUtil.byteArrayToHexString(data .getEncryptedDPK())); objectToSave.put(KEY_IV, DPKEncryptionUtil.byteArrayToHexString(d...
python
def register_model(cls, model): """ Register a model class according to its remote name Args: model: the model to register """ rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_regis...
python
def extract_jwt_token(self, token): """ Extracts a data dictionary from a jwt token """ # Note: we disable exp verification because we will do it ourselves with InvalidTokenHeader.handle_errors('failed to decode JWT token'): data = jwt.decode( token, ...
java
public static base_responses update(nitro_service client, aaakcdaccount resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { aaakcdaccount updateresources[] = new aaakcdaccount[resources.length]; for (int i=0;i<resources.length;i++){ updateresource...
java
public static void addAttributes(SerializationHandler handler, int src) throws TransformerException { TransformerImpl transformer = (TransformerImpl) handler.getTransformer(); DTM dtm = transformer.getXPathContext().getDTM(src); for (int node = dtm.getFirstAttribute(src...
python
def potentiallayers(self, x, y, layers, aq=None): '''Returns array of size len(layers) only used in building equations Defined here as it is the particular solution inside a semi-confined aquifer and cannot be added by using eigen vectors''' if aq is None: aq = self.model.aq.find_aquifer...
python
def get_winner(trials): """Get winner trial of a job.""" winner = {} # TODO: sort_key should be customized here sort_key = "accuracy" if trials and len(trials) > 0: first_metrics = get_trial_info(trials[0])["metrics"] if first_metrics and not first_metrics.get("accuracy", None): ...
python
def ProcessBlocks(self, block_limit=1000): """ Method called on a loop to check the current height of the blockchain. If the height of the blockchain is more than the current stored height in the wallet, we get the next block in line and processes it. In the case that the walle...
python
def create_parser(): """Create the argument parser for iotile.""" parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging level (goes error, warn, info, debug)") ...
java
public static <T> T fromXml(String xml, Class<T> clazz) { try { StringReader reader = new StringReader(xml); return (T) createUnmarshaller(clazz).unmarshal(reader); } catch (JAXBException e) { throw ExceptionUtil.unchecked(e); } }
python
def _build_iterable_validator(iterable): """Build a validator from an iterable.""" sub_schemas = [parse_schema(s) for s in iterable] def item_validator(value): """Validate items in an iterable.""" for sub in sub_schemas: try: return sub(value) except...
python
def _attr_display(value, html_element): ''' Set the display value ''' if value == 'block': html_element.display = Display.block elif value == 'none': html_element.display = Display.none else: html_element.display = Display.inline
java
@Override public DescribeMaintenanceWindowsForTargetResult describeMaintenanceWindowsForTarget(DescribeMaintenanceWindowsForTargetRequest request) { request = beforeClientExecution(request); return executeDescribeMaintenanceWindowsForTarget(request); }
java
public CouchDbSamlMetadataDocument merge(final SamlMetadataDocument document) { setId(document.getId()); setName(document.getName()); setValue(document.getValue()); setSignature(document.getSignature()); return this; }
python
def link(self): """Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark that running update persists the summary f...
java
@Override public void setServerDefaultSSLContext(SSLConfig defaultSSLConfig) throws Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "setServerDefaultSSLContext"); SSLContext context = getSSLContext(null, defaultSSLConfig); if (context !...
java
public static short toType(String strType) throws RegistryException { if (strType.equals(REGDWORD_TOKEN)) return RegistryEntry.TYPE_DWORD; else if (strType.equals(REGSTR_TOKEN)) return RegistryEntry.TYPE_STRING; else if (strType.equals(REGKEY_TOKEN)) return RegistryEntry.TYPE_KEY; throw new RegistryException(strTyp...
python
def remove_existID_pixels(givenvalue_pixels_positions, idx_array): """Delete the existed ID pixels who's in nparray idx_array After computing pixels connectivity, we get a set of pixels which have connectivity and have the same ID. We get these pixels positions set as nparray idx_array as well. Th...
java
protected TranWrapper getCurrentTranWrapper() throws ResourceException { final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled(); if (isTracingEnabled && tc.isEntryEnabled()) { Tr.entry(this, tc, "getCurrentTranWrapper"); } // If the MCWrapper has not been co...
java
public static com.liferay.commerce.product.model.CPSpecificationOption deleteCPSpecificationOption( com.liferay.commerce.product.model.CPSpecificationOption cpSpecificationOption) throws com.liferay.portal.kernel.exception.PortalException { return getService().deleteCPSpecificationOption(cpSpecificationOption); ...
python
def percentile(self, percent): """Return the value that is the Nth precentile in the histogram. Args: percent (Union[int, float]): The precentile being sought. The default consumer implementations use consistently use ``99``. Returns: int: The value corr...
python
def git_status_all_repos(cat, hard=True, origin=False, clean=True): """Perform a 'git status' in each data repository. """ log = cat.log log.debug("gitter.git_status_all_repos()") all_repos = cat.PATHS.get_all_repo_folders() for repo_name in all_repos: log.info("Repo in: '{}'".format(re...
python
def get_col_data_by_name(self, col_name, WHERE_Clause=''): """ returns the values of col_name according to where """ #print('get_col_data_by_name: col_name = ', col_name, ' WHERE = ', WHERE_Clause) col_key = self.get_col_by_name(col_name) if col_key is None: print('get_col_da...
java
public static void addExistingImports (String asFile, ImportSet imports) { // Discover the location of the 'public class' declaration. // We won't search past there. Matcher m = AS_PUBLIC_CLASS_DECL.matcher(asFile); int searchTo = asFile.length(); if (m.find()) { ...
python
def verify_system_status(self): """Verify system status.""" if not sys.platform.startswith('linux'): raise InstallError('Supported platform is Linux only.') if self.python.is_system_python(): if self.python.is_python_binding_installed(): message = ''' RPM...
java
public void start() throws Exception { super.start(); if (!javax.servlet.Filter.class .isAssignableFrom(_class)) { super.stop(); throw new IllegalStateException(_class+" is not a javax.servlet.Filter"); } _filter=(Filter)n...
java
@Override public PersistenceSpaceIdentifier<DiskResourceService> getPersistenceSpaceIdentifier(String name, CacheConfiguration<?, ?> config) throws CachePersistenceException { if (persistenceService == null) { return null; } boolean persistent = config.getResourcePools().getPoolForResource(ResourceT...
java
public Observable<Void> purgeDeletedCertificateAsync(String vaultBaseUrl, String certificateName) { return purgeDeletedCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> respon...
java
public static <T> List<T> merge(List<List<T>> list) { return list.stream().flatMap(Collection::stream).collect(Collectors.toList()); }
python
def is_orthonormal(self): """ Compute a matrix of Hilbert-Schmidt inner products for the basis operators, and see if they are orthonormal. If they are return True, else, False. :return: True if the basis vectors represented by this OperatorBasis are orthonormal, False otherwise...
java
public void retryLastFailedTask(String workflowId) { Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank"); stub.retryWorkflow(WorkflowServicePb.RetryWorkflowRequest.newBuilder() .setWorkflowId(workflowId) .build() ); }
python
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
java
public static base_response kill(nitro_service client, systemsession resource) throws Exception { systemsession killresource = new systemsession(); killresource.sid = resource.sid; killresource.all = resource.all; return killresource.perform_operation(client,"kill"); }
python
def unique_field(self, field_name): """set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...)""" self.fields_set.options["unique"] = True return self.select_field(field_name)
java
private void installChecksums( File installedFile ) throws MojoExecutionException { boolean signatureFile = installedFile.getName().endsWith( ".asc" ); if ( installedFile.isFile() && !signatureFile ) { installChecksum( installedFile, installedFile, md5Digester, ".md5"...
java
public void fetchRemaining() throws SQLException { if (!isEof) { lock.lock(); try { lastRowPointer = -1; while (!isEof) { addStreamingValue(); } } catch (SQLException queryException) { throw ExceptionMapper.getException(queryException, null, statement, fa...
java
Object forceRemoveField(String name) { int saved_state = _state; try { _state = __MSG_EDITABLE; return removeField(name); } finally { _state = saved_state; } }
python
def ipath_from_ext(self, ext): """ Returns the path of the input file with extension ext. Use it when the file does not exist yet. """ return os.path.join(self.workdir, self.prefix.idata + "_" + ext)
python
def scatter2d(data_list, channels=[0,1], xscale='logicle', yscale='logicle', xlabel=None, ylabel=None, xlim=None, ylim=None, title=None, color=None, savefig=None, **...
python
def tempfile(self): "write the docx to a named tmpfile and return the tmpfile filename" tf = tempfile.NamedTemporaryFile() tfn = tf.name tf.close() os.remove(tf.name) shutil.copy(self.fn, tfn) return tfn
java
@SuppressWarnings("unchecked") @Override public T where(final CharSequence rawString) { this.rawStrings.add(rawString); this.useOperator = true; return (T) this; }
java
protected IConceptSet getA(int B, int r) { if (B >= CONCEPTS) { resizeConcepts(B); } if (r >= ROLES) { resizeRoles(r); } // Note the "+1" in the following line: final int index = indexOf(B, r) + 1; if (null == data[index]) { ...
python
def _standalone(argv): """Parse the given input directory and emit generated code.""" varprefix = "GEOCODE" per_locale = True separator = None chunks = -1 try: opts, args = getopt.getopt(argv, "hv:fs:c:", ("help", "var=", "flat", "sep=", "chunks=")) except getopt.GetoptError: ...
java
private String getFixedName (Class<? extends ComponentSystemEvent> cls) { StringBuilder result = new StringBuilder(); String className; // Get the unqualified class name. className = cls.getSimpleName(); // Strip the trailing "event" off the class n...
java
public void init(Object text) { this.setOpaque(false); this.setPreferredSize(PREFERRED_SIZE); int rows = 1; int cols = 30; m_control = new JTextArea(rows, cols); m_control.setBorder(null); // No border inside a scroller. JScrollPane scrollpane = new JScro...
java
private E evict() { switch (evictPolicy) { case EVICT_OLDEST: return deque.pollFirst(); case EVICT_NEWEST: return deque.pollLast(); default: throw new IllegalStateException("Illegal evict policy: " + evictPolicy); } ...
python
def save(self, record_key, record_data, overwrite=True, secret_key=''): ''' a method to create a record in the collection folder :param record_key: string with name to assign to record (see NOTES below) :param record_data: byte data for record body :param overwrite:...
java
@Override public void set(int row, int col, double val) { super.set(row, col, val); version.incrementAndGet(); }
python
def get_description_lines(docstring): """Extract the description from the given docstring. This grabs everything up to the first occurrence of something that looks like a parameter description. The docstring will be dedented and cleaned up using the standard Sphinx methods. :param str docstring: T...
python
def activate(self, engine): """ Activates the Component. :param engine: Engine to attach the Component to. :type engine: QObject :return: Method success. :rtype: bool """ LOGGER.debug("> Activating '{0}' Component.".format(self.__class__.__name__)) ...
java
public static ImageFormat getImageFormat_WrapIOException(final InputStream is) { try { return getImageFormat(is); } catch (IOException ioe) { throw Throwables.propagate(ioe); } }
python
def kdf_salt(self): """ Returns the byte string to use as the salt for the KDF. :return: A byte string """ encryption_algo = self['algorithm'].native if encryption_algo == 'pbes2': salt = self['parameters']['key_derivation_func']['parameters']['...
java
static NeutronApi neutronApi( Map<String,String> targetProperties ) throws TargetException { validate( targetProperties ); return ContextBuilder .newBuilder( PROVIDER_NEUTRON ) .endpoint( targetProperties.get( API_URL )) .credentials( identity( targetProperties ), targetProperties.get( PASSWORD )) ...
java
private List createPoints(int numberOfSegments, float radius, float cx, float cy, float start, float end) { ArrayList tempPoints = new ArrayList(); int step = 360 / numberOfSegments; for (float a=start;a<=end+step;a+=step) { float ang = a; if (ang > end) ...
java
final Integer[] getDateValues(String filePath, Formatter formatter) { Pattern pattern = defaultPathPattern; switch (formatter) { case DEFAULT: case LOWER_DEFAULT: break; case HIVE: pattern = hivePathPattern; break; default: throw new IAE("Format %s not s...