language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def children_to_list(node): """Organize children structure.""" if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(key=lambda x: x['name']) ...
python
def nemo_accpars(self,vo,ro): """ NAME: nemo_accpars PURPOSE: return the accpars potential parameters for use of this potential with NEMO INPUT: vo - velocity unit in km/s ro - length unit in kpc OUTPUT: accpars strin...
java
public static String format(String str, Object... args) { str = str.replaceAll("\\{}", "%s"); return String.format(str, args); }
python
def calculate(self): """do the TPM calculation""" self._calculated = True for name in self.transcripts: self.transcripts[name]['RPK'] = (float(self.transcripts[name]['count'])/float(self.transcripts[name]['length']))/float(1000) tot = 0.0 for name in self.transcripts: tot...
python
def infos(self): """:py:class:`OrbitInfos` object of ``self`` """ if not hasattr(self, '_infos'): self._infos = OrbitInfos(self) return self._infos
python
def get_fault_type_dummy_variables(self, rup): """ Fault-type classification dummy variable based on rup.rake. "``H`` is 1 for a strike-slip mechanism and 0 for a reverse mechanism" (p. 1201). Note: UserWarning is raised if mechanism is determined to be normal ...
java
public static String paragraphs(int paragraphCount, boolean supplemental) { List<String> paragraphList = new ArrayList<String>(); for (int i = 0; i < paragraphCount; i++) { paragraphList.add(paragraph(3, supplemental, 3)); } String joined = StringUtils.join(paragraphList, "\...
java
@Override public void writeBinaryData(byte []sBuf, int sOffset, int sLength) { byte []tBuf = _buffer; int tOffset = _offset; int tLength = tBuf.length; int end = sOffset + sLength; while (sOffset < end) { if (tLength - tOffset < 1) { tOffset = flush(tOffset); } ...
python
def to_float(value, default=_marker): """Converts the passed in value to a float number :param value: The value to be converted to a floatable number :type value: str, float, int :returns: The float number representation of the passed in value :rtype: float """ if not is_floatable(value): ...
java
public static ConfluentRegistryAvroDeserializationSchema<GenericRecord> forGeneric(Schema schema, String url, int identityMapCapacity) { return new ConfluentRegistryAvroDeserializationSchema<>( GenericRecord.class, schema, new CachedSchemaCoderProvider(url, identityMapCapacity)); }
python
def on_message(self, handler, msg): """ In remote debugging mode this simply acts as a forwarding proxy for the two clients. """ if self.remote_debugging: #: Forward to other clients for h in self.handlers: if h != handler: h.wr...
java
@Override public int getNumberOfDevices() { if (numberOfDevices.get() < 0) { synchronized (this) { if (numberOfDevices.get() < 1) { numberOfDevices.set(NativeOpsHolder.getInstance().getDeviceNativeOps().getAvailableDevices()); } } ...
java
@Override public void resetPMICounters() { // TODO needs to change if cache provider supports PMI counters. final String methodName = "resetPMICounters()"; if (tc.isDebugEnabled()) { Tr.debug(tc, methodName + " cacheName=" + cacheName); } }
java
protected byte[] serializeStreamValue(final int iIndex) throws IOException { if (serializedValues[iIndex] <= 0) { // NEW OR MODIFIED: MARSHALL CONTENT OProfiler.getInstance().updateCounter("OMVRBTreeMapEntry.serializeValue", 1); return ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSeria...
java
@Override public void run() { try { while (! isClosed() && _is.read() > 0 && _in.readMessage(_is)) { ServiceRef.flushOutbox(); } } catch (EOFException e) { log.finer(this + " end of file"); if (log.isLoggable(Level.ALL)) { log.log(Level.ALL, e.toString(), e); ...
python
def to_json(self): """ Creates a JSON serializable representation of this instance Returns: :obj:`dict`: For example, { "lat": 9.3470298, "lon": 3.79274, "time": "2016-07-15T15:27:53.574110" } ...
python
def _get_next_server(self): """Returns a valid redis server or raises a TransportException""" current_try = 0 max_tries = len(self._servers) while current_try < max_tries: server_index = self._raise_server_index() server = self._servers[server_index] ...
java
public OvhVrackNetwork serviceName_vrack_network_vrackNetworkId_GET(String serviceName, Long vrackNetworkId) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}"; StringBuilder sb = path(qPath, serviceName, vrackNetworkId); String resp = exec(qPath, "GET", sb.toStrin...
python
def project(self, points): """Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- ...
python
def _post(self, url, data): """ Helper method: POST data to a given URL on TBA's API. :param url: URL string to post data to and hash. :pararm data: JSON data to post and hash. :return: Requests Response object. """ return self.session.post(self.WRITE_URL_PRE + ...
python
def asignTopUnit(self, top, topName): """ Set hwt unit as template for component """ self._top = top self.name = topName pack = self._packager self.model.addDefaultViews(topName, pack.iterParams(top)) for intf in pack.iterInterfaces(self._top): ...
python
def print_detail_scan_summary(json_data, names=None): ''' Print a detailed summary of the data returned from a CVE scan. ''' clean = True sevs = ['Critical', 'Important', 'Moderate', 'Low'] cve_summary = json_data['host_results'] image_template = " {0:10}: {1}" cve_template = " ...
java
public void addComparator(Comparator<T> comparator, boolean reverse) { checkLocked(); comparatorChain.add(comparator); if (reverse == true) { orderingBits.set(comparatorChain.size() - 1); } }
java
public SynchronizeFxServer newChannel(final Object root, final String channelName, final Executor modelChangeExecutor, final ServerCallback callback) { synchronized (channels) { if (channels.containsKey(channelName)) { throw new IllegalArgumentException("A new Synchronize...
python
def get_interface_detail_output_interface_logical_hardware_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail...
java
protected void logResources() throws SystemException { if (tc.isEntryEnabled()) Tr.entry(tc, "logResources", _resourcesLogged); if (!_resourcesLogged) { for (int i = 0; i < _resourceObjects.size(); i++) { final JTAResource resource = _resourceObjects.get(i); ...
python
def _validate_jp2h(self, boxes): """Validate the JP2 Header box.""" self._check_jp2h_child_boxes(boxes, 'top-level') jp2h_lst = [box for box in boxes if box.box_id == 'jp2h'] jp2h = jp2h_lst[0] # 1st jp2 header box cannot be empty. if len(jp2h.box) == 0: msg...
java
public ImageDescriptor image(SarlAgent agent) { final JvmDeclaredType jvmElement = this.jvmModelAssociations.getInferredType(agent); return this.images.forAgent( agent.getVisibility(), this.adornments.get(jvmElement)); }
java
public Integer getMaxStatements() { if (childNode.getTextValueForPatternName("max-statements") != null && !childNode.getTextValueForPatternName("max-statements").equals("null")) { return Integer.valueOf(childNode.getTextValueForPatternName("max-statements")); } return null; }
java
public static SparseVector fromCollection(Collection<? extends Number> list) { return Vector.fromCollection(list).to(Vectors.SPARSE); }
java
public static boolean isKnownEOFException (@Nullable final Class <?> aClass) { if (aClass == null) return false; final String sClass = aClass.getName (); return sClass.equals ("java.io.EOFException") || sClass.equals ("org.mortbay.jetty.EofException") || sClass.equals ("org.ec...
java
private static Collection<JobIdWithStatus> combine( Collection<JobIdWithStatus> first, Collection<JobIdWithStatus> second) { checkNotNull(first); checkNotNull(second); ArrayList<JobIdWithStatus> result = new ArrayList<>(first.size() + second.size()); result.addAll(first); result.addAll(second); ret...
python
def get_starred_segments(self, limit=None): """ Returns a summary representation of the segments starred by the authenticated user. Pagination is supported. http://strava.github.io/api/v3/segments/#starred :param limit: (optional), limit number of starred segments returned. ...
python
def predict_from_variants( self, variants, transcript_expression_dict=None, gene_expression_dict=None): """ Predict epitopes from a Variant collection, filtering options, and optional gene and transcript expression data. Parameters ...
python
def iter_islast(iterable): """Generate (item, islast) pairs for an iterable. Generates pairs where the first element is an item from the iterable source and the second element is a boolean flag indicating if it is the last item in the sequence. """ it = iter(iterable) prev = next(it) fo...
python
def censor(input_text): """ Returns the input string with profanity replaced with a random string of characters plucked from the censor_characters pool. """ ret = input_text words = get_words() for word in words: curse_word = re.compile(re.escape(word), re.IGNORECASE) cen = "".j...
java
public void checkBlockableReadSequence(long readSequence) { if (isTooLargeSequence(readSequence)) { throw new IllegalArgumentException("sequence:" + readSequence + " is too large. The current tailSequence is:" + tailSequence()); } if (isStaleSequence(readSequence)...
java
protected File asAbsoluteFile( File f ) { if ( f.isAbsolute() ) { return f; } return new File( getBasedir(), f.getPath() ); }
java
@Override public void onDestroy() { super.onDestroy(); eventRegister.unregisterEventBuses(); if (getControllerClass() != null) { try { Mvc.graph().dereference(controller, getControllerClass(), null); } catch (ProviderMissingException e) { ...
python
def save_riskmodel(self): """ Save the risk models in the datastore """ self.datastore['risk_model'] = rm = self.riskmodel self.datastore['taxonomy_mapping'] = self.riskmodel.tmap attrs = self.datastore.getitem('risk_model').attrs attrs['min_iml'] = hdf5.array_of_...
java
public Promise<Void> force(boolean metaData) { return sanitize(ofBlockingRunnable(executor, () -> { try { channel.force(metaData); } catch (IOException e) { throw new UncheckedException(e); } })); }
python
def enable_firewall_ruleset(host, username, password, ruleset_enable, ruleset_name, protocol=None, port=None, esxi_hosts=Non...
java
private static ReloadableType searchForReloadableType(int typeId, TypeRegistry typeRegistry) { ReloadableType reloadableType; reloadableType = typeRegistry.getReloadableTypeInTypeRegistryHierarchy( NameRegistry.getTypenameById(typeId)); typeRegistry.rememberReloadableType(typeId, reloadableType); return rel...
java
public int findColumn(final String columnLabel) throws SQLException { if (this.queryResult.getResultSetType() == ResultSetType.SELECT) { try { return ((SelectQueryResult) queryResult).getColumnId(columnLabel) + 1; } catch (NoSuchColumnException e) { throw ...
python
def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool: """ Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded """ return obj._is_valid(log)
java
public CompletableFuture<Object> putAsync(final Consumer<HttpConfig> configuration) { return CompletableFuture.supplyAsync(() -> put(configuration), getExecutor()); }
java
public boolean fling(float velocityX, float velocityY, float velocityZ) { boolean scrolled = true; float viewportX = mScrollable.getViewPortWidth(); if (Float.isNaN(viewportX)) { viewportX = 0; } float maxX = Math.min(MAX_SCROLLING_DISTANCE, viewportX...
python
def __parse_blacklist(self, json): """Parse blacklist entries using Sorting Hat format. The Sorting Hat blacklist format is a JSON stream that stores a list of blacklisted entries. Next, there is an example of a valid stream: { "blacklist": [ "John ...
java
public static List<? extends CmsPrincipal> filterFlag(List<? extends CmsPrincipal> principals, int flag) { Iterator<? extends CmsPrincipal> it = principals.iterator(); while (it.hasNext()) { CmsPrincipal p = it.next(); if ((p.getFlags() & flag) != flag) { it.remo...
python
def route(self, url, host=None): """This is a decorator """ def fn(handler_cls): handlers = self._get_handlers_on_host(host) handlers.insert(0, (url, handler_cls)) return handler_cls return fn
python
def run(self): """Run all runners, blocking until completion or error""" self._logger.info('starting all runners') try: with self._lock: assert not self.running.set(), 'cannot re-run: %s' % self self.running.set() thread_runner = self.runne...
java
public static KeyStore load(String path, char[] password) { try { return load(new FileInputStream(path), password); } catch (FileNotFoundException e) { throw new TrustManagerLoadFailedException(e); } }
python
def resolve(self, other: Type) -> Optional[Type]: """See ``PlaceholderType.resolve``""" if not isinstance(other, NltkComplexType): return None expected_second = ComplexType(NUMBER_TYPE, ComplexType(ANY_TYPE, ComplexType(ComplexType(ANY_TYPE, ANY_...
java
public static String getShortID(String id) { String canonicalID = getCanonicalCLDRID(id); if (canonicalID == null) { return null; } return getShortIDFromCanonical(canonicalID); }
java
public void materializeFullObject(Object target) { ClassDescriptor cld = broker.getClassDescriptor(target.getClass()); // don't force, let OJB use the user settings final boolean forced = false; if (forceProxies){ broker.getReferenceBroker().retrieveProxyReferences(...
python
def db_open(cls, impl, working_dir): """ Open a connection to our chainstate db """ path = config.get_snapshots_filename(impl, working_dir) return cls.db_connect(path)
python
def call_chunks(self, chunks): ''' Iterate over a list of chunks and call them, checking for requires. ''' # Check for any disabled states disabled = {} if 'state_runs_disabled' in self.opts['grains']: for low in chunks[:]: state_ = '{0}.{1}'.f...
java
private void handleQueries( final HttpServletResponse response, final Map<String, List<String>> queries, final String version) throws IOException { LOG.log(Level.INFO, "HttpServerReefEventHandler handleQueries is called"); for (final Map.Entry<String, List<String>> entry : queries.entrySet()...
python
def _set_properties(self): """Sets dialog title and size limitations of the widgets""" self.SetTitle("CSV Export") self.SetSize((600, 600)) for button in [self.button_cancel, self.button_apply, self.button_ok]: button.SetMinSize((80, 28))
python
def access_key(self): """ The access key id used to sign the request. If the access key is not in the same credential scope as this request, an AttributeError exception is raised. """ credential = self.query_parameters.get(_x_amz_credential) if credential is not ...
java
public static Map<String, Object> toMap(XmlReaders readers){ Node root = readers.getNode("xml"); if (root == null){ return Collections.emptyMap(); } NodeList children = root.getChildNodes(); if (children.getLength() == 0){ return Collections.emptyMap(); ...
python
def create_initial_tree(channel): """ create_initial_tree: Create initial tree structure Args: channel (Channel): channel to construct Returns: tree manager to run rest of steps """ # Create channel manager with channel data config.LOGGER.info(" Setting up initial channel s...
python
def get_logger(name, CFG=None): """set up logging for a service using the py 2.7 dictConfig """ logger = logging.getLogger(name) if CFG: # Make log directory if it doesn't exist for handler in CFG.get('handlers', {}).itervalues(): if 'filename' in handler: l...
python
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, b...
java
public int doStartTag() throws JspException { if (_rolloverImage != null && getJavaScriptAttribute(ONMOUSEOVER) == null) { // cause the roll over script to be inserted WriteRenderAppender writer = new WriteRenderAppender(pageContext); ScriptRequestState srs = ScriptReques...
python
def _clean_empty(d): """Remove None values from a dict.""" if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (_clean_empty(v) for v in d) if v is not None] return { k: v for k, v in ((k, _clean_empty(v)) for k, v in d.items()) ...
python
def setContext(self, font, feaFile, compiler=None): """ Populate a temporary `self.context` namespace, which is reset after each new call to `_write` method. Subclasses can override this to provide contextual information which depends on other data, or set any temporary attributes. ...
python
def set_widgets(self): """Set widgets on the Field tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose() subcategory = self.parent.step_kw_subcategory.selected_subcategory() unit = self.parent.step_kw_unit.selected_unit() layer_mode =...
python
def auto_tweet(sender, instance, *args, **kwargs): """ Allows auto-tweeting newly created object to twitter on accounts configured in settings. You MUST create an app to allow oAuth authentication to work: -- https://dev.twitter.com/apps/ You also must set the app to "Read and Write" access le...
java
private Entry setParent(Entry entry, Entry parent) { unlinkFromNeighbors(entry); entry.oParent = parent; parent.oFirstChild = mergeLists(entry, parent.oFirstChild); parent.degree++; entry.isMarked = false; return parent; }
java
public Observable<DocumentFragment<Mutation>> execute(PersistTo persistTo, long timeout, TimeUnit timeUnit) { return execute(persistTo, ReplicateTo.NONE, timeout, timeUnit); }
java
public ActivityTypeInfos withTypeInfos(ActivityTypeInfo... typeInfos) { if (this.typeInfos == null) { setTypeInfos(new java.util.ArrayList<ActivityTypeInfo>(typeInfos.length)); } for (ActivityTypeInfo ele : typeInfos) { this.typeInfos.add(ele); } return th...
java
public Set<String> getCommonPropertyAsSet(String key) { Set<String> propertiesSet = new HashSet<>(); StringTokenizer tk = new StringTokenizer(props.getProperty(PropertiesBundleConstant.PROPS_PREFIX + key, ""), ","); while (tk.hasMoreTokens()) propertiesSet.add(tk.nextToken().trim()); return propertiesSet...
java
public void marshall(ReservationUtilizationGroup reservationUtilizationGroup, ProtocolMarshaller protocolMarshaller) { if (reservationUtilizationGroup == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
private void writeAmountOfNodesBack(List<ExampleQuery> exampleQueries) { String sqlTemplate = "UPDATE _" + EXAMPLE_QUERIES_TAB + " SET nodes=?, used_ops=CAST(? AS text[]) WHERE example_query=?;"; for (ExampleQuery eQ : exampleQueries) { getJdbcTemplate().update(sqlTemplate, eQ.getNodes(), eQ.g...
java
@Override public UserGroupInformation getProxiedUser(final Props userProp) throws HadoopSecurityManagerException { final String userToProxy = verifySecureProperty(userProp, JobProperties.USER_TO_PROXY); final UserGroupInformation user = getProxiedUser(userToProxy); if (user == null) { throw ne...
python
def from_local_repository(repository_path, refspec=None): """ Retrieves the git context from a local git repository. :param repository_path: Path to the git repository to retrieve the context from :param refspec: The commit(s) to retrieve """ context = GitContext() # If...
java
public static OutputStream marshal(Document document, OutputStream out, String encoding) throws CmsXmlException { try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(out, format); writer.se...
java
private void checkExistingCriteriaForUserBasedLimit(QueryWhere queryWhere, String userId, UserGroupCallback userGroupCallback) { List<String> groupIds = userGroupCallback.getGroupsForUser(userId); Set<String> userAndGroupIds = new HashSet<String>(); if( groupIds != null ) { userAndGr...
python
def copy_files(filename, dstfilename): # type: (AnyStr, AnyStr) -> None """Copy files with the same name and different suffixes, such as ESRI Shapefile.""" FileClass.remove_files(dstfilename) dst_prefix = os.path.splitext(dstfilename)[0] pattern = os.path.splitext(filename)[0] + ...
java
private static String initRemoveEntityQuery(EntityKeyMetadata entityKeyMetadata) { StringBuilder queryBuilder = new StringBuilder( "MATCH " ); appendEntityNode( "n", entityKeyMetadata, queryBuilder ); queryBuilder.append( " OPTIONAL MATCH (n)-[r]->(e:EMBEDDED), path=(e)-[*0..]->(:EMBEDDED) " ); queryBuilder.app...
python
def match_length(self): """ Find the total length of all words that match between the two sequences.""" length = 0 for match in self.get_matching_blocks(): a, b, size = match length += self._text_length(self.a[a:a+size]) return length
java
@Exported public @CheckForNull String getRequiredCoreVersion() { String v = manifest.getMainAttributes().getValue("Jenkins-Version"); if (v!= null) return v; v = manifest.getMainAttributes().getValue("Hudson-Version"); if (v!= null) return v; return null; }
java
@Override public UpdateResolverResult updateResolver(UpdateResolverRequest request) { request = beforeClientExecution(request); return executeUpdateResolver(request); }
python
def get_child_ids(self): """Gets the children of this node. return: (osid.id.IdList) - the children of this node *compliance: mandatory -- This method must be implemented.* """ id_list = [] from ..id.objects import IdList for child_node in self._my_map['childNod...
python
def mls_polynomial_coefficients(rho, degree): """Determine the coefficients for a MLS polynomial smoother. Parameters ---------- rho : float Spectral radius of the matrix in question degree : int Degree of polynomial coefficients to generate Returns ------- Tuple of arr...
java
public Matrix4x3d rotateYXZ(Vector3d angles) { return rotateYXZ(angles.y, angles.x, angles.z); }
python
def download_as_obj( base_url=d1_common.const.URL_DATAONE_ROOT, timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT, ): """Download public certificate from a TLS/SSL web server as Certificate object. Also see download_as_der(). Args: base_url : str A full URL to a DataONE service en...
python
def pack_mbap(transaction_id, protocol_id, length, unit_id): """ Create and return response MBAP. :param transaction_id: Transaction id. :param protocol_id: Protocol id. :param length: Length of following bytes in ADU. :param unit_id: Unit id. :return: Byte array of 7 bytes. """ return ...
python
def create_memory_layer( layer_name, geometry, coordinate_reference_system=None, fields=None): """Create a vector memory layer. :param layer_name: The name of the layer. :type layer_name: str :param geometry: The geometry of the layer. :rtype geometry: QgsWkbTypes (note: ...
python
def check_spyder_kernels(): """Check spyder-kernel requirement.""" try: import spyder_kernels required_ver = '1.0.0' actual_ver = spyder_kernels.__version__ if LooseVersion(actual_ver) < LooseVersion(required_ver): show_warning("Please check Spyder installation...
java
public void setResult(String newResult) { String oldResult = result; result = newResult; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.SCENARIO__RESULT, oldResult, result)); }
python
def update(self, item): """ Add a collector item. Args: item (CollectorUpdate): event data like stage, timestampe and status. """ if item.matrix not in self.data: self.data[item.matrix] = [] result = Select(self.data[item.matrix]).where( ...
python
def write_bool(self, flag): """ Writes a boolean to the underlying output file as a 1-byte value. """ if flag: self.write(b"\x01") else: self.write(b"\x00")
python
def _register_entry_point_module(self, entry_point, module): """ Private method that registers an entry_point with a provided module. """ records_map = self._map_entry_point_module(entry_point, module) self.store_records_for_package(entry_point, list(records_map.keys()))...
python
def getPercentiles(data,weights=None,percentiles=[0.5],presorted=False): ''' Calculates the requested percentiles of (weighted) data. Median by default. Parameters ---------- data : numpy.array A 1D array of float data. weights : np.array A weighting vector for the data. pe...
java
public void hideSoftKeyboard() { if(config.commandLogging){ Log.d(config.commandLoggingTag, "hideSoftKeyboard()"); } dialogUtils.hideSoftKeyboard(null, true, false); }
python
def push_new_version(gh_token: str = None, owner: str = None, name: str = None): """ Runs git push and git push --tags. :param gh_token: Github token used to push. :param owner: Organisation or user that owns the repository. :param name: Name of repository. :raises GitError: if GitCommandError ...
python
def delete(self, **kw): """ Delete a policy route from the engine. You can delete using a single field or multiple fields for a more exact match. Use a keyword argument to delete a route by any valid attribute. :param kw: use valid Route keyword values to delete by exact...
python
def has_reg(value): """Return True if the given key exists in HKEY_LOCAL_MACHINE, False otherwise.""" try: SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, value) ret = True except SCons.Util.WinError: ret = False return ret