language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@NotNull static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree, @NotNull final EnvironmentImpl env, @NotNull final ExpiredLoggableCollection expired) { final long newMetaTreeAddress = metaTree.save(); final Log log = env.getLog(); final int lastStructureId = env.getLastStructureId(); final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID, DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId)); expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress)); return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress); }
java
public <T> V fetch(K key, Functor<V, T> functor, T argument) throws Exception { return locate(key).get(functor, argument); }
python
def open(cls, filename, band_names=None, lazy_load=True, mutable=False, **kwargs): """ Read a georaster from a file. :param filename: url :param band_names: list of strings, or string. if None - will try to read from image, otherwise - these will be ['0', ..] :param lazy_load: if True - do not load anything :return: GeoRaster2 """ if mutable: geo_raster = MutableGeoRaster(filename=filename, band_names=band_names, **kwargs) else: geo_raster = cls(filename=filename, band_names=band_names, **kwargs) if not lazy_load: geo_raster._populate_from_rasterio_object(read_image=True) return geo_raster
java
public static String weightingToFileName(Weighting w, boolean edgeBased) { return toLowerCase(w.toString()).replaceAll("\\|", "_") + (edgeBased ? "_edge" : "_node"); }
java
private static byte[] extract(byte[] salt, byte[] inputKeyingMaterial) { return initHmacSha256(salt == null ? NULL_SALT : salt).doFinal(inputKeyingMaterial); }
python
def _get_gcloud_records(self, gcloud_zone, page_token=None): """ Generator function which yields ResourceRecordSet for the managed gcloud zone, until there are no more records to pull. :param gcloud_zone: zone to pull records from :type gcloud_zone: google.cloud.dns.ManagedZone :param page_token: page token for the page to get :return: a resource record set :type return: google.cloud.dns.ResourceRecordSet """ gcloud_iterator = gcloud_zone.list_resource_record_sets( page_token=page_token) for gcloud_record in gcloud_iterator: yield gcloud_record # This is to get results which may be on a "paged" page. # (if more than max_results) entries. if gcloud_iterator.next_page_token: for gcloud_record in self._get_gcloud_records( gcloud_zone, gcloud_iterator.next_page_token): # yield from is in python 3 only. yield gcloud_record
java
private void updateAperture(int newValue, long now) { int previous = targetAperture; targetAperture = newValue; targetAperture = Math.max(minAperture, targetAperture); int maxAperture = Math.min(this.maxAperture, activeSockets.size() + pool.poolSize()); targetAperture = Math.min(maxAperture, targetAperture); lastApertureRefresh = now; pendings.reset((minPendings + maxPendings) / 2); if (targetAperture != previous) { logger.debug( "Current pending={}, new target={}, previous target={}", pendings.value(), targetAperture, previous); } }
java
public SDVariable[] batchMmul(String[] names, SDVariable[] matricesA, SDVariable[] matricesB, boolean transposeA, boolean transposeB) { validateSameType("batchMmul", true, matricesA); validateSameType("batchMmul", true, matricesB); SDVariable[] result = f().batchMmul(matricesA, matricesB, transposeA, transposeB); return updateVariableNamesAndReferences(result, names); }
java
private String toTag(String name, Archive source, Analyzer.Type type) { if (!isJDKArchive(source)) { return source.getName(); } JDKArchive jdk = (JDKArchive)source; boolean isExported = false; if (type == CLASS || type == VERBOSE) { isExported = jdk.isExported(name); } else { isExported = jdk.isExportedPackage(name); } Profile p = getProfile(name, type); if (isExported) { // exported API return options.showProfile && p != null ? p.profileName() : ""; } else { return "JDK internal API (" + source.getName() + ")"; } }
java
public ValidDBInstanceModificationsMessage withValidProcessorFeatures(AvailableProcessorFeature... validProcessorFeatures) { if (this.validProcessorFeatures == null) { setValidProcessorFeatures(new com.amazonaws.internal.SdkInternalList<AvailableProcessorFeature>(validProcessorFeatures.length)); } for (AvailableProcessorFeature ele : validProcessorFeatures) { this.validProcessorFeatures.add(ele); } return this; }
python
def libvlc_media_player_has_vout(p_mi): '''How many video outputs does this media player have? @param p_mi: the media player. @return: the number of video outputs. ''' f = _Cfunctions.get('libvlc_media_player_has_vout', None) or \ _Cfunction('libvlc_media_player_has_vout', ((1,),), None, ctypes.c_uint, MediaPlayer) return f(p_mi)
java
@Override public void start(BundleContext context) throws Exception { this.bundleContext = context; this.bundle = context.getBundle(); try { // check if another version of the bundle exists long myId = this.bundle.getBundleId(); String myName = this.bundle.getSymbolicName(); Bundle[] currentBundles = this.bundleContext.getBundles(); for (Bundle bundle : currentBundles) { if (myId != bundle.getBundleId() && myName.equals(bundle.getSymbolicName())) { // found another version of me handleAnotherVersionAtStartup(bundle); } } // set bundle's user-defined properties this.properties = new Properties(); properties.put(Constants.LOOKUP_PROP_VERSION, bundle.getVersion().toString()); String alias = alias(); if (!StringUtils.isEmpty(alias)) { properties.put(Constants.LOOKUP_PROP_MODULE, alias); } init(); } catch (Exception e) { _destroy(); throw e; } }
python
def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if message not in resource.error_message: if not resource.error_message: resource.error_message = message else: resource.error_message += ' (%s)' % message resource.save() logger.warning('%s %s (PK: %s) does not exist at backend.' % ( resource.__class__.__name__, resource, resource.pk))
java
public static String generateExactMatchPattern(URI origin, URI destination, String bindingVar, boolean includeUrisBound) { List<String> patterns = new ArrayList<String>(); // Exact match pattern StringBuffer query = new StringBuffer(); query.append(Util.generateSubclassPattern(origin, destination) + NL); query.append(Util.generateSuperclassPattern(origin, destination) + NL); patterns.add(query.toString()); // Find same term cases query = new StringBuffer(); query.append("FILTER (str("). append(sparqlWrapUri(origin)). append(") = str("). append(sparqlWrapUri(destination)). append(") ) . " + NL); patterns.add(query.toString()); StringBuffer result = new StringBuffer(generateUnionStatement(patterns)); // Bind a variable for inspection result.append("BIND (true as ?" + bindingVar + ") ." + NL); // Include origin and destination in the returned bindings if requested if (includeUrisBound) { result.append("BIND (").append(sparqlWrapUri(origin)).append(" as ?origin) .").append(NL); result.append("BIND (").append(sparqlWrapUri(destination)).append(" as ?destination) .").append(NL); } return result.toString(); }
java
private Mapper createMapper(Class<?> clazz) { Mapper mapper; if (Enum.class.isAssignableFrom(clazz)) { mapper = new EnumMapper(clazz); } else if (Map.class.isAssignableFrom(clazz)) { mapper = new MapMapper(clazz); } else if (clazz.isAnnotationPresent(Embeddable.class)) { mapper = new EmbeddedObjectMapper(clazz); } else { throw new NoSuitableMapperException( String.format("No mapper found for class %s", clazz.getName())); } return mapper; }
java
public boolean recordDeprecationReason(String reason) { if (currentInfo.setDeprecationReason(reason)) { populated = true; return true; } else { return false; } }
python
def _queue_declare_ok(self, args): """ confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ queue = args.read_shortstr() message_count = args.read_long() consumer_count = args.read_long() return queue, message_count, consumer_count
java
public Coding addAdditionalMaterial() { //3 Coding t = new Coding(); if (this.additionalMaterial == null) this.additionalMaterial = new ArrayList<Coding>(); this.additionalMaterial.add(t); return t; }
python
def kill_all(self, kill_signal, kill_shell=False): """Kill all running processes.""" for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)
python
def sub_working_days(self, day, delta, extra_working_days=None, extra_holidays=None, keep_datetime=False): """ Substract `delta` working days to the date. This method is a shortcut / helper. Users may want to use either:: cal.add_working_days(my_date, -7) cal.sub_working_days(my_date, 7) The other parameters are to be used exactly as in the ``add_working_days`` method. A negative ``delta`` argument will be converted into its absolute value. Hence, the two following calls are equivalent:: cal.sub_working_days(my_date, -7) cal.sub_working_days(my_date, 7) As in ``add_working_days()`` you can set the parameter ``keep_datetime`` to ``True`` to make sure that if your ``day`` argument is a ``datetime``, the returned date will also be a ``datetime`` object. """ delta = abs(delta) return self.add_working_days( day, -delta, extra_working_days, extra_holidays, keep_datetime=keep_datetime)
python
def prune(t): """Returns the currently defining instance of t. As a side effect, collapses the list of type instances. The function Prune is used whenever a type expression has to be inspected: it will always return a type expression which is either an uninstantiated type variable or a type operator; i.e. it will skip instantiated variables, and will actually prune them from expressions to remove long chains of instantiated variables. Args: t: The type to be pruned Returns: An uninstantiated TypeVariable or a TypeOperator """ if isinstance(t, TypeVariable): if t.instance is not None: t.instance = prune(t.instance) return t.instance return t
java
public static boolean deleteOrDie(@Nonnull final String file) throws IOException { // this returns true if the file was actually deleted // and false for 2 cases: // 1. file did not exist to start with // 2. File.delete() failed at some point for some reason // so we disambiguate the 'false' case below by checking for file existence final boolean fileWasDeleted = delete(file); if (fileWasDeleted) { // file was definitely deleted return true; } else { final File fileObj = new File(file); if (fileObj.exists()) { throw new IOException("File still exists after erasure, cannot write object to file: " + file); } // file was not deleted, because it does not exist return false; } }
python
def create_307_response(self): """ Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message received during processing the request. """ request = get_current_request() msg_mb = UserMessageMember(self.message) coll = request.root['_messages'] coll.add(msg_mb) # Figure out the new location URL. qs = self.__get_new_query_string(request.query_string, self.message.slug) resubmit_url = "%s?%s" % (request.path_url, qs) headers = [('Warning', '299 %s' % self.message.text), # ('Content-Type', cnt_type), ] http_exc = HttpWarningResubmit(location=resubmit_url, detail=self.message.text, headers=headers) return request.get_response(http_exc)
python
def options(self, context, module_options): ''' PATH Path to dll/exe to inject PROCID Process ID to inject into (default: current powershell process) EXEARGS Arguments to pass to the executable being reflectively loaded (default: None) ''' if not 'PATH' in module_options: context.log.error('PATH option is required!') exit(1) self.payload_path = os.path.expanduser(module_options['PATH']) if not os.path.exists(self.payload_path): context.log.error('Invalid path to EXE/DLL!') exit(1) self.procid = None self.exeargs = None if 'PROCID' in module_options: self.procid = module_options['PROCID'] if 'EXEARGS' in module_options: self.exeargs = module_options['EXEARGS'] self.ps_script = obfs_ps_script('powersploit/CodeExecution/Invoke-ReflectivePEInjection.ps1')
python
def format_atomic(value): """Format atomic value This function also takes care of escaping the value in case one of the reserved characters occurs in the value. """ # Perform escaping if isinstance(value, str): if any(r in value for r in record.RESERVED_CHARS): for k, v in record.ESCAPE_MAPPING: value = value.replace(k, v) # String-format the given value if value is None: return "." else: return str(value)
python
def extract_data(self): """Extracts data from archive. Returns: PackageData object containing the extracted data. """ data = PackageData( local_file=self.local_file, name=self.name, pkg_name=self.rpm_name or self.name_convertor.rpm_name( self.name, pkg_name=True), version=self.version, srcname=self.srcname) with self.archive: data.set_from(self.data_from_archive) # for example nose has attribute `packages` but instead of name # listing the pacakges is using function to find them, that makes # data.packages an empty set if virtualenv is disabled if self.venv_extraction_disabled and getattr(data, "packages") == []: data.packages = [data.name] return data
java
public static void hexToBits(String s, BitSet ba, int length) { byte[] b = hexToBytes(s); bytesToBits(b, ba, length); }
java
private void processCachedTimerDataSettings(BeanMetaData bmd) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) { Tr.entry(tc, "processCachedTimerDataSettings " + AllowCachedTimerDataFor); } //F001419: start if (AllowCachedTimerDataFor != null) { StringTokenizer st = new StringTokenizer(AllowCachedTimerDataFor, ":"); while (st.hasMoreTokens()) { String token = st.nextToken(); int assignmentPivot = token.indexOf('='); if (assignmentPivot > 0) { //case where we have 'j2eename=<integer>' or '*=<integer>' String lh = token.substring(0, assignmentPivot).trim(); //get j2eename or '*' if (lh.equals(bmd.j2eeName.toString()) || lh.equals("*")) { // d130438 String rh = token.substring(assignmentPivot + 1).trim();//get <integer> try { bmd.allowCachedTimerDataForMethods = Integer.parseInt(rh); bmd._moduleMetaData.ivAllowsCachedTimerData = true; break; } catch (NumberFormatException e) { FFDCFilter.processException(e, CLASS_NAME + ".processCachedTimerDataSettings", "3923", this); } } } else { //token did not include an equals sign....case where we have just 'j2eename' or '*'. Apply all caching in this case. if (token.equals(bmd.j2eeName.toString()) || token.equals("*")) { // d130438 bmd.allowCachedTimerDataForMethods = -1; // d642293 bmd._moduleMetaData.ivAllowsCachedTimerData = true; break; } } } // while loop } // allowCachedTimerDataForSpec not null if (isTraceOn && tc.isEntryEnabled()) { Tr.exit(tc, "processCachedTimerDataSettings " + bmd.allowCachedTimerDataForMethods); } }
java
public void setEveryWorkingDay(final boolean isEveryWorkingDay) { if (m_model.isEveryWorkingDay() != isEveryWorkingDay) { removeExceptionsOnChange(new Command() { public void execute() { m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay)); m_model.setInterval(getPatternDefaultValues().getInterval()); onValueChange(); } }); } }
python
def update_function(self, function_name, # type: str zip_contents, # type: str environment_variables=None, # type: StrMap runtime=None, # type: OptStr tags=None, # type: StrMap timeout=None, # type: OptInt memory_size=None, # type: OptInt role_arn=None, # type: OptStr subnet_ids=None, # type: OptStrList security_group_ids=None, # type: OptStrList layers=None, # type: OptStrList ): # type: (...) -> Dict[str, Any] """Update a Lambda function's code and configuration. This method only updates the values provided to it. If a parameter is not provided, no changes will be made for that that parameter on the targeted lambda function. """ return_value = self._update_function_code(function_name=function_name, zip_contents=zip_contents) self._update_function_config( environment_variables=environment_variables, runtime=runtime, timeout=timeout, memory_size=memory_size, role_arn=role_arn, subnet_ids=subnet_ids, security_group_ids=security_group_ids, function_name=function_name, layers=layers ) if tags is not None: self._update_function_tags(return_value['FunctionArn'], tags) return return_value
java
public final void mT__96() throws RecognitionException { try { int _type = T__96; int _channel = DEFAULT_TOKEN_CHANNEL; // BELScript.g:83:7: ( 'substitution' ) // BELScript.g:83:9: 'substitution' { match("substitution"); } state.type = _type; state.channel = _channel; } finally { } }
python
def _get_aliases(self): u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname. """ if self._aliases is None: self._aliases = {} if self._xml is not None: for child in self._xml.iterchildren(): self._aliases[helpers.normalize_tag(child.tag)] = child.tag return self._aliases
java
public String getFamilyName() { if (DocumentSpecies_Type.featOkTst && ((DocumentSpecies_Type)jcasType).casFeat_familyName == null) jcasType.jcas.throwFeatMissing("familyName", "ch.epfl.bbp.uima.types.DocumentSpecies"); return jcasType.ll_cas.ll_getStringValue(addr, ((DocumentSpecies_Type)jcasType).casFeatCode_familyName);}
python
def factor_for_trace(ls: HilbertSpace, op: Operator) -> Operator: r'''Given a :class:`.LocalSpace` `ls` to take the partial trace over and an operator `op`, factor the trace such that operators acting on disjoint degrees of freedom are pulled out of the trace. If the operator acts trivially on ls the trace yields only a pre-factor equal to the dimension of ls. If there are :class:`LocalSigma` operators among a product, the trace's cyclical property is used to move to sandwich the full product by :class:`LocalSigma` operators: .. math:: {\rm Tr} A \sigma_{jk} B = {\rm Tr} \sigma_{jk} B A \sigma_{jj} Args: ls: Degree of Freedom to trace over op: Operator to take the trace of Returns: The (partial) trace over the operator's spc-degrees of freedom ''' if op.space == ls: if isinstance(op, OperatorTimes): pull_out = [o for o in op.operands if o.space is TrivialSpace] rest = [o for o in op.operands if o.space is not TrivialSpace] if pull_out: return (OperatorTimes.create(*pull_out) * OperatorTrace.create(OperatorTimes.create(*rest), over_space=ls)) raise CannotSimplify() if ls & op.space == TrivialSpace: return ls.dimension * op if ls < op.space and isinstance(op, OperatorTimes): pull_out = [o for o in op.operands if (o.space & ls) == TrivialSpace] rest = [o for o in op.operands if (o.space & ls) != TrivialSpace] if (not isinstance(rest[0], LocalSigma) or not isinstance(rest[-1], LocalSigma)): for j, r in enumerate(rest): if isinstance(r, LocalSigma): m = r.j rest = ( rest[j:] + rest[:j] + [LocalSigma.create(m, m, hs=ls), ]) break if not rest: rest = [IdentityOperator] if len(pull_out): return (OperatorTimes.create(*pull_out) * OperatorTrace.create(OperatorTimes.create(*rest), over_space=ls)) raise CannotSimplify()
java
public TableInformation getRealTableInformation(final Connection _con, final String _tableName) throws SQLException { final TableInformation tableInfo = new TableInformation(_tableName.toUpperCase()); final Map<String, TableInformation> tableInfos = new HashMap<>(1); tableInfos.put(_tableName.toUpperCase(), tableInfo); this.initTableInfoColumns(_con, null, tableInfos); this.initTableInfoUniqueKeys(_con, null, tableInfos); this.initTableInfoForeignKeys(_con, null, tableInfos); return tableInfo; }
python
def contains_pyversion(marker): """Check whether a marker contains a python_version operand. """ if not marker: return False marker = _ensure_marker(marker) return _markers_contains_pyversion(marker._markers)
python
def _update_info(self): """ Update metadata for this HDU """ try: self._FITS.movabs_hdu(self._ext+1) except IOError: raise RuntimeError("no such hdu") self._info = self._FITS.get_hdu_info(self._ext+1)
java
public SightPublish setPublishStatus(long sightId, SightPublish sightPublish) throws SmartsheetException { Util.throwIfNull(sightPublish); return this.updateResource("sights/" + sightId + "/publish", SightPublish.class, sightPublish); }
java
public static void process(CharSequence html, OutputStream output) { new TableToXls().doProcess( html instanceof String ? (String) html : html.toString(), output); }
python
def safe_str(value): """ Returns: * a `str` instance (bytes) in Python 2.x, or * a `str` instance (Unicode) in Python 3.x. """ if sys.version_info < (3,0) and isinstance(value, unicode): return value.encode('utf-8') else: return str(value)
java
public static List<TagEntryAO> tagsMapToTagEntries(Map<String, String> tagsMap) { if (tagsMap==null) return Collections.EMPTY_LIST; List<TagEntryAO> tagEntries = new ArrayList<>(tagsMap.size()); for (Map.Entry<String,String> entry : tagsMap.entrySet()) tagEntries.add( new TagEntryAO(entry.getKey(), entry.getValue()) ); return tagEntries; }
python
def dedent(string, indent_str=' ', max_levels=None): """Revert the effect of indentation. Examples -------- Remove a simple one-level indentation: >>> text = '''<->This is line 1. ... <->Next line. ... <->And another one.''' >>> print(text) <->This is line 1. <->Next line. <->And another one. >>> print(dedent(text, '<->')) This is line 1. Next line. And another one. Multiple levels of indentation: >>> text = '''<->Level 1. ... <-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <->Level 1. <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 1. <->Level 2. <-><->Level 3. >>> text = '''<-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 2. <->Level 3. >>> print(dedent(text, '<->', max_levels=1)) <->Level 2. <-><->Level 3. """ if len(indent_str) == 0: return string lines = string.splitlines() # Determine common (minumum) number of indentation levels, capped at # `max_levels` if given def num_indents(line): max_num = int(np.ceil(len(line) / len(indent_str))) for i in range(max_num): if line.startswith(indent_str): line = line[len(indent_str):] else: break return i num_levels = num_indents(min(lines, key=num_indents)) if max_levels is not None: num_levels = min(num_levels, max_levels) # Dedent dedent_len = num_levels * len(indent_str) return '\n'.join(line[dedent_len:] for line in lines)
python
def read_dictionary_file(dictionary_path): """Return all words in dictionary file as set.""" try: return _user_dictionary_cache[dictionary_path] except KeyError: if dictionary_path and os.path.exists(dictionary_path): with open(dictionary_path, "rt") as dict_f: words = set(re.findall(r"(\w[\w']*\w|\w)", " ".join(dict_f.read().splitlines()))) return words return set()
python
def convertASTtoThreeAddrForm(ast): """Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory. """ return [(node.value, node.reg) + tuple([c.reg for c in node.children]) for node in ast.allOf('op')]
python
def get_store_credit_transaction_by_id(cls, store_credit_transaction_id, **kwargs): """Find StoreCreditTransaction Return single instance of StoreCreditTransaction by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_credit_transaction_by_id(store_credit_transaction_id, async=True) >>> result = thread.get() :param async bool :param str store_credit_transaction_id: ID of storeCreditTransaction to return (required) :return: StoreCreditTransaction If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_store_credit_transaction_by_id_with_http_info(store_credit_transaction_id, **kwargs) else: (data) = cls._get_store_credit_transaction_by_id_with_http_info(store_credit_transaction_id, **kwargs) return data
python
def get_staking_cutoff(self, round_num=0, tournament=1): """Compute staking cutoff for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: cutoff probability Raises: ValueError: in case of missing prize pool information """ query = ''' query($number: Int! $tournament: Int!) { rounds(number: $number tournament: $tournament) { selection { outcome pCutoff bCutoff } } } ''' arguments = {'number': round_num, 'tournament': tournament} result = self.raw_query(query, arguments) result = result['data']['rounds'][0]['selection'] key = 'bCutoff' if round_num >= 154 or round_num == 0 else 'pCutoff' return utils.parse_float_string(result[key])
python
def find_callback(args, kw=None): 'Return callback whether passed as a last argument or as a keyword' if args and callable(args[-1]): return args[-1], args[:-1] try: return kw['callback'], args except (KeyError, TypeError): return None, args
java
protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException, BadPdfFormatException { PdfIndirectReference theRef; RefKey key = new RefKey(in); IndirectReferences iRef = (IndirectReferences)indirects.get(key); if (iRef != null) { theRef = iRef.getRef(); if (iRef.getCopied()) { return theRef; } } else { theRef = body.getPdfIndirectReference(); iRef = new IndirectReferences(theRef); indirects.put(key, iRef); } PdfObject obj = PdfReader.getPdfObjectRelease(in); if (obj != null && obj.isDictionary()) { PdfObject type = PdfReader.getPdfObjectRelease(((PdfDictionary)obj).get(PdfName.TYPE)); if (type != null && PdfName.PAGE.equals(type)) { return theRef; } } iRef.setCopied(); obj = copyObject(obj); addToBody(obj, theRef); return theRef; }
java
public K findKey (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { K[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != null && valueTable[i] == null) return keyTable[i]; } else if (identity) { for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return null; }
python
def shlex_split(s, **kwargs): ''' Only split if variable is a string ''' if isinstance(s, six.string_types): # On PY2, shlex.split will fail with unicode types if there are # non-ascii characters in the string. So, we need to make sure we # invoke it with a str type, and then decode the resulting string back # to unicode to return it. return salt.utils.data.decode( shlex.split(salt.utils.stringutils.to_str(s), **kwargs) ) else: return s
python
def info2dicts(info, in_place=False): """ Return info with: 1) `packages` list replaced by a 'packages' dict indexed by 'project' 2) `releases` list replaced by a 'releases' dict indexed by 'name' """ if 'packages' not in info and 'releases' not in info: return info if in_place: info_dicts = info else: info_dicts = info.copy() packages = info.get('packages') if packages: info_dicts['packages'] = list2dict(packages, 'project') releases = info.get('releases') if releases: info_dicts['releases'] = list2dict(releases, 'name') return info_dicts
python
def check_url(url): ''' Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code} ''' request = urllib2.Request(url) try: response = urlopen(request) return True, response.code except urllib2.HTTPError as e: return False, e.code
python
def select_storage_for(cls, section_name, storage): """Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: Data storage to use. :return: :param:`storage` or a part of it (as section storage). """ section_storage = storage storage_name = cls.get_storage_name_for(section_name) if storage_name: section_storage = storage.get(storage_name, None) if section_storage is None: section_storage = storage[storage_name] = dict() return section_storage
java
final void randomizePrefix() { byte[] cb = new byte[preLen]; // Use SecureRandom for prefix only srand.nextBytes(cb); for (int i = 0; i < preLen; i++) { pre[i] = digits[(cb[i] & 0xFF) % base]; } }
java
public void putDefaultClasspathEntriesIn(Collection<IClasspathEntry> classpathEntries) { final IPath newPath = this.jreGroup.getJREContainerPath(); if (newPath != null) { classpathEntries.add(JavaCore.newContainerEntry(newPath)); } else { final IClasspathEntry[] entries = PreferenceConstants.getDefaultJRELibrary(); classpathEntries.addAll(Arrays.asList(entries)); } final IClasspathEntry sarlClasspathEntry = JavaCore.newContainerEntry( SARLClasspathContainerInitializer.CONTAINER_ID, new IAccessRule[0], new IClasspathAttribute[0], true); classpathEntries.add(sarlClasspathEntry); }
java
public Matrix4 setToTransform (IVector3 translation, IQuaternion rotation) { return setToRotation(rotation).setTranslation(translation); }
java
public void process() { try { check(); boolean isReconcilePhase = false; // In the Eclipse IDE's integration between JDT and APT, annotation processors // run in two phases -- reconcile and build. These translate into the // check and generate phases for a TwoPhaseAnnotationProcessor. In order to // optimize for hosting in this environment (and other IDE-centric AP environments) // the generate phase can be cut out when performing only the check phase. // Custom AP environments that wish to control this shoudl set the "phase" flag of the // annotation processor to "RECONCILE". try { String phase = (String)CompilerUtils.isReconcilePhase(getAnnotationProcessorEnvironment()); isReconcilePhase = "RECONCILE".equals(phase); } catch(FatalCompileTimeException e) { e.printDiagnostic(this); } // Do not call generate if check resulted in errors of if the AP is running in // a phase called "reconcile" if (!isReconcilePhase && !hasErrors()) { generate(); } } catch ( FatalCompileTimeException e ) { e.printDiagnostic( this ); } }
python
def _run(self): # type: (SyncCopy) -> None """Execute SyncCopy :param SyncCopy self: this """ # mark start self._start_time = blobxfer.util.datetime_now() logger.info('blobxfer start time: {0}'.format(self._start_time)) # initialize resume db if specified if self._general_options.resume_file is not None: self._resume = blobxfer.operations.resume.SyncCopyResumeManager( self._general_options.resume_file) # initialize download threads self._initialize_transfer_threads() # iterate through source paths to download processed_files = 0 for src_ase, dst_ase in self._bind_sources_to_destination(): processed_files += 1 if self._general_options.dry_run: logger.info('[DRY RUN] synccopy: {} -> {}'.format( src_ase.path, dst_ase.path)) else: # add transfer to set with self._transfer_lock: self._transfer_set.add( blobxfer.operations.synccopy.SyncCopy. create_unique_transfer_operation_id(src_ase, dst_ase)) self._synccopy_total += 1 self._synccopy_bytes_total += src_ase.size if blobxfer.util.is_not_empty(dst_ase.replica_targets): self._synccopy_bytes_total += ( len(dst_ase.replica_targets) * src_ase.size ) self._add_to_transfer_queue(src_ase, dst_ase) # set remote files processed with self._transfer_lock: self._all_remote_files_processed = True synccopy_size_mib = ( self._synccopy_bytes_total / blobxfer.util.MEGABYTE ) logger.debug( ('{0} remote files to sync, waiting for copy ' 'completion of approx. {1:.4f} MiB').format( processed_files, synccopy_size_mib)) del processed_files # wait for downloads to complete self._wait_for_transfer_threads(terminate=False) end_time = blobxfer.util.datetime_now() # update progress bar self._update_progress_bar() # check for exceptions if len(self._exceptions) > 0: logger.error('exceptions encountered while downloading') # raise the first one raise self._exceptions[0] # check for mismatches if (self._synccopy_sofar != self._synccopy_total or self._synccopy_bytes_sofar != self._synccopy_bytes_total): raise RuntimeError( 'copy mismatch: [count={}/{} bytes={}/{}]'.format( self._synccopy_sofar, self._synccopy_total, self._synccopy_bytes_sofar, self._synccopy_bytes_total)) # delete all remaining local files not accounted for if # delete extraneous enabled self._delete_extraneous_files() # delete resume file if we've gotten this far if self._resume is not None: self._resume.delete() # output throughput if self._synccopy_start_time is not None: dltime = (end_time - self._synccopy_start_time).total_seconds() synccopy_size_mib = ( (self._synccopy_bytes_total << 1) / blobxfer.util.MEGABYTE ) dlmibspeed = synccopy_size_mib / dltime logger.info( ('elapsed copy time and throughput of {0:.4f} ' 'GiB: {1:.3f} sec, {2:.4f} Mbps ({3:.3f} MiB/sec)').format( synccopy_size_mib / 1024, dltime, dlmibspeed * 8, dlmibspeed)) end_time = blobxfer.util.datetime_now() logger.info('blobxfer end time: {0} (elapsed: {1:.3f} sec)'.format( end_time, (end_time - self._start_time).total_seconds()))
java
private byte[] alloc() { position = 0; chunk++; if (chunk >= pool.size()) { byte[] bytes = new byte[chunk == 0 ? initialSize : incrementalSize]; pool.add(bytes); } return chunk(); }
java
public synchronized void removeCommandPolling(final CommandImpl command) throws DevFailed { if (commandCacheMap.containsKey(command)) { final CommandCache cache = commandCacheMap.get(command); cache.stopRefresh(); commandCacheMap.remove(command); } else if (extTrigCommandCacheMap.containsKey(command)) { extTrigCommandCacheMap.remove(command); } else if (command.getName().equalsIgnoreCase(DeviceImpl.STATE_NAME) && stateCache != null) { stateCache.stopRefresh(); stateCache = null; } else if (command.getName().equalsIgnoreCase(DeviceImpl.STATUS_NAME) && statusCache != null) { statusCache.stopRefresh(); statusCache = null; } }
java
protected Element grabArticle(boolean preserveUnlikelyCandidates) { /** * First, node prepping. Trash nodes that look cruddy (like ones with * the class name "comment", etc), and turn divs into P tags where they * have been used inappropriately (as in, where they contain no other * block level elements.) * * Note: Assignment from index for performance. See * http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5 TODO: * Shouldn't this be a reverse traversal? **/ for (Element node : mDocument.getAllElements()) { /* Remove unlikely candidates */ if (!preserveUnlikelyCandidates) { String unlikelyMatchString = node.className() + node.id(); Matcher unlikelyCandidatesMatcher = Patterns.get( Patterns.RegEx.UNLIKELY_CANDIDATES).matcher( unlikelyMatchString); Matcher maybeCandidateMatcher = Patterns.get( Patterns.RegEx.OK_MAYBE_ITS_A_CANDIDATE).matcher( unlikelyMatchString); if (unlikelyCandidatesMatcher.find() && maybeCandidateMatcher.find() && !"body".equalsIgnoreCase(node.tagName())) { node.remove(); dbg("Removing unlikely candidate - " + unlikelyMatchString); continue; } } /* * Turn all divs that don't have children block level elements into * p's */ if ("div".equalsIgnoreCase(node.tagName())) { Matcher matcher = Patterns .get(Patterns.RegEx.DIV_TO_P_ELEMENTS).matcher( node.html()); if (!matcher.find()) { dbg("Alternating div to p: " + node); try { node.tagName("p"); } catch (Exception e) { dbg("Could not alter div to p, probably an IE restriction, reverting back to div.", e); } } } } /** * Loop through all paragraphs, and assign a score to them based on how * content-y they look. Then add their score to their parent node. * * A score is determined by things like number of commas, class names, * etc. Maybe eventually link density. **/ Elements allParagraphs = mDocument.getElementsByTag("p"); ArrayList<Element> candidates = new ArrayList<Element>(); for (Element node : allParagraphs) { Element parentNode = node.parent(); Element grandParentNode = parentNode.parent(); String innerText = getInnerText(node, true); /* * If this paragraph is less than 25 characters, don't even count * it. */ if (innerText.length() < 25) { continue; } /* Initialize readability data for the parent. */ if (!parentNode.hasAttr("readabilityContentScore")) { initializeNode(parentNode); candidates.add(parentNode); } /* Initialize readability data for the grandparent. */ if (!grandParentNode.hasAttr("readabilityContentScore")) { initializeNode(grandParentNode); candidates.add(grandParentNode); } int contentScore = 0; /* Add a point for the paragraph itself as a base. */ contentScore++; /* Add points for any commas within this paragraph */ contentScore += innerText.split(",").length; /* * For every 100 characters in this paragraph, add another point. Up * to 3 points. */ contentScore += Math.min(Math.floor(innerText.length() / 100), 3); /* Add the score to the parent. The grandparent gets half. */ incrementContentScore(parentNode, contentScore); incrementContentScore(grandParentNode, contentScore / 2); } /** * After we've calculated scores, loop through all of the possible * candidate nodes we found and find the one with the highest score. */ Element topCandidate = null; for (Element candidate : candidates) { /** * Scale the final candidates score based on link density. Good * content should have a relatively small link density (5% or less) * and be mostly unaffected by this operation. */ scaleContentScore(candidate, 1 - getLinkDensity(candidate)); dbg("Candidate: (" + candidate.className() + ":" + candidate.id() + ") with score " + getContentScore(candidate)); if (topCandidate == null || getContentScore(candidate) > getContentScore(topCandidate)) { topCandidate = candidate; } } /** * If we still have no top candidate, just use the body as a last * resort. We also have to copy the body node so it is something we can * modify. */ if (topCandidate == null || "body".equalsIgnoreCase(topCandidate.tagName())) { topCandidate = mDocument.createElement("div"); topCandidate.html(mDocument.body().html()); mDocument.body().html(""); mDocument.body().appendChild(topCandidate); initializeNode(topCandidate); } /** * Now that we have the top candidate, look through its siblings for * content that might also be related. Things like preambles, content * split by ads that we removed, etc. */ Element articleContent = mDocument.createElement("div"); articleContent.attr("id", "readability-content"); int siblingScoreThreshold = Math.max(10, (int) (getContentScore(topCandidate) * 0.2f)); Elements siblingNodes = topCandidate.parent().children(); for (Element siblingNode : siblingNodes) { boolean append = false; dbg("Looking at sibling node: (" + siblingNode.className() + ":" + siblingNode.id() + ")" + " with score " + getContentScore(siblingNode)); if (siblingNode == topCandidate) { append = true; } if (getContentScore(siblingNode) >= siblingScoreThreshold) { append = true; } if ("p".equalsIgnoreCase(siblingNode.tagName())) { float linkDensity = getLinkDensity(siblingNode); String nodeContent = getInnerText(siblingNode, true); int nodeLength = nodeContent.length(); if (nodeLength > 80 && linkDensity < 0.25f) { append = true; } else if (nodeLength < 80 && linkDensity == 0.0f && nodeContent.matches(".*\\.( |$).*")) { append = true; } } if (append) { dbg("Appending node: " + siblingNode); /* * Append sibling and subtract from our list because it removes * the node when you append to another node */ articleContent.appendChild(siblingNode); continue; } } /** * So we have all of the content that we need. Now we clean it up for * presentation. */ prepArticle(articleContent); return articleContent; }
java
public final BaseTable makeTable(Record record) { BaseTable table = this.doMakeTable(record); if (DBConstants.TRUE.equalsIgnoreCase(this.getProperty(DBConstants.BASE_TABLE_ONLY))) return this.returnBaseTable(table); int iRawDBType = (record.getDatabaseType() & DBConstants.TABLE_TYPE_MASK); if ((iRawDBType == DBConstants.LOCAL) || (iRawDBType == DBConstants.REMOTE) || (iRawDBType == DBConstants.TABLE)) if ((this.getMasterSlave() & RecordOwner.SLAVE) == RecordOwner.SLAVE) // Do this at the server only { if ((record.getDatabaseType() & DBConstants.LOCALIZABLE) == DBConstants.LOCALIZABLE) { m_databaseLocale = this.makeDBLocale(record, m_databaseLocale); // Check the local database to make sure it is correct if (m_databaseLocale != this) table = this.makeResourceTable(record, table, m_databaseLocale, false); // Add the locale capability if it exists } if (m_databaseBase != null) if ((record.getDatabaseType() & DBConstants.HIERARCHICAL) == DBConstants.HIERARCHICAL) table = this.makeResourceTable(record, table, m_databaseBase, true); // Add the base database if it exists } return table; }
python
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolute[genome].append((bases / total) * float(100)) index += 1 total_assembled = [0 for i in absolute[genome]] for genome in absolute: index = 0 for cov in absolute[genome]: total_assembled[index] += cov index += 1 absolute['Unassembled'] = [(100 - i) for i in total_assembled] return absolute
python
def parse (self, lines): """Parse the input lines from a robot.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. @return: None """ log.debug(LOG_CHECK, "%r parse lines", self.url) state = 0 linenumber = 0 entry = Entry() for line in lines: line = line.strip() linenumber += 1 if not line: if state == 1: log.debug(LOG_CHECK, "%r line %d: allow or disallow directives without any user-agent line", self.url, linenumber) entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: log.debug(LOG_CHECK, "%r line %d: missing blank line before user-agent directive", self.url, linenumber) self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state == 0: log.debug(LOG_CHECK, "%r line %d: missing user-agent directive before this line", self.url, linenumber) pass else: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state == 0: log.debug(LOG_CHECK, "%r line %d: missing user-agent directive before this line", self.url, linenumber) pass else: entry.rulelines.append(RuleLine(line[1], True)) state = 2 elif line[0] == "crawl-delay": if state == 0: log.debug(LOG_CHECK, "%r line %d: missing user-agent directive before this line", self.url, linenumber) pass else: try: entry.crawldelay = max(0, int(line[1])) state = 2 except (ValueError, OverflowError): log.debug(LOG_CHECK, "%r line %d: invalid delay number %r", self.url, linenumber, line[1]) pass elif line[0] == "sitemap": # Note that sitemap URLs must be absolute according to # http://www.sitemaps.org/protocol.html#submit_robots # But this should be checked by the calling layer. self.sitemap_urls.append((line[1], linenumber)) else: log.debug(LOG_CHECK, "%r line %d: unknown key %r", self.url, linenumber, line[0]) pass else: log.debug(LOG_CHECK, "%r line %d: malformed line %r", self.url, linenumber, line) pass if state in (1, 2): self.entries.append(entry) self.modified() log.debug(LOG_CHECK, "Parsed rules:\n%s", str(self))
java
public com.squareup.okhttp.Call getCharactersCharacterIdFwStatsAsync(Integer characterId, String datasource, String ifNoneMatch, String token, final ApiCallback<CharacterFwStatsResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getCharactersCharacterIdFwStatsValidateBeforeCall(characterId, datasource, ifNoneMatch, token, callback); Type localVarReturnType = new TypeToken<CharacterFwStatsResponse>() { }.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
python
def list_feeds(): """List all feeds in plain text and give their aliases""" with Database("feeds") as feeds, Database("aliases") as aliases_db: for feed in feeds: name = feed url = feeds[feed] aliases = [] for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())): if v == name: aliases.append(k) if aliases: print(name, " : %s Aliases: %s" % (url, aliases)) else: print(name, " : %s" % url)
python
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, store in self.stores.items(): store.begin() indexes = self.indexes[collection] for index in indexes.values(): index.begin()
python
def done(self, result, noraise=False): """This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end. """ # [??] Should this be in a critical section? # Has done() already been called on this task? if self.ev_done.is_set(): # ?? if isinstance(self.result, Exception) and (not noraise): raise self.result return self.result # calculate running time and other finalization self.endtime = time.time() try: self.totaltime = self.endtime - self.starttime except AttributeError: # task was not initialized properly self.totaltime = 0.0 self.result = result # Release thread waiters self.ev_done.set() # Perform callbacks for event-style waiters self.make_callback('resolved', self.result) # If the result is an exception, then our final act is to raise # it in the caller, unless the caller explicitly supressed that if isinstance(result, Exception) and (not noraise): raise result return result
java
public String stats(int printPrecision) { StringBuilder sb = new StringBuilder(); //Report: Accuracy, precision, recall, F1. Then: confusion matrix int maxLabelsLength = 15; if (labels != null) { for (String s : labels) { maxLabelsLength = Math.max(s.length(), maxLabelsLength); } } String subPattern = "%-12." + printPrecision + "f"; String pattern = "%-" + (maxLabelsLength + 5) + "s" //Label + subPattern + subPattern + subPattern + subPattern //Accuracy, f1, precision, recall + "%-8d%-7d%-7d%-7d%-7d"; //Total count, TP, TN, FP, FN String patternHeader = "%-" + (maxLabelsLength + 5) + "s%-12s%-12s%-12s%-12s%-8s%-7s%-7s%-7s%-7s"; List<String> headerNames = Arrays.asList("Label", "Accuracy", "F1", "Precision", "Recall", "Total", "TP", "TN", "FP", "FN"); if (rocBinary != null) { patternHeader += "%-12s"; pattern += subPattern; headerNames = new ArrayList<>(headerNames); headerNames.add("AUC"); } String header = String.format(patternHeader, headerNames.toArray()); sb.append(header); if (countTrueNegative != null) { for (int i = 0; i < countTrueNegative.length; i++) { int totalCount = totalCount(i); double acc = accuracy(i); double f1 = f1(i); double precision = precision(i); double recall = recall(i); String label = (labels == null ? String.valueOf(i) : labels.get(i)); List<Object> args = Arrays.<Object>asList(label, acc, f1, precision, recall, totalCount, truePositives(i), trueNegatives(i), falsePositives(i), falseNegatives(i)); if (rocBinary != null) { args = new ArrayList<>(args); args.add(rocBinary.calculateAUC(i)); } sb.append("\n").append(String.format(pattern, args.toArray())); } if (decisionThreshold != null) { sb.append("\nPer-output decision thresholds: ") .append(Arrays.toString(decisionThreshold.dup().data().asFloat())); } } else { //Empty evaluation sb.append("\n-- No Data --\n"); } return sb.toString(); }
java
void register(String repoFullName) { lock.writeLock().lock(); try { if (!entityListenersByRepo.containsKey(requireNonNull(repoFullName))) { entityListenersByRepo.put(repoFullName, HashMultimap.create()); } } finally { lock.writeLock().unlock(); } }
java
public void marshall(GetKeyRotationStatusRequest getKeyRotationStatusRequest, ProtocolMarshaller protocolMarshaller) { if (getKeyRotationStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getKeyRotationStatusRequest.getKeyId(), KEYID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public Quaterniond rotationTo(Vector3dc fromDir, Vector3dc toDir) { return rotationTo(fromDir.x(), fromDir.y(), fromDir.z(), toDir.x(), toDir.y(), toDir.z()); }
python
def is_matching_rule(self, request): """Check according to the rules defined in the class docstring.""" # First, if in DEBUG mode and with django-debug-toolbar, we skip # this entire process. if settings.DEBUG and request.path.startswith("/__debug__"): return True # Second we check against matches match = resolve(request.path, getattr(request, "urlconf", settings.ROOT_URLCONF)) if "({0})".format(match.app_name) in EXEMPT: return True if "[{0}]".format(match.namespace) in EXEMPT: return True if "{0}:{1}".format(match.namespace, match.url_name) in EXEMPT: return True if match.url_name in EXEMPT: return True # Third, we check wildcards: for exempt in [x for x in EXEMPT if x.startswith("fn:")]: exempt = exempt.replace("fn:", "") if fnmatch.fnmatch(request.path, exempt): return True return False
java
public List<CmsModelPageEntry> getModelGroups() { List<CmsModelPageEntry> result = new ArrayList<CmsModelPageEntry>(); CmsResourceTypeConfig config = m_adeConfig.getResourceType( CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME); if ((config != null) && !config.isDisabled()) { String modelGroupFolderPath = config.getFolderPath(m_cms, m_adeConfig.getBasePath()); if (m_cms.existsResource(modelGroupFolderPath)) { try { Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms); List<CmsResource> modelResources = m_cms.readResources( modelGroupFolderPath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType( OpenCms.getResourceManager().getResourceType( CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME)), false); for (CmsResource model : modelResources) { CmsModelPageEntry entry = createModelPageEntry(model, false, false, wpLocale); if (entry != null) { result.add(entry); } } } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); } } } return result; }
python
def steps(self, *steps_cfg:StartOptEnd): "Build anneal schedule for all of the parameters." return [Scheduler(step, n_iter, func=func) for (step,(n_iter,func)) in zip(steps_cfg, self.phases)]
java
public static String parseToHtmlTag(String emoji_str){ if(emoji_str != null){ String str = EmojiParser.parseToHtmlHexadecimal(emoji_str); return htmlHexadecimalToHtmlTag(str); } return null; }
java
public void setSubFolders(java.util.Collection<Folder> subFolders) { if (subFolders == null) { this.subFolders = null; return; } this.subFolders = new java.util.ArrayList<Folder>(subFolders); }
java
public void setRepCoEx(Integer newRepCoEx) { Integer oldRepCoEx = repCoEx; repCoEx = newRepCoEx; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.COLOR_FIDELITY__REP_CO_EX, oldRepCoEx, repCoEx)); }
java
protected void handleAnnotationGroup(ProtoNetwork protoNetwork, Map<String, Annotation> annotationMap, AnnotationGroup ag) { if (ag != null) { // handle citation if (ag.getCitation() != null) { handleCitationAnnotations(protoNetwork, ag.getCitation(), annotationMap); } // handle evidence if (ag.getEvidence() != null) { handleEvidenceAnnotations(protoNetwork, ag.getEvidence(), annotationMap); } // handle user annotations (which were already defined) if (hasItems(ag.getAnnotations())) { for (Annotation a : ag.getAnnotations()) { annotationMap.put(a.getDefinition().getId(), a); } } } }
java
public static <E> List<E> constrainedList(List<E> list, Constraint<? super E> constraint) { return (list instanceof RandomAccess) ? new ConstrainedRandomAccessList<E>(list, constraint) : new ConstrainedList<E>(list, constraint); }
python
def getMirrorTextureGL(self, eEye): """Access to mirror textures from OpenGL.""" fn = self.function_table.getMirrorTextureGL pglTextureId = glUInt_t() pglSharedTextureHandle = glSharedTextureHandle_t() result = fn(eEye, byref(pglTextureId), byref(pglSharedTextureHandle)) return result, pglTextureId, pglSharedTextureHandle
python
def rounded_rectangle_region(width, height, radius): """ Returns a rounded rectangle wx.Region """ bmp = wx.Bitmap.FromRGBA(width, height) # Mask color is #000000 dc = wx.MemoryDC(bmp) dc.Brush = wx.Brush((255,) * 3) # Any non-black would do dc.DrawRoundedRectangle(0, 0, width, height, radius) dc.SelectObject(wx.NullBitmap) bmp.SetMaskColour((0,) * 3) return wx.Region(bmp)
java
public SqlPara getSqlParaByString(String content, Map data) { Template template = engine.getTemplateByString(content); SqlPara sqlPara = new SqlPara(); data.put(SQL_PARA_KEY, sqlPara); sqlPara.setSql(template.renderToString(data)); data.remove(SQL_PARA_KEY); // 避免污染传入的 Map return sqlPara; }
java
public Long getInteger(int key) { PebbleTuple tuple = getTuple(key, PebbleTuple.TupleType.INT); if (tuple == null) { return null; } return (Long) tuple.value; }
java
public <U extends T, A, B, C> OngoingMatchingC3<T, U, A, B, C> when( DecomposableMatchBuilder3<U, A, B, C> decomposableMatchBuilder) { return new OngoingMatchingC3<>(this, decomposableMatchBuilder.build()); }
python
def visit_BoolOp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s operator and operands as inlined expression.""" op = node.op with self.op_man(op): src = self.visit(op).join([self.visit(node.values[0])] + [self.visit(val, dfltChaining=False) for val in node.values[1:]]) return self.wrap_expr(src, dfltChaining)
python
def patch(source, sink): """Create a direct link between a source and a sink. Implementation:: sink = sink() for value in source(): sink.send(value) .. |patch| replace:: :py:func:`patch` """ sink = sink() for v in source(): try: sink.send(v) except StopIteration: return
java
public void setImage(Image image) { column.setText(null); table = null; this.image = image; }
java
public short[] getPixelValues(BufferedImage image) { validateImageType(image); WritableRaster raster = image.getRaster(); short[] pixelValues = getPixelValues(raster); return pixelValues; }
python
def parameters(self): """ Returns a dictionary of all parameters for this source. We use the parameter path as the key because it's guaranteed to be unique, unlike the parameter name. :return: """ all_parameters = collections.OrderedDict() for component in self._components.values(): for par in component.shape.parameters.values(): all_parameters[par.path] = par return all_parameters
java
public static Polygon makePolygon(Geometry shell) throws IllegalArgumentException { if(shell == null) { return null; } LinearRing outerLine = checkLineString(shell); return shell.getFactory().createPolygon(outerLine, null); }
java
public static void setPreferredAttributeNameForLaneCount(String name) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { if (name == null || "".equals(name) || DEFAULT_ATTR_LANE_COUNT.equalsIgnoreCase(name)) { //$NON-NLS-1$ prefs.remove("LANE_COUNT_ATTR_NAME"); //$NON-NLS-1$ } else { prefs.put("LANE_COUNT_ATTR_NAME", name); //$NON-NLS-1$ } } }
java
private Class<?> generateLobLoader(JDBCStorableProperty<S> property, Class<?> loaderType) throws SupportException { ClassInjector ci = ClassInjector.create (property.getEnclosingType().getName(), mParentClassLoader); ClassFile cf = new ClassFile(ci.getClassName()); cf.markSynthetic(); cf.setSourceFile(JDBCStorableGenerator.class.getName()); cf.setTarget("1.5"); cf.addInterface(loaderType); boolean isClob = loaderType == JDBCClobLoader.class; final TypeDesc capType = TypeDesc.forClass(JDBCConnectionCapability.class); final TypeDesc resultSetType = TypeDesc.forClass(ResultSet.class); final TypeDesc preparedStatementType = TypeDesc.forClass(PreparedStatement.class); final TypeDesc sqlLobType = TypeDesc.forClass (isClob ? java.sql.Clob.class : java.sql.Blob.class); final String enclosingFieldName = "enclosing"; final TypeDesc enclosingType = mClassFile.getType(); cf.addField(Modifiers.PRIVATE, enclosingFieldName, enclosingType); // Add constructor that accepts reference to enclosing storable. { MethodInfo mi = cf.addConstructor(Modifiers.PUBLIC, new TypeDesc[] {enclosingType}); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.invokeSuperConstructor(null); b.loadThis(); b.loadLocal(b.getParameter(0)); b.storeField(enclosingFieldName, enclosingType); b.returnVoid(); } MethodInfo mi = cf.addMethod (Modifiers.PUBLIC, "load", sqlLobType, new TypeDesc[] {capType}); mi.addException(TypeDesc.forClass(FetchException.class)); CodeBuilder b = new CodeBuilder(mi); LocalVariable capVar = b.getParameter(0); Label tryBeforeCon = b.createLabel().setLocation(); LocalVariable conVar = getConnection(b, capVar); Label tryAfterCon = b.createLabel().setLocation(); StringBuilder selectBuilder = new StringBuilder(); selectBuilder.append("SELECT "); selectBuilder.append(property.getColumnName()); selectBuilder.append(" FROM "); selectBuilder.append(mInfo.getQualifiedTableName()); LocalVariable psVar = b.createLocalVariable("ps", preparedStatementType); LocalVariable instanceVar = b.createLocalVariable(null, enclosingType); b.loadThis(); b.loadField(enclosingFieldName, enclosingType); b.storeLocal(instanceVar); Label tryAfterPs = buildWhereClauseAndPreparedStatement (b, selectBuilder, conVar, psVar, capVar, instanceVar); b.loadLocal(psVar); b.invokeInterface(preparedStatementType, "executeQuery", resultSetType, null); LocalVariable rsVar = b.createLocalVariable("rs", resultSetType); b.storeLocal(rsVar); Label tryAfterRs = b.createLabel().setLocation(); // If no results, then return null. Otherwise, there must be exactly // one result. LocalVariable resultVar = b.createLocalVariable(null, sqlLobType); b.loadNull(); b.storeLocal(resultVar); b.loadLocal(rsVar); b.invokeInterface(resultSetType, "next", TypeDesc.BOOLEAN, null); Label noResults = b.createLabel(); b.ifZeroComparisonBranch(noResults, "=="); b.loadLocal(rsVar); b.loadConstant(1); b.invokeInterface(resultSetType, isClob ? "getClob" : "getBlob", sqlLobType, new TypeDesc[] {TypeDesc.INT}); b.storeLocal(resultVar); noResults.setLocation(); closeResultSet(b, rsVar, tryAfterRs); closeStatement(b, psVar, tryAfterPs); yieldConAndHandleException(b, capVar, tryBeforeCon, conVar, tryAfterCon, false); b.loadLocal(resultVar); b.returnValue(sqlLobType); return ci.defineClass(cf); }
python
def rt_update(self, statement, element, mode, linenum, lineparser): """Performs a real-time update of the specified statement that is in the body of the module. :arg statement: the lines of code that was added/removed/changed on the element after it had alread been parsed. The lines together form a single continuous code statement. :arg element: the Module instance to update. :arg mode: 'insert', 'replace', or 'delete'. """ #First find out if we are passed the CONTAINS section separating executables from #the type and member definitions. In order for this code to be reached, the lines #that are being changed are *between* definitions that already exist. The likelihood #is that they are *new* definitions of members, types or executables. if linenum <= element.contains_index: #we only have to look for type and member definitions. self._rt_parse_members(statement, element, mode) self._rt_parse_types(statement, element, mode, lineparser) else: #we only have to deal with executables. self._rt_parse_execs(statement, element, mode, lineparser)
java
public void keyReleased(KeyEvent event) { lastKeyName = EMPTY_KEY_NAME; lastCode = NO_KEY_CODE; final Integer key = Integer.valueOf(event.getCode()); keys.remove(key); pressed.remove(key); }
java
public static <K1, V1, K2, V2> void setReducer(JobConf job, Class<? extends Reducer<K1, V1, K2, V2>> klass, Class<? extends K1> inputKeyClass, Class<? extends V1> inputValueClass, Class<? extends K2> outputKeyClass, Class<? extends V2> outputValueClass, boolean byValue, JobConf reducerConf) { job.setReducerClass(ChainReducer.class); job.setOutputKeyClass(outputKeyClass); job.setOutputValueClass(outputValueClass); Chain.setReducer(job, klass, inputKeyClass, inputValueClass, outputKeyClass, outputValueClass, byValue, reducerConf); }
java
public DiscriminatorJdbcSubBuilder when(String value, TypeReference<? extends T> type) { return when(value, type.getType()); }
java
@Override public ResourceSet<UsageRecord> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
java
protected boolean handleJsonBody(ActionRuntime runtime, VirtualForm virtualForm) { final ActionFormMeta formMeta = virtualForm.getFormMeta(); if (formMeta.isJsonBodyMapping()) { if (formMeta.isRootSymbolForm()) { mappingJsonBody(runtime, virtualForm, prepareJsonFromRequestBody(virtualForm)); } else if (formMeta.isTypedListForm()) { mappingListJsonBody(runtime, virtualForm, prepareJsonFromRequestBody(virtualForm)); } // basically no way here (but no exception just in case) } return false; }
java
@Override public void deleteDurableSubscription(String subscriptionName, String durableSubscriptionHome) throws SIConnectionUnavailableException, SIConnectionDroppedException, SIResourceException, SIConnectionLostException, SIErrorException, SINotAuthorizedException, SIIncorrectCallException, SIDurableSubscriptionNotFoundException, SIDestinationLockedException { //liberty code change : chetan //Since there is no ME-ME communication the durableSubscriptionHome is always the local ME durableSubscriptionHome = _messageProcessor.getMessagingEngineName(); if (TraceComponent.isAnyTracingEnabled() && CoreSPIConnection.tc.isEntryEnabled()) SibTr.entry(CoreSPIConnection.tc, "deleteDurableSubscription", new Object[] { this, subscriptionName, durableSubscriptionHome }); deleteDurableSubscription(subscriptionName, durableSubscriptionHome, null); if (TraceComponent.isAnyTracingEnabled() && CoreSPIConnection.tc.isEntryEnabled()) SibTr.exit(CoreSPIConnection.tc, "deleteDurableSubscription"); }