language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Scale get(final int index, final DistanceUnit unit) { return new Scale(this.scaleDenominators[index], unit, PDF_DPI); }
java
private Map<String, Object> parseRequestParameters(String requestParameters) { Map<String, Object> parameterMap; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(requestParameters)) { parameterMap = new HashMap<String, Object>(); String[] params = requestParameters.split("&"); for (int i = 0; i < params.length; i++) { int position = params[i].indexOf("="); if (position >= 0) { String key = params[i].substring(0, position); String value = params[i].substring(position + 1); if (value.contains(",")) { parameterMap.put(key, value.split(",")); } else { parameterMap.put(key, value); } } } } else { parameterMap = Collections.<String, Object> emptyMap(); } return parameterMap; }
python
def clean_cache_upstream(self): """Clean cache for all steps that are upstream to `self`. """ logger.info('Cleaning cache for the entire upstream pipeline') for step in self.all_upstream_steps.values(): logger.info('Step {}, cleaning cache'.format(step.name)) step.output = None return self
python
def react(self, emojiname): """ React to a message using the web api """ self._client.react_to_message( emojiname=emojiname, channel=self._body['channel'], timestamp=self._body['ts'])
python
def subscribe_account(self, username, password, service): """Subscribe an account for a service. """ data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, data, self.token_header)
python
def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None): """ :param attributes_a: A dict of functions to their attributes :param attributes_b: A dict of functions to their attributes The following parameters are optional. :param filter_set_a: A set to limit attributes_a to the functions in this set. :param filter_set_b: A set to limit attributes_b to the functions in this set. :returns: A list of tuples of matching objects. """ # get the attributes that are in the sets if filter_set_a is None: filtered_attributes_a = {k: v for k, v in attributes_a.items()} else: filtered_attributes_a = {k: v for k, v in attributes_a.items() if k in filter_set_a} if filter_set_b is None: filtered_attributes_b = {k: v for k, v in attributes_b.items()} else: filtered_attributes_b = {k: v for k, v in attributes_b.items() if k in filter_set_b} # get closest closest_a = _get_closest_matches(filtered_attributes_a, filtered_attributes_b) closest_b = _get_closest_matches(filtered_attributes_b, filtered_attributes_a) # a match (x,y) is good if x is the closest to y and y is the closest to x matches = [] for a in closest_a: if len(closest_a[a]) == 1: match = closest_a[a][0] if len(closest_b[match]) == 1 and closest_b[match][0] == a: matches.append((a, match)) return matches
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<BatchPredictResult, OperationMetadata> batchPredictAsync( ModelName name, BatchPredictInputConfig inputConfig, BatchPredictOutputConfig outputConfig, Map<String, String> params) { BatchPredictRequest request = BatchPredictRequest.newBuilder() .setName(name == null ? null : name.toString()) .setInputConfig(inputConfig) .setOutputConfig(outputConfig) .putAllParams(params) .build(); return batchPredictAsync(request); }
python
def upsert(db, table, key_cols, update_dict): """Fabled upsert for SQLiteDB. Perform an upsert based on primary key. :param SQLiteDB db: database :param str table: table to upsert into :param str key_cols: name of key columns :param dict update_dict: key-value pairs to upsert """ with db: cur = db.cursor() cur.execute( 'UPDATE {} SET {} WHERE {}'.format( table, ','.join(_sqlpformat(col) for col in update_dict.keys()), ' AND '.join(_sqlpformat(col) for col in key_cols), ), update_dict, ) if db.changes() == 0: keys, values = zip(*update_dict.items()) cur.execute( 'INSERT INTO {} ({}) VALUES ({})'.format( table, ','.join(keys), ','.join('?' for _ in values)), values)
python
def from_api_repr(cls, resource, client): """Factory: construct a job given its API representation .. note: This method assumes that the project found in the resource matches the client's project. :type resource: dict :param resource: dataset job representation returned from the API :type client: :class:`google.cloud.bigquery.client.Client` :param client: Client which holds credentials and project configuration for the dataset. :rtype: :class:`google.cloud.bigquery.job.CopyJob` :returns: Job parsed from ``resource``. """ job_id, config_resource = cls._get_resource_config(resource) config = CopyJobConfig.from_api_repr(config_resource) # Copy required fields to the job. copy_resource = config_resource["copy"] destination = TableReference.from_api_repr(copy_resource["destinationTable"]) sources = [] source_configs = copy_resource.get("sourceTables") if source_configs is None: single = copy_resource.get("sourceTable") if single is None: raise KeyError("Resource missing 'sourceTables' / 'sourceTable'") source_configs = [single] for source_config in source_configs: table_ref = TableReference.from_api_repr(source_config) sources.append(table_ref) job = cls(job_id, sources, destination, client=client, job_config=config) job._set_properties(resource) return job
java
@Override public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { ProxyIoSession proxyIoSession = (ProxyIoSession) session .getAttribute(ProxyIoSession.PROXY_SESSION); proxyIoSession.getEventQueue().enqueueEventIfNecessary( new IoSessionEvent(nextFilter, session, status)); }
java
public static Object instantiateObject(String className, ClassLoader classLoader, Object...args) { Constructor c = (Constructor) constructors.get( className ); if ( c == null ) { c = loadClass(className, classLoader).getConstructors()[0]; constructors.put(className, c); } Object object; try { object = c.newInstance(args); } catch ( Throwable e ) { throw new RuntimeException( "Unable to instantiate object for class '" + className + "' with constructor " + c, e ); } return object; }
python
def get_value_from_environment( section_name, key_name, envname_pad=ENVNAME_PAD, logger=logging.getLogger('ProsperCommon'), ): """check environment for key/value pair Args: section_name (str): section name key_name (str): key to look up envname_pad (str): namespace padding logger (:obj:`logging.logger`): logging handle Returns: str: value in environment """ var_name = '{pad}_{section}__{key}'.format( pad=envname_pad, section=section_name, key=key_name ) logger.debug('var_name=%s', var_name) value = getenv(var_name) logger.debug('env value=%s', value) return value
python
def add_peer_parser(subparsers, parent_parser): """Adds argument parser for the peer command Args: subparsers: Add parsers to this subparser object parent_parser: The parent argparse.ArgumentParser object """ parser = subparsers.add_parser( 'peer', help='Displays information about validator peers', description="Provides a subcommand to list a validator's peers") grand_parsers = parser.add_subparsers(title='subcommands', dest='subcommand') grand_parsers.required = True add_peer_list_parser(grand_parsers, parent_parser)
java
public static MultiValueMap asMultiValueMap(final Map innerMap) { return org.springframework.util.CollectionUtils.toMultiValueMap(innerMap); }
python
def coPrime(l): """returns 'True' if the values in the list L are all co-prime otherwise, it returns 'False'. """ for i, j in combinations(l, 2): if euclid(i, j) != 1: return False return True
java
private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation, ModelNode host) { final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR)); if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) { //We have a composite operation resulting from a transformation to redeploy affected deployments //See redeploying deployments affected by an overlay. ModelNode serverOp = operation.clone(); Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>(); for (ModelNode step : serverOp.get(STEPS).asList()) { ModelNode newStep = step.clone(); String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue(); newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies); for(ServerIdentity server : servers) { if(!composite.containsKey(server)) { composite.put(server, Operations.CompositeOperationBuilder.create()); } composite.get(server).addStep(newStep); } if(!servers.isEmpty()) { newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode()); } } if(!composite.isEmpty()) { Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>(); for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) { result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation()); } return result; } return Collections.emptyMap(); } final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies); return Collections.singletonMap(allServers, operation.clone()); }
java
@Requires({ "name != null", "!name.isEmpty()", "kind != null" }) public static URI getUriForClass(String name, Kind kind) { try { return new URI("com.google.java.contract://com.google.java.contract/" + name + kind.extension); } catch (URISyntaxException e) { throw new IllegalArgumentException(); } }
java
public static AuditEntryBean planCreated(PlanBean bean, ISecurityContext securityContext) { AuditEntryBean entry = newEntry(bean.getOrganization().getId(), AuditEntityType.Plan, securityContext); entry.setEntityId(bean.getId()); entry.setEntityVersion(null); entry.setData(null); entry.setWhat(AuditEntryType.Create); return entry; }
python
def nvmlDeviceGetSerial(handle): r""" /** * Retrieves the globally unique board serial number associated with this device's board. * * For all products with an inforom. * * The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator). * This number matches the serial number tag that is physically attached to the board. See \ref * nvmlConstants::NVML_DEVICE_SERIAL_BUFFER_SIZE. * * @param device The identifier of the target device * @param serial Reference in which to return the board/module serial number * @param length The maximum allowed length of the string returned in \a serial * * @return * - \ref NVML_SUCCESS if \a serial has been set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a serial is NULL * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error */ nvmlReturn_t DECLDIR nvmlDeviceGetSerial """ c_serial = create_string_buffer(NVML_DEVICE_SERIAL_BUFFER_SIZE) fn = _nvmlGetFunctionPointer("nvmlDeviceGetSerial") ret = fn(handle, c_serial, c_uint(NVML_DEVICE_SERIAL_BUFFER_SIZE)) _nvmlCheckReturn(ret) return bytes_to_str(c_serial.value)
java
private void fireNotAuthenticatedEvent(String userName) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "fireNotAuthenticatedEvent", userName); // Check that we have a RuntimeEventListener if (_runtimeEventListener != null) { // Build the message for the Notification String message = nls.getFormattedMessage( "USER_NOT_AUTHORIZED_ERROR_CWSIP0301", new Object[] { userName, getMessagingEngineName(), getMessagingEngineBus() }, null); // Build the properties for the Notification Properties props = new Properties(); props.put(SibNotificationConstants.KEY_OPERATION, SibNotificationConstants.OPERATION_CONNECT); props.put(SibNotificationConstants.KEY_SECURITY_USERID, userName); props.put(SibNotificationConstants.KEY_SECURITY_REASON, SibNotificationConstants.SECURITY_REASON_NOT_AUTHENTICATED); // Fire the event _runtimeEventListener .runtimeEventOccurred( _engine, SibNotificationConstants.TYPE_SIB_SECURITY_NOT_AUTHENTICATED, message, props); } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Null RuntimeEventListener, cannot fire event"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "fireNotAuthenticatedEvent"); }
python
def btc_get_privkey_address(privkey_info, **blockchain_opts): """ Get the address for a given private key info bundle (be it multisig or singlesig) Return the address on success Raise exception on error """ from .multisig import make_multisig_segwit_address_from_witness_script if btc_is_singlesig(privkey_info): return btc_address_reencode( ecdsalib.ecdsa_private_key(privkey_info).public_key().address() ) if btc_is_multisig(privkey_info) or btc_is_singlesig_segwit(privkey_info): redeem_script = str(privkey_info['redeem_script']) return btc_make_p2sh_address(redeem_script) if btc_is_multisig_segwit(privkey_info): return make_multisig_segwit_address_from_witness_script(str(privkey_info['redeem_script'])) raise ValueError("Invalid private key info")
java
protected boolean getBoolean(String key, boolean defaultValue) { try { return getConfig().getBoolean(key, defaultValue); } catch (ConversionException e) { logConversionException(key, e); } return defaultValue; }
python
def load_model_by_id(self, model_id): """Get the model by model_id Parameters ---------- model_id : int model index Returns ------- load_model : Graph the model graph representation """ with open(os.path.join(self.path, str(model_id) + ".json")) as fin: json_str = fin.read().replace("\n", "") load_model = json_to_graph(json_str) return load_model
python
def RIBVRFRouteLimitExceeded_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubElement(RIBVRFRouteLimitExceeded, "originator-switch-info") switchIdentifier = ET.SubElement(originator_switch_info, "switchIdentifier") switchIdentifier.text = kwargs.pop('switchIdentifier') callback = kwargs.pop('callback', self._callback) return callback(config)
python
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): """ Compute the standard deviation along given axis while ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True ddof : int, default 1 Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. mask : ndarray[bool], optional nan-mask if known Returns ------- result : float Unless input is a float array, in which case use the same precision as the input array. Examples -------- >>> import pandas.core.nanops as nanops >>> s = pd.Series([1, np.nan, 2, 3]) >>> nanops.nanstd(s) 1.0 """ result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _wrap_results(result, values.dtype)
python
def is_valid(arxiv_id): """ Check that a given arXiv ID is a valid one. :param arxiv_id: The arXiv ID to be checked. :returns: Boolean indicating whether the arXiv ID is valid or not. >>> is_valid('1506.06690') True >>> is_valid('1506.06690v1') True >>> is_valid('arXiv:1506.06690') True >>> is_valid('arXiv:1506.06690v1') True >>> is_valid('arxiv:1506.06690') True >>> is_valid('arxiv:1506.06690v1') True >>> is_valid('math.GT/0309136') True >>> is_valid('abcdf') False >>> is_valid('bar1506.06690foo') False >>> is_valid('mare.GG/0309136') False """ match = REGEX.match(arxiv_id) return (match is not None) and (match.group(0) == arxiv_id)
java
public Set<MailAccount> getReservedMailAccountsForCurrentThread() { lock.lock(); try { Map<MailAccount, ThreadReservationKeyWrapper> accountsForThread = filterValues(usedAccounts, new CurrentThreadWrapperPredicate()); return ImmutableSet.copyOf(accountsForThread.keySet()); } finally { lock.unlock(); } }
java
@Override public void setEnabled(boolean enabled) { if (this.enabled != enabled) { this.enabled = enabled; setProperty("enabled", Boolean.toString(enabled)); if (enabled && getAlertThreshold() == AlertThreshold.OFF) { setAlertThreshold(AlertThreshold.DEFAULT); } } }
python
def create_custom_views(name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=falsee' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(upperview)[0]['symbolId'] payload = '''{ "name": "'''+name+ '''"upperview" : "'''+str(parentviewid)+'''"}''' print (payload) r = requests.post(f_url, data = payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 201: return 'View ' + name +' created successfully' else: print(r.status_code) print("An Error has occured")
python
def vcf_writer(parser, keep, extract, args): """Writes the data in VCF format.""" # The output output = sys.stdout if args.output == "-" else open(args.output, "w") try: # Getting the samples samples = np.array(parser.get_samples(), dtype=str) k = _get_sample_select(samples=samples, keep=keep) # Writing the VCF header output.write(_VCF_HEADER.format( date=datetime.today().strftime("%Y%m%d"), version=__version__, samples="\t".join(samples[k]), )) # The data generator generator = _get_generator(parser=parser, extract=extract, keep=k, check_maf=args.maf) # The number of markers extracted nb_extracted = 0 for data in generator: # Keeping only the required genotypes genotypes = data.genotypes # Computing the alternative allele frequency af = np.nanmean(genotypes) / 2 print(data.variant.chrom, data.variant.pos, data.variant.name, data.reference, data.coded, ".", "PASS", "AF={}".format(af), "GT:DS", sep="\t", end="", file=output) for geno in genotypes: if np.isnan(geno): output.write("\t./.:.") else: rounded_geno = int(round(geno, 0)) output.write("\t{}:{}".format( _VCF_GT_MAP[rounded_geno], geno, )) output.write("\n") nb_extracted += 1 if nb_extracted == 0: logger.warning("No markers matched the extract list") finally: output.close()
python
def _try_validate(cnf, schema, **options): """ :param cnf: Mapping object represents configuration data :param schema: JSON schema object :param options: Keyword options passed to :func:`jsonschema.validate` :return: Given 'cnf' as it is if validation succeeds else None """ valid = True if schema: (valid, msg) = validate(cnf, schema, **options) if msg: LOGGER.warning(msg) if valid: return cnf return None
python
def pymmh3_hash128(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> int: """ Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: integer hash """ if x64arch: return pymmh3_hash128_x64(key, seed) else: return pymmh3_hash128_x86(key, seed)
java
private ReportEntry9 createLine(UmsLine line) throws Exception { ReportEntry9 entry = new ReportEntry9(); EntryDetails8 detail = new EntryDetails8(); entry.getNtryDtls().add(detail); EntryTransaction9 tx = new EntryTransaction9(); detail.getTxDtls().add(tx); // Checken, ob es Soll- oder Habenbuchung ist boolean haben = line.value != null && line.value.getBigDecimalValue().compareTo(BigDecimal.ZERO) > 0; entry.setCdtDbtInd(haben ? CreditDebitCode.CRDT : CreditDebitCode.DBIT); //////////////////////////////////////////////////////////////////////// // Buchungs-ID { TransactionReferences3 ref = new TransactionReferences3(); tx.setRefs(ref); ProprietaryReference1 prt = new ProprietaryReference1(); prt.setRef(line.id); ref.getPrtry().add(prt); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Gegenkonto: IBAN + Name if (line.other != null) { TransactionParties4 other = new TransactionParties4(); tx.setRltdPties(other); CashAccount24 acc = new CashAccount24(); if (haben) other.setDbtrAcct(acc); else other.setCdtrAcct(acc); AccountIdentification4Choice id = new AccountIdentification4Choice(); acc.setId(id); id.setIBAN(line.other.iban); Party35Choice party = new Party35Choice(); PartyIdentification125 pi = new PartyIdentification125(); pi.setNm(line.other.name); party.setPty(pi); if (haben) other.setDbtr(party); else other.setCdtr(party); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Gegenkonto: BIC if (line.other != null) { TransactionAgents4 banks = new TransactionAgents4(); tx.setRltdAgts(banks); BranchAndFinancialInstitutionIdentification5 bank = new BranchAndFinancialInstitutionIdentification5(); if (haben) banks.setDbtrAgt(bank); else banks.setCdtrAgt(bank); FinancialInstitutionIdentification8 bic = new FinancialInstitutionIdentification8(); bank.setFinInstnId(bic); bic.setBICFI(line.other.bic); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Verwendungszweck if (line.usage != null && line.usage.size() > 0) { RemittanceInformation15 usages = new RemittanceInformation15(); usages.getUstrd().addAll(line.usage); tx.setRmtInf(usages); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Betrag if (line.value != null) { ActiveOrHistoricCurrencyAndAmount amt = new ActiveOrHistoricCurrencyAndAmount(); entry.setAmt(amt); BigDecimal val = line.value.getBigDecimalValue(); amt.setValue(val.abs()); // Hier gibt es keine negativen Werte. Wir haben stattdessen DEB/CRED-Merkmale amt.setCcy(line.value.getCurr()); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Storno-Kennzeichen if (line.isStorno) entry.setRvslInd(Boolean.TRUE); // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Buchungs- und Valuta-Datum Date bdate = line.bdate; Date valuta = line.valuta; if (bdate == null) bdate = valuta; if (valuta == null) valuta = bdate; if (bdate != null) { DateAndDateTime2Choice d = new DateAndDateTime2Choice(); d.setDt(this.createCalendar(bdate.getTime())); entry.setBookgDt(d); } if (valuta != null) { DateAndDateTime2Choice d = new DateAndDateTime2Choice(); d.setDt(this.createCalendar(valuta.getTime())); entry.setValDt(d); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Art und Kundenreferenz entry.setAddtlNtryInf(line.text); entry.setAcctSvcrRef(line.customerref); // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Primanota, GV-Code und GV-Code-Ergaenzung StringBuilder sb = new StringBuilder(); if (line.gvcode != null && line.gvcode.length() > 0) { sb.append(line.gvcode); sb.append("+"); } if (line.primanota != null && line.primanota.length() > 0) { sb.append(line.primanota); sb.append("+"); } if (line.addkey != null && line.addkey.length() > 0) { sb.append(line.addkey); } String s = sb.toString(); if (s.length() > 0) { BankTransactionCodeStructure4 b = new BankTransactionCodeStructure4(); tx.setBkTxCd(b); ProprietaryBankTransactionCodeStructure1 pb = new ProprietaryBankTransactionCodeStructure1(); pb.setCd(s); b.setPrtry(pb); } // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Purpose-Code if (line.purposecode != null) { Purpose2Choice c = new Purpose2Choice(); c.setCd(line.purposecode); tx.setPurp(c); } // //////////////////////////////////////////////////////////////////////// return entry; }
java
private synchronized void init() { if (!initialized.compareAndSet(false, true)) { return; } LOG.debug("GStreamer webcam device initialization"); pipe = new Pipeline(getName()); source = ElementFactory.make(GStreamerDriver.getSourceBySystem(), "source"); if (Platform.isWindows()) { source.set("device-index", deviceIndex); } else if (Platform.isLinux()) { source.set("device", videoFile.getAbsolutePath()); } else if (Platform.isMacOSX()) { throw new IllegalStateException("not yet implemented"); } sink = new RGBDataSink(getName(), this); sink.setPassDirectBuffer(true); sink.getSinkElement().setMaximumLateness(LATENESS, TimeUnit.MILLISECONDS); sink.getSinkElement().setQOSEnabled(true); filter = ElementFactory.make("capsfilter", "capsfilter"); jpegdec = ElementFactory.make("jpegdec", "jpegdec"); pipelineReady(); resolutions = parseResolutions(source.getPads().get(0)); pipelineStop(); }
python
def is_between(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if value is None: return False if minimum is not None and maximum is None: return value >= minimum elif minimum is None and maximum is not None: return value <= maximum elif minimum is not None and maximum is not None: return value >= minimum and value <= maximum
python
async def sunionstore(self, dest, keys, *args): """ Store the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Cluster impl: Use sunion() --> Dlete dest key --> store result in dest key Operation is no longer atomic. """ res = await self.sunion(keys, *args) await self.delete(dest) return await self.sadd(dest, *res)
java
public static boolean tryToClose(Closeable closeable) { Object token = ThreadIdentityManager.runAsServer(); try { if (closeable != null) { try { closeable.close(); return true; } catch (IOException e) { // ignore } } } finally { ThreadIdentityManager.reset(token); } return false; }
java
public final B accessToken(String accessToken) { requireNonNull(accessToken, "accessToken"); checkArgument(!accessToken.isEmpty(), "accessToken is empty."); this.accessToken = accessToken; return self(); }
python
def release_downloads(request, package_name, version): """ Retrieve a list of files and download count for a given package and release version. """ session = DBSession() release_files = ReleaseFile.by_release(session, package_name, version) if release_files: release_files = [(f.release.package.name, f.filename) for f in release_files] return release_files
java
private void updateFontButton(@Nonnull final MindMapPanelConfig config) { final String strStyle; final Font thefont = config.getFont(); if (thefont.isBold()) { strStyle = thefont.isItalic() ? "bolditalic" : "bold"; } else { strStyle = thefont.isItalic() ? "italic" : "plain"; } this.buttonFont.setText(thefont.getName() + ", " + strStyle + ", " + thefont.getSize()); }
java
@Override public ListenersModel addListener(ListenerModel listener) { addChildModel(listener); _listeners.add(listener); return this; }
python
def coerce(self, value): """ Coerces value to location hash. """ return { 'lat': float(value.get('lat', value.get('latitude'))), 'lon': float(value.get('lon', value.get('longitude'))) }
python
def stats(self, date=None): '''Return the current statistics for a given queue on a given date. The results are returned are a JSON blob:: { 'total' : ..., 'mean' : ..., 'variance' : ..., 'histogram': [ ... ] } The histogram's data points are at the second resolution for the first minute, the minute resolution for the first hour, the 15-minute resolution for the first day, the hour resolution for the first 3 days, and then at the day resolution from there on out. The `histogram` key is a list of those values.''' return json.loads( self.client('stats', self.name, date or repr(time.time())))
java
private boolean shrinkBlock() throws StructureException, RefinerFailedException { // Let shrink moves only if the repeat is larger enough if (repeatCore <= Lmin) return false; // Select column by maximum distance updateMultipleAlignment(); Matrix residueDistances = MultipleAlignmentTools .getAverageResidueDistances(msa); double maxDist = Double.MIN_VALUE; double[] colDistances = new double[length]; int res = 0; for (int col = 0; col < length; col++) { int normalize = 0; for (int s = 0; s < order; s++) { if (residueDistances.get(s, col) != -1) { colDistances[col] += residueDistances.get(s, col); normalize++; } } colDistances[col] /= normalize; if (colDistances[col] > maxDist) { // geometric distribution if (rnd.nextDouble() > 0.5) { maxDist = colDistances[col]; res = col; } } } for (int su = 0; su < order; su++) { Integer residue = block.get(su).get(res); block.get(su).remove(res); if (residue != null) freePool.add(residue); Collections.sort(freePool); } length--; checkGaps(); return true; }
python
def _StrftimeLocal(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns local time. """ time_tuple = time.localtime(value) return _StrftimeHelper(args, time_tuple)
python
def upload_file_to_s3(awsclient, bucket, key, filename): """Upload a file to AWS S3 bucket. :param awsclient: :param bucket: :param key: :param filename: :return: """ client_s3 = awsclient.get_client('s3') transfer = S3Transfer(client_s3) # Upload /tmp/myfile to s3://bucket/key and print upload progress. transfer.upload_file(filename, bucket, key) response = client_s3.head_object(Bucket=bucket, Key=key) etag = response.get('ETag') version_id = response.get('VersionId', None) return etag, version_id
java
public static ClientConfigurationBuilder builder(final String url, final String username, final String password) { return new ClientConfigurationBuilder(url, username, password); }
python
def _to_edit(self, infoid): ''' render the HTML page for post editing. ''' postinfo = MPost.get_by_uid(infoid) if postinfo: pass else: return self.show404() if 'def_cat_uid' in postinfo.extinfo: catid = postinfo.extinfo['def_cat_uid'] elif 'gcat0' in postinfo.extinfo: catid = postinfo.extinfo['gcat0'] else: catid = '' if len(catid) == 4: pass else: catid = '' catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catid = post2catinfo.tag_id catinfo = MCategory.get_by_uid(catid) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = { 'gcat0': catid, 'parentname': '', 'catname': '', 'parentlist': MCategory.get_parent_list(), 'userip': self.request.remote_ip, 'extinfo': json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False), } if self.filter_view: tmpl = 'autogen/edit/edit_{0}.html'.format(catid) else: tmpl = 'post_{0}/post_edit.html'.format(self.kind) logger.info('Meta template: {0}'.format(tmpl)) self.render( tmpl, kwd=kwd, postinfo=postinfo, catinfo=catinfo, pcatinfo=p_catinfo, userinfo=self.userinfo, cat_enum=MCategory.get_qian2(catid[:2]), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), tag_infos2=MCategory.query_all(by_order=True, kind=self.kind), app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(), app2label_info=MPost2Label.get_by_uid(infoid).objects() )
java
public static DoublePredicate softenDoublePredicate(final CheckedDoublePredicate fn) { return t -> { try { return fn.test(t); } catch (final Throwable e) { throw throwSoftenedException(e); } }; }
python
def init_counts(self, counts_len): '''Called after instantiating with a compressed payload Params: counts_len counts size to use based on decoded settings in the header ''' assert self._data and counts_len and self.counts_len == 0 self.counts_len = counts_len self._init_counts() results = decode(self._data, payload_header_size, addressof(self.counts), counts_len, self.word_size) # no longer needed self._data = None return results
python
def print_frame( self, x: int, y: int, width: int, height: int, string: str = "", clear: bool = True, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a framed rectangle with optional text. This uses the default background color and blend mode to fill the rectangle and the default foreground to draw the outline. `string` will be printed on the inside of the rectangle, word-wrapped. If `string` is empty then no title will be drawn. Args: x (int): The x coordinate from the left. y (int): The y coordinate from the top. width (int): The width if the frame. height (int): The height of the frame. string (str): A Unicode string to print. clear (bool): If True all text in the affected area will be removed. bg_blend (int): The background blending flag. .. versionchanged:: 8.2 Now supports Unicode strings. .. deprecated:: 8.5 Console methods which depend on console defaults have been deprecated. Use :any:`Console.draw_frame` instead, calling this function will print a warning detailing which default values need to be made explicit. """ self.__deprecate_defaults("draw_frame", bg_blend) string = _fmt(string) if string else ffi.NULL lib.TCOD_console_printf_frame( self.console_c, x, y, width, height, clear, bg_blend, string )
java
@Override public Response sendFAX(String CorpNum, MgtKeyType KeyType, String MgtKey, String Sender, String Receiver) throws PopbillException { return sendFAX(CorpNum, KeyType, MgtKey, Sender, Receiver, null); }
java
public String getSectionId() { if (Section_Type.featOkTst && ((Section_Type)jcasType).casFeat_sectionId == null) jcasType.jcas.throwFeatMissing("sectionId", "de.julielab.jules.types.Section"); return jcasType.ll_cas.ll_getStringValue(addr, ((Section_Type)jcasType).casFeatCode_sectionId);}
python
def cmd_gimbal_status(self, args): '''show gimbal status''' master = self.master if 'GIMBAL_REPORT' in master.messages: print(master.messages['GIMBAL_REPORT']) else: print("No GIMBAL_REPORT messages")
python
def get_activities_by_genus_type(self, activity_genus_type): """Gets an ``ActivityList`` corresponding to the given activity genus ``Type`` which does not include activities of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known activities or an error results. Otherwise, the returned list may contain only those activities that are accessible through this session. arg: activity_genus_type (osid.type.Type): an activity genus type return: (osid.learning.ActivityList) - the returned ``Activity`` list raise: NullArgument - ``activity_genus_type`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceLookupSession.get_resources_by_genus_type # NOTE: This implementation currently ignores plenary view collection = JSONClientValidated('learning', collection='Activity', runtime=self._runtime) result = collection.find( dict({'genusTypeId': str(activity_genus_type)}, **self._view_filter())).sort('_id', DESCENDING) return objects.ActivityList(result, runtime=self._runtime, proxy=self._proxy)
java
public static DirectionsApiRequest getDirections( GeoApiContext context, String origin, String destination) { return new DirectionsApiRequest(context).origin(origin).destination(destination); }
java
void writeBootstrapMethods() { int alenIdx = writeAttr(names.BootstrapMethods); databuf.appendChar(bootstrapMethods.size()); for (Map.Entry<DynamicMethod, MethodHandle> entry : bootstrapMethods.entrySet()) { DynamicMethod dmeth = entry.getKey(); DynamicMethodSymbol dsym = (DynamicMethodSymbol)dmeth.baseSymbol(); //write BSM handle databuf.appendChar(pool.get(entry.getValue())); //write static args length databuf.appendChar(dsym.staticArgs.length); //write static args array Object[] uniqueArgs = dmeth.uniqueStaticArgs; for (Object o : uniqueArgs) { databuf.appendChar(pool.get(o)); } } endAttr(alenIdx); }
java
static Set<String> labels(final ResultSet results) throws SQLException { final ResultSetMetaData metadata = results.getMetaData(); final int count = metadata.getColumnCount(); final Set<String> labels = new HashSet<>(count); for (int i = 1; i <= count; i++) { labels.add(metadata.getColumnLabel(i).toUpperCase()); } return labels; }
java
public JsonBeanProcessor findJsonBeanProcessor( Class target ) { if( !beanProcessorMap.isEmpty() ) { Object key = jsonBeanProcessorMatcher.getMatch( target, beanProcessorMap.keySet() ); return (JsonBeanProcessor) beanProcessorMap.get( key ); } return null; }
python
def _build_lv_grid(ding0_grid, network): """ Build eDisGo LV grid from Ding0 data Parameters ---------- ding0_grid: ding0.MVGridDing0 Ding0 MV grid object Returns ------- list of LVGrid LV grids dict Dictionary containing a mapping of LV stations in Ding0 to newly created eDisGo LV stations. This mapping is used to use the same instances of LV stations in the MV grid graph. """ lv_station_mapping = {} lv_grids = [] lv_grid_mapping = {} for la in ding0_grid.grid_district._lv_load_areas: for lvgd in la._lv_grid_districts: ding0_lv_grid = lvgd.lv_grid if not ding0_lv_grid.grid_district.lv_load_area.is_aggregated: # Create LV grid instance lv_grid = LVGrid( id=ding0_lv_grid.id_db, geom=ding0_lv_grid.grid_district.geo_data, grid_district={ 'geom': ding0_lv_grid.grid_district.geo_data, 'population': ding0_lv_grid.grid_district.population}, voltage_nom=ding0_lv_grid.v_level / 1e3, network=network) station = {repr(_): _ for _ in network.mv_grid.graph.nodes_by_attribute( 'lv_station')}['LVStation_' + str( ding0_lv_grid._station.id_db)] station.grid = lv_grid for t in station.transformers: t.grid = lv_grid lv_grid.graph.add_node(station, type='lv_station') lv_station_mapping.update({ding0_lv_grid._station: station}) # Create list of load instances and add these to grid's graph loads = {_: Load( id=_.id_db, geom=_.geo_data, grid=lv_grid, consumption=_.consumption) for _ in ding0_lv_grid.loads()} lv_grid.graph.add_nodes_from(loads.values(), type='load') # Create list of generator instances and add these to grid's # graph generators = {_: (GeneratorFluctuating( id=_.id_db, geom=_.geo_data, nominal_capacity=_.capacity, type=_.type, subtype=_.subtype, grid=lv_grid, weather_cell_id=_.weather_cell_id, v_level=_.v_level) if _.type in ['wind', 'solar'] else Generator( id=_.id_db, geom=_.geo_data, nominal_capacity=_.capacity, type=_.type, subtype=_.subtype, grid=lv_grid, v_level=_.v_level)) for _ in ding0_lv_grid.generators()} lv_grid.graph.add_nodes_from(generators.values(), type='generator') # Create list of branch tee instances and add these to grid's # graph branch_tees = { _: BranchTee(id=_.id_db, geom=_.geo_data, grid=lv_grid, in_building=_.in_building) for _ in ding0_lv_grid._cable_distributors} lv_grid.graph.add_nodes_from(branch_tees.values(), type='branch_tee') # Merge node above defined above to a single dict nodes = {**loads, **generators, **branch_tees, **{ding0_lv_grid._station: station}} edges = [] edges_raw = list(nx.get_edge_attributes( ding0_lv_grid._graph, 'branch').items()) for edge in edges_raw: edges.append({'adj_nodes': edge[0], 'branch': edge[1]}) # Create list of line instances and add these to grid's graph lines = [(nodes[_['adj_nodes'][0]], nodes[_['adj_nodes'][1]], {'line': Line( id=_['branch'].id_db, type=_['branch'].type, length=_['branch'].length / 1e3, kind=_['branch'].kind, grid=lv_grid) }) for _ in edges] # convert voltage from V to kV for line in lines: # ToDo: remove work around once it's fixed in ding0 if line[2]['line'].type['U_n'] >= 400: line[2]['line'].type['U_n'] = \ line[2]['line'].type['U_n'] / 1e3 lv_grid.graph.add_edges_from(lines, type='line') # Add LV station as association to LV grid lv_grid._station = station # Add to lv grid mapping lv_grid_mapping.update({lv_grid: ding0_lv_grid}) # Put all LV grid to a list of LV grids lv_grids.append(lv_grid) # ToDo: don't forget to adapt lv stations creation in MV grid return lv_grids, lv_station_mapping, lv_grid_mapping
java
public OvhFrontendUdp serviceName_udp_frontend_POST(String serviceName, String[] dedicatedIpfo, Long defaultFarmId, Boolean disabled, String displayName, String port, String zone) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/udp/frontend"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "dedicatedIpfo", dedicatedIpfo); addBody(o, "defaultFarmId", defaultFarmId); addBody(o, "disabled", disabled); addBody(o, "displayName", displayName); addBody(o, "port", port); addBody(o, "zone", zone); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhFrontendUdp.class); }
python
def _try_mask_first_value(value, row, all_close): ''' mask first value in row value1 : ~typing.Any row : 1d masked array all_close : bool compare with np.isclose instead of == Return whether masked a value ''' # Compare value to row for i, value2 in enumerate(row): if _value_equals(value, value2, all_close): row[i] = ma.masked return True return False
python
def singlerose(self, Width=1, Color=['red']): ''' draw the rose map of single sample with different items~ ''' self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1]) self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1] self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])] Name = self.SingleRoseName self.axes.clear() # self.axes.set_xlim(-90, 450) # self.axes.set_ylim(0, 90) titles = list('NWSE') titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30'] self.n = len(titles) self.angles = np.arange(90, 90 + 360, 360.0 / self.n) self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330., 360., 30., 60.]) self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14) self.raw = self._df real_max = [] for k in range(len(Name)): Data = [] S = [] R = [] for i in range(len(self.raw)): S.append(self.raw.at[i, Name[k]]) s = np.linspace(0, 360, 360 / self.Gap + 1) t = tuple(s.tolist()) count = [] for i in range(len(t)): tmp_count = 0 for j in S: if i < len(t) - 1: if t[i] < j <= t[i + 1]: tmp_count += 1 count.append(tmp_count) count_max = max(count) real_max.append(count_max) maxuse = max(real_max) for k in range(len(Name)): Data = [] S = [] R = [] for i in range(len(self.raw)): S.append(self.raw.at[i, Name[k]]) s = np.linspace(0, 360, 360 / self.Gap + 1) t = tuple(s.tolist()) count = [] for i in range(len(t)): tmp_count = 0 for j in S: if i < len(t) - 1: if t[i] < j <= t[i + 1]: tmp_count += 1 count.append(tmp_count) s = np.linspace(0, 360, 360 / self.Gap + 1) t = tuple(s.tolist()) R_factor = 90 / maxuse for i in count: TMP = 90 - i * R_factor R.append(TMP) m, n = self.Trans(t, R) self.axes.plot(m, n, color=Color[k], linewidth=1, alpha=0.6, marker='') self.axes.fill(m, n, Color=Color[k], Alpha=0.6, ) if (self.Type_cb.isChecked()): self.Type_cb.setText('Wulf') list1 = [self.eqan(x) for x in range(15, 90, 15)] else: self.Type_cb.setText('Schmidt') list1 = [self.eqar(x) for x in range(15, 90, 15)] list2= list1 print(maxuse + 1) try: list2 = [str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1.0) / 7.0))] except(ValueError): pass list2.reverse() self.axes.set_rgrids(list1, list2) #self.axes.set_thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)]) if (self.legend_cb.isChecked()): self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop)
python
def merge_dicts(i): """ Input: { dict1 - merge this dict with dict2 (will be directly modified!) dict2 - dict Output: { return - return code = 0, if successful dict1 - output dict } """ a=i['dict1'] b=i['dict2'] for k in b: v=b[k] if type(v) is dict: if k not in a: a.update({k:b[k]}) elif type(a[k])==dict: merge_dicts({'dict1':a[k], 'dict2':b[k]}) else: a[k]=b[k] elif type(v) is list: a[k]=[] for y in v: a[k].append(y) else: a[k]=b[k] return {'return':0, 'dict1':a}
java
public void appendExists(Filter<S> filter) throws FetchException { mStatementBuilder.append(" WHERE "); mStatementBuilder.append("EXISTS (SELECT * FROM"); JDBCStorableInfo<S> info; final JDBCRepository repo = mStatementBuilder.getRepository(); try { info = repo.examineStorable(filter.getStorableType()); } catch (RepositoryException e) { throw repo.toFetchException(e); } JoinNode jn; try { JoinNodeBuilder jnb = new JoinNodeBuilder(repo, info, mAliasGenerator); filter.accept(jnb, null); jn = jnb.getRootJoinNode(); } catch (UndeclaredThrowableException e) { throw repo.toFetchException(e); } jn.appendFullJoinTo(mStatementBuilder); mStatementBuilder.append(" WHERE "); { int i = 0; for (JDBCStorableProperty<S> property : info.getPrimaryKeyProperties().values()) { if (i > 0) { mStatementBuilder.append(" AND "); } mStatementBuilder.append(mJoinNode.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); mStatementBuilder.append('='); mStatementBuilder.append(jn.getAlias()); mStatementBuilder.append('.'); mStatementBuilder.append(property.getColumnName()); i++; } } mStatementBuilder.append(" AND ("); WhereBuilder<S> wb = new WhereBuilder<S>(mStatementBuilder, jn, mAliasGenerator); FetchException e = filter.accept(wb, null); if (e != null) { throw e; } // Transfer property filters so that the values are extracted properly. mPropertyFilters.addAll(wb.mPropertyFilters); mPropertyFilterNullable.addAll(wb.mPropertyFilterNullable); mStatementBuilder.append(')'); mStatementBuilder.append(')'); }
java
public static JPanel makeVBox (Policy policy, Justification justification) { return new JPanel(new VGroupLayout(policy, justification)); }
python
def invalidate(self, cls, id_field, id_val): """ Invalidate the cache for a given Mongo object by deleting the cached data and the cache flag. """ cache_key, flag_key = self.get_keys(cls, id_field, id_val) pipeline = self.redis.pipeline() pipeline.delete(cache_key) pipeline.delete(flag_key) pipeline.execute()
python
def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ mkdir_p('/tmp/test/test') source('/root/.bash_profile') yum_install(['httpd', 'git']) yum_install(['httpd', 'git'], dest_dir='/tmp/test/test', downloadonly=True) sed('/Users/yennaco/Downloads/homer_testing/network', '^HOSTNAME.*', 'HOSTNAME=foo.joe') test_script = '/Users/yennaco/Downloads/homer/script.sh' results = run_command([test_script], timeout_sec=1000) print('Script {s} produced exit code [{c}] and output:\n{o}'.format( s=test_script, c=results['code'], o=results['output']))
java
public DoubleStreamEx mapFirst(DoubleUnaryOperator mapper) { return delegate(new PairSpliterator.PSOfDouble((a, b) -> b, mapper, spliterator(), PairSpliterator.MODE_MAP_FIRST)); }
java
public static <T> boolean compareLists(List<T> list1, List<T> list2) { if (list1 == list2) return true; if (list1 == null || list2 == null) return false; if (list1.size() != list2.size()) return false; for (int i = 0; i < list1.size(); i++) { if (!list1.get(i).equals(list2.get(i))) { return false; } } return true; }
python
def dict_selective_merge(a, b, selection, path=None): """Conditionally merges b into a if b's keys are contained in selection :param a: :param b: :param selection: limit merge to these top-level keys :param path: :return: """ if path is None: path = [] for key in b: if key in selection: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): dict_selective_merge(a[key], b[key], b[key].keys(), path + [str(key)]) elif a[key] != b[key]: # update the value a[key] = b[key] else: a[key] = b[key] return a
java
protected List<ImageDTO> extractImagesFromCursor(Cursor cursor, int offset, int limit) { List<ImageDTO> images = new ArrayList<>(); int count = 0; int begin = offset > 0 ? offset : 0; if (cursor.moveToPosition(begin)) { do { ImageDTO image = extractOneImageFromCurrentCursor(cursor); images.add(image); count++; if (limit > 0 && count > limit) { break; } } while (cursor.moveToNext()); } cursor.close(); return images; }
python
def _filter(self, dict, keep): """ Remove any keys not in 'keep' """ if not keep: return dict result = {} for key, value in dict.iteritems(): if key in keep: result[key] = value return result
java
public static Seconds seconds(int seconds) { switch (seconds) { case 0: return ZERO; case 1: return ONE; case 2: return TWO; case 3: return THREE; case Integer.MAX_VALUE: return MAX_VALUE; case Integer.MIN_VALUE: return MIN_VALUE; default: return new Seconds(seconds); } }
java
@Override public void execute() throws MojoExecutionException { try { ensureNotExisting(); createDirectories(); if ("blank".equalsIgnoreCase(skel)) { createApplicationConfiguration(); createBlankPomFile(); createPackageStructure(); copyDefaultErrorTemplates(); } else { createApplicationConfiguration(); createPomFile(); createPackageStructure(); createDefaultController(); createTests(); copyAssets(); createWelcomeTemplate(); copyDefaultErrorTemplates(); } printStartGuide(); } catch (IOException e) { throw new MojoExecutionException("Error during project generation", e); } }
java
public void setWidth(int width) { this.width = width; getElement().getStyle().setWidth(width, Style.Unit.PX); }
python
def _check_pyopengl_3D(): """Helper to ensure users have OpenGL for 3D texture support (for now)""" global USE_TEX_3D USE_TEX_3D = True try: import OpenGL.GL as _gl except ImportError: raise ImportError('PyOpenGL is required for 3D texture support') return _gl
java
private void scan(final String targetPath, final String basePackageName, final String relativePackageName, final WildcardMatcher matcher, final SaveHandler saveHandler) { final File target = new File(targetPath); if (!target.exists()) { return; } target.listFiles(file -> { String fileName = file.getName(); if (file.isDirectory()) { String relativePackageName2; if (relativePackageName == null) { relativePackageName2 = fileName + ResourceUtils.REGULAR_FILE_SEPARATOR; } else { relativePackageName2 = relativePackageName + fileName + ResourceUtils.REGULAR_FILE_SEPARATOR; } String basePath2 = targetPath + fileName + ResourceUtils.REGULAR_FILE_SEPARATOR; scan(basePath2, basePackageName, relativePackageName2, matcher, saveHandler); } else if (fileName.endsWith(ClassUtils.CLASS_FILE_SUFFIX)) { String className; if (relativePackageName != null) { className = basePackageName + relativePackageName + fileName.substring(0, fileName.length() - ClassUtils.CLASS_FILE_SUFFIX.length()); } else { className = basePackageName + fileName.substring(0, fileName.length() - ClassUtils.CLASS_FILE_SUFFIX.length()); } String relativePath = className.substring(basePackageName.length()); if (matcher.matches(relativePath)) { String resourceName = targetPath + fileName; Class<?> targetClass = loadClass(className); saveHandler.save(resourceName, targetClass); } } return false; }); }
java
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int startX = 0; int endX = getWidth(); int lineHeight; int startYLine = getHeight() - getPaddingBottom() + underlineTopSpacing; int startYFloatingLabel = (int) (getPaddingTop() - floatingLabelPercent * floatingLabelBottomSpacing); if (error != null && enableErrorLabel) { lineHeight = dpToPx(thicknessError); int startYErrorLabel = startYLine + errorLabelSpacing + lineHeight; paint.setColor(errorColor); textPaint.setColor(errorColor); //Error Label Drawing if (multiline) { canvas.save(); canvas.translate(startX + rightLeftSpinnerPadding, startYErrorLabel - errorLabelSpacing); staticLayout.draw(canvas); canvas.restore(); } else { //scrolling canvas.drawText(error.toString(), startX + rightLeftSpinnerPadding - errorLabelPosX, startYErrorLabel, textPaint); if (errorLabelPosX > 0) { canvas.save(); canvas.translate(textPaint.measureText(error.toString()) + getWidth() / 2, 0); canvas.drawText(error.toString(), startX + rightLeftSpinnerPadding - errorLabelPosX, startYErrorLabel, textPaint); canvas.restore(); } } } else { lineHeight = dpToPx(thickness); if (isSelected || hasFocus()) { paint.setColor(highlightColor); } else { paint.setColor(isEnabled() ? baseColor : disabledColor); } } // Underline Drawing canvas.drawRect(startX, startYLine, endX, startYLine + lineHeight, paint); //Floating Label Drawing if ((hint != null || floatingLabelText != null) && enableFloatingLabel) { if (isSelected || hasFocus()) { textPaint.setColor(highlightColor); } else { textPaint.setColor(isEnabled() ? floatingLabelColor : disabledColor); } if (floatingLabelAnimator.isRunning() || !floatingLabelVisible) { textPaint.setAlpha((int) ((0.8 * floatingLabelPercent + 0.2) * baseAlpha * floatingLabelPercent)); } String textToDraw = floatingLabelText != null ? floatingLabelText.toString() : hint.toString(); if (isRtl) { canvas.drawText(textToDraw, getWidth() - rightLeftSpinnerPadding - textPaint.measureText(textToDraw), startYFloatingLabel, textPaint); } else { canvas.drawText(textToDraw, startX + rightLeftSpinnerPadding, startYFloatingLabel, textPaint); } } drawSelector(canvas, getWidth() - rightLeftSpinnerPadding, getPaddingTop() + dpToPx(8)); }
java
public void send(String channel, String message) { // CAUSE: Assignment to method parameter Pair<Boolean, String> sendValidation = isSendValid(channel, message, null, null); //String lMessage = message.replace("\n", "\\n"); if (sendValidation != null && sendValidation.first) { try { String messageId = Strings.randomString(8); ArrayList<Pair<String, String>> messagesToSend = multiPartMessage( message, messageId); for (Pair<String, String> messageToSend : messagesToSend) { send(channel, messageToSend.second, messageToSend.first, sendValidation.second); } } catch (IOException e) { raiseOrtcEvent(EventEnum.OnException, this, e); } } }
python
def dendrogram(df, method='average', filter=None, n=0, p=0, sort=None, orientation=None, figsize=None, fontsize=16, inline=False ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertical display will fit up to 50 columns. If more than 50 columns are specified and orientation is left unspecified the dendrogram will automatically swap to a horizontal display to fit the additional variables. :param df: The DataFrame whose completeness is being dendrogrammed. :param method: The distance measure being used for clustering. This is a parameter that is passed to `scipy.hierarchy`. :param filter: The filter to apply to the heatmap. Should be one of "top", "bottom", or None (default). :param n: The cap on the number of columns to include in the filtered DataFrame. :param p: The cap on the percentage fill of the columns in the filtered DataFrame. :param sort: The sort to apply to the heatmap. Should be one of "ascending", "descending", or None. :param figsize: The size of the figure to display. This is a `matplotlib` parameter which defaults to `(25, 10)`. :param fontsize: The figure's font size. :param orientation: The way the dendrogram is oriented. Defaults to top-down if there are less than or equal to 50 columns and left-right if there are more. :param inline: Whether or not the figure is inline. If it's not then instead of getting plotted, this method will return its figure. :return: If `inline` is False, the underlying `matplotlib.figure` object. Else, nothing. """ if not figsize: if len(df.columns) <= 50 or orientation == 'top' or orientation == 'bottom': figsize = (25, 10) else: figsize = (25, (25 + len(df.columns) - 50)*0.5) plt.figure(figsize=figsize) gs = gridspec.GridSpec(1, 1) ax0 = plt.subplot(gs[0]) df = nullity_filter(df, filter=filter, n=n, p=p) df = nullity_sort(df, sort=sort) # Link the hierarchical output matrix, figure out orientation, construct base dendrogram. x = np.transpose(df.isnull().astype(int).values) z = hierarchy.linkage(x, method) if not orientation: if len(df.columns) > 50: orientation = 'left' else: orientation = 'bottom' hierarchy.dendrogram(z, orientation=orientation, labels=df.columns.tolist(), distance_sort='descending', link_color_func=lambda c: 'black', leaf_font_size=fontsize, ax=ax0 ) # Remove extraneous default visual elements. ax0.set_aspect('auto') ax0.grid(b=False) if orientation == 'bottom': ax0.xaxis.tick_top() ax0.xaxis.set_ticks_position('none') ax0.yaxis.set_ticks_position('none') ax0.spines['top'].set_visible(False) ax0.spines['right'].set_visible(False) ax0.spines['bottom'].set_visible(False) ax0.spines['left'].set_visible(False) ax0.patch.set_visible(False) # Set up the categorical axis labels and draw. if orientation == 'bottom': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='left') elif orientation == 'top': ax0.set_xticklabels(ax0.xaxis.get_majorticklabels(), rotation=45, ha='right') if orientation == 'bottom' or orientation == 'top': ax0.tick_params(axis='y', labelsize=int(fontsize / 16 * 20)) else: ax0.tick_params(axis='x', labelsize=int(fontsize / 16 * 20)) if inline: plt.show() else: return ax0
python
def _datetime_from_json(value, field): """Coerce 'value' to a datetime, if set or not nullable. Args: value (str): The timestamp. field (.SchemaField): The field corresponding to the value. Returns: Optional[datetime.datetime]: The parsed datetime object from ``value`` if the ``field`` is not null (otherwise it is :data:`None`). """ if _not_null(value, field): if "." in value: # YYYY-MM-DDTHH:MM:SS.ffffff return datetime.datetime.strptime(value, _RFC3339_MICROS_NO_ZULU) else: # YYYY-MM-DDTHH:MM:SS return datetime.datetime.strptime(value, _RFC3339_NO_FRACTION) else: return None
python
def set_application(self, app, callback=None): """ Set ``CommandLineInterface`` instance for this connection. (This can be replaced any time.) :param cli: CommandLineInterface instance. :param callback: Callable that takes the result of the CLI. """ assert isinstance(app, Application) assert callback is None or callable(callback) self.cli = CommandLineInterface( application=app, eventloop=self.eventloop, output=self.vt100_output) self.callback = callback # Create a parser, and parser callbacks. cb = self.cli.create_eventloop_callbacks() inputstream = InputStream(cb.feed_key) # Input decoder for stdin. (Required when working with multibyte # characters, like chinese input.) stdin_decoder_cls = getincrementaldecoder(self.encoding) stdin_decoder = [stdin_decoder_cls()] # nonlocal # Tell the CLI that it's running. We don't start it through the run() # call, but will still want _redraw() to work. self.cli._is_running = True def data_received(data): """ TelnetProtocolParser 'data_received' callback """ assert isinstance(data, binary_type) try: result = stdin_decoder[0].decode(data) inputstream.feed(result) except UnicodeDecodeError: stdin_decoder[0] = stdin_decoder_cls() return '' def size_received(rows, columns): """ TelnetProtocolParser 'size_received' callback """ self.size = Size(rows=rows, columns=columns) cb.terminal_size_changed() self.parser = TelnetProtocolParser(data_received, size_received)
java
public boolean isRadioButtonValueSelected(final String radioButtonName, final String value) { List<WebElement> radioGroup = driver.findElements(By .name(radioButtonName)); for (WebElement button : radioGroup) { if (button.getAttribute("value").equalsIgnoreCase(value) && button.isSelected()) { return true; } } return false; }
java
private void submitTaskStateEvent(TaskState taskState, Map<String, String> jobMetadata) { ImmutableMap.Builder<String, String> taskMetadataBuilder = new ImmutableMap.Builder<>(); taskMetadataBuilder.putAll(jobMetadata); taskMetadataBuilder.put(METADATA_TASK_ID, taskState.getTaskId()); taskMetadataBuilder.put(METADATA_TASK_START_TIME, Long.toString(taskState.getStartTime())); taskMetadataBuilder.put(METADATA_TASK_END_TIME, Long.toString(taskState.getEndTime())); taskMetadataBuilder.put(METADATA_TASK_WORKING_STATE, taskState.getWorkingState().toString()); taskMetadataBuilder.put(METADATA_TASK_FAILURE_CONTEXT, taskState.getTaskFailureException().or(UNKNOWN_VALUE)); taskMetadataBuilder.put(EventSubmitter.EVENT_TYPE, TASK_STATE); this.eventSubmitter.submit(TASK_STATE, taskMetadataBuilder.build()); }
python
def slow_highlight(img1, img2, opts): """Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, smoothing it a bit to reduce spurious matches in areas that are perceptibly different (e.g. text), and then taking the point-wise minimum of all those difference maps. This way if you insert a few pixel rows/columns into an image, similar areas should match even if different areas need to be aligned with different shifts. As you can imagine, this brute-force approach can be pretty slow, if there are many possible alignments. The closer the images are in size, the faster this will work. If would work better if it could compare alignments that go beyond the outer boundaries of the images, in case some pixels got shifted closer to an edge. """ w1, h1 = img1.size w2, h2 = img2.size W, H = max(w1, w2), max(h1, h2) pimg1 = Image.new('RGB', (W, H), opts.bgcolor) pimg2 = Image.new('RGB', (W, H), opts.bgcolor) pimg1.paste(img1, (0, 0)) pimg2.paste(img2, (0, 0)) diff = Image.new('L', (W, H), 255) # It is not a good idea to keep one diff image; it should track the # relative positions of the two images. I think that's what explains # the fuzz I see near the edges of the different areas. xr = abs(w1 - w2) + 1 yr = abs(h1 - h2) + 1 try: p = Progress(xr * yr, timeout=opts.timeout) for x in range(xr): for y in range(yr): p.next() this = ImageChops.difference(pimg1, pimg2).convert('L') this = this.filter(ImageFilter.MaxFilter(7)) diff = ImageChops.darker(diff, this) if h1 > h2: pimg2 = ImageChops.offset(pimg2, 0, 1) else: pimg1 = ImageChops.offset(pimg1, 0, 1) if h1 > h2: pimg2 = ImageChops.offset(pimg2, 0, -yr) else: pimg1 = ImageChops.offset(pimg1, 0, -yr) if w1 > w2: pimg2 = ImageChops.offset(pimg2, 1, 0) else: pimg1 = ImageChops.offset(pimg1, 1, 0) except KeyboardInterrupt: return None, None diff = diff.filter(ImageFilter.MaxFilter(5)) diff1 = diff.crop((0, 0, w1, h1)) diff2 = diff.crop((0, 0, w2, h2)) mask1 = tweak_diff(diff1, opts.opacity) mask2 = tweak_diff(diff2, opts.opacity) return mask1, mask2
python
def add(self, command, response): """ Register a command/response pair. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sent as the response to any command that matches the given regular expression. If the given response handler is a function, it is called with the command passed as an argument. :type command: str|regex :param command: A string or a compiled regular expression. :type response: function|str :param response: A reponse, or a response handler. """ command = re.compile(command) self.response_list.append((command, response))
java
@Override public Object invoke(Object[] allVals) throws InvocationTargetException { Object[] vals; Object tmp; vals = new Object[paraParaCount]; System.arraycopy(allVals, idx, vals, 0, vals.length); tmp = para.invoke(vals); vals = new Object[baseParaCount]; System.arraycopy(allVals, 0, vals, 0, idx); vals[idx] = tmp; System.arraycopy(allVals, idx + paraParaCount, vals, idx + 1, vals.length - (idx + 1)); return base.invoke(vals); }
java
public TedTask getTask(Long taskId) { if (taskId == null) return null; return tedDriverImpl.getTask(taskId); }
java
public static String wrap(String line, int widthInCharacters, String indent) { StringBuilder buffer = new StringBuilder(); int lineCount = 1; int spaceIndex; // if indent is null, then do not indent the wrapped lines indent = (indent != null ? indent : EMPTY_STRING); while (line.length() > widthInCharacters) { spaceIndex = line.substring(0, widthInCharacters).lastIndexOf(SINGLE_SPACE); buffer.append(lineCount++ > 1 ? indent : EMPTY_STRING); // throws IndexOutOfBoundsException if spaceIndex is -1, implying no word boundary was found within // the given width; this also avoids the infinite loop buffer.append(line.substring(0, spaceIndex)); buffer.append(LINE_SEPARATOR); // possible infinite loop if spaceIndex is -1, see comment above line = line.substring(spaceIndex + 1); } buffer.append(lineCount > 1 ? indent : EMPTY_STRING); buffer.append(line); return buffer.toString(); }
java
public static void assertJsonPartNotEquals(Object expected, Object fullJson, String path, Configuration configuration) { Diff diff = create(expected, fullJson, FULL_JSON, path, configuration); if (diff.similar()) { if (ROOT.equals(path)) { doFail("Expected different values but the values were equal."); } else { doFail(String.format("Expected different values in node \"%s\" but the values were equal.", path)); } } }
java
public void setResponses(Map<String, List<Map<String, AttributeValue>>> responses) { this.responses = responses; }
java
public List<EventData> parse(Long pipelineId, List<Entry> datas) throws SelectException { List<EventData> eventDatas = new ArrayList<EventData>(); Pipeline pipeline = configClientService.findPipeline(pipelineId); List<Entry> transactionDataBuffer = new ArrayList<Entry>(); // hz为主站点,us->hz的数据,需要回环同步会us。并且需要开启回环补救算法 PipelineParameter pipelineParameter = pipeline.getParameters(); boolean enableLoopbackRemedy = pipelineParameter.isEnableRemedy() && pipelineParameter.isHome() && pipelineParameter.getRemedyAlgorithm().isLoopback(); boolean isLoopback = false; boolean needLoopback = false; // 判断是否属于需要loopback处理的类型,只处理正常otter同步产生的回环数据,因为会有业务方手工屏蔽同步的接口,避免回环 long now = new Date().getTime(); try { for (Entry entry : datas) { switch (entry.getEntryType()) { case TRANSACTIONBEGIN: isLoopback = false; break; case ROWDATA: String tableName = entry.getHeader().getTableName(); // 判断是否是回环表retl_mark boolean isMarkTable = tableName.equalsIgnoreCase(pipeline.getParameters().getSystemMarkTable()); if (isMarkTable) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkLoopback(pipeline, rowChange.getRowDatas(0)); } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 } isLoopback |= loopback > 0; } } // 检查下otter3.0的回环表,对应的schmea会比较随意,所以不做比较 boolean isCompatibleLoopback = tableName.equalsIgnoreCase(compatibleMarkTable); if (isCompatibleLoopback) { RowChange rowChange = RowChange.parseFrom(entry.getStoreValue()); if (!rowChange.getIsDdl()) { int loopback = 0; if (rowChange.getRowDatasCount() > 0) { loopback = checkCompatibleLoopback(pipeline, rowChange.getRowDatas(0)); } if (loopback == 2) { needLoopback |= true; // 只处理正常同步产生的回环数据 } isLoopback |= loopback > 0; } } if ((!isLoopback || (enableLoopbackRemedy && needLoopback)) && !isMarkTable && !isCompatibleLoopback) { transactionDataBuffer.add(entry); } break; case TRANSACTIONEND: if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); } else { eventData.setSyncConsistency(SyncConsistency.BASE); } eventData.setRemedy(true); } eventDatas.add(eventData); } } } isLoopback = false; needLoopback = false; transactionDataBuffer.clear(); break; default: break; } } // 添加最后一次的数据,可能没有TRANSACTIONEND if (!isLoopback || (enableLoopbackRemedy && needLoopback)) { // 添加数据解析 for (Entry bufferEntry : transactionDataBuffer) { List<EventData> parseDatas = internParse(pipeline, bufferEntry); if (CollectionUtils.isEmpty(parseDatas)) {// 可能为空,针对ddl返回时就为null continue; } // 初步计算一下事件大小 long totalSize = bufferEntry.getHeader().getEventLength(); long eachSize = totalSize / parseDatas.size(); for (EventData eventData : parseDatas) { if (eventData == null) { continue; } eventData.setSize(eachSize);// 记录一下大小 if (needLoopback) {// 针对需要回环同步的 // 如果延迟超过指定的阀值,则设置为需要反查db if (now - eventData.getExecuteTime() > 1000 * pipeline.getParameters() .getRemedyDelayThresoldForMedia()) { eventData.setSyncConsistency(SyncConsistency.MEDIA); } else { eventData.setSyncConsistency(SyncConsistency.BASE); } } eventDatas.add(eventData); } } } } catch (Exception e) { throw new SelectException(e); } return eventDatas; }
python
def scipy_constraints(self, constraints): """ Returns all constraints in a scipy compatible format. :param constraints: List of either MinimizeModel instances (this is what is provided by :class:`~symfit.core.fit.Fit`), :class:`~symfit.core.fit.BaseModel`, or :class:`sympy.core.relational.Relational`. :return: dict of scipy compatible statements. """ cons = [] types = { # scipy only distinguishes two types of constraint. sympy.Eq: 'eq', sympy.Ge: 'ineq', } for constraint in constraints: if isinstance(constraint, MinimizeModel): # Typically the case when called by `Fit constraint_type = constraint.model.constraint_type elif hasattr(constraint, 'constraint_type'): # Model object, not provided by `Fit`. Do the best we can. if self.parameters != constraint.params: raise AssertionError('The constraint should accept the same' ' parameters as used for the fit.') constraint_type = constraint.constraint_type constraint = MinimizeModel(constraint, data=self.objective.data) elif isinstance(constraint, sympy.Rel): constraint_type = constraint.__class__ constraint = self.objective.model.__class__.as_constraint( constraint, self.objective.model ) constraint = MinimizeModel(constraint, data=self.objective.data) else: raise TypeError('Unknown type for a constraint.') con = { 'type': types[constraint_type], 'fun': constraint, } cons.append(con) cons = tuple(cons) return cons
python
def _generate_permutation(self, npoints): """ Create shuffle and deshuffle vectors """ i = np.arange(0, npoints) # permutation p = np.random.permutation(npoints) ip = np.empty_like(p) # inverse permutation ip[p[i]] = i return p, ip
python
def eventFilter( self, object, event ): """ Filters the chart widget for the resize event to modify this scenes rect. :param object | <QObject> event | <QEvent> """ if ( event.type() != event.Resize ): return False size = event.size() w = size.width() h = size.height() hpolicy = Qt.ScrollBarAlwaysOff vpolicy = Qt.ScrollBarAlwaysOff if ( self._minimumHeight != -1 and h < self._minimumHeight ): h = self._minimumHeight vpolicy = Qt.ScrollBarAsNeeded if ( self._maximumHeight != -1 and self._maximumHeight < h ): h = self._maximumHeight vpolicy = Qt.ScrollBarAsNeeded if ( self._minimumWidth != -1 and w < self._minimumWidth ): w = self._minimumWidth hpolicy = Qt.ScrollBarAsNeeded if ( self._maximumWidth != -1 and self._maximumWidth < w ): w = self._maximumWidth hpolicy = Qt.ScrollBarAsNeeded hruler = self.horizontalRuler() vruler = self.verticalRuler() hlen = hruler.minLength(Qt.Horizontal) vlen = hruler.minLength(Qt.Vertical) offset_w = 0 offset_h = 0 # if ( hlen > w ): # w = hlen # hpolicy = Qt.ScrollBarAlwaysOn # offset_h = 25 # # if ( vlen > h ): # h = vlen # vpolicy = Qt.ScrollBarAlwaysOn # offset_w = 25 self.setSceneRect(0, 0, w - offset_w, h - offset_h) object.setVerticalScrollBarPolicy(vpolicy) object.setHorizontalScrollBarPolicy(hpolicy) return False
python
def setter_generator(field_name): """ Generate set_'field name' method for field field_name. """ def set_translation_field(cls, value, language_code=None): setattr(cls.get_translation(language_code, True), field_name, value) set_translation_field.short_description = "set " + field_name return set_translation_field
python
def _set_interface_ipv6(self, v, load=False): """ Setter method for interface_ipv6, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_ipv6 (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_ipv6 is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_ipv6() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=interface_ipv6.interface_ipv6, is_container='container', presence=False, yang_name="interface-ipv6", rest_name="ipv6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Interface ipv6 attributes for isis', u'cli-incomplete-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-incomplete-command': None, u'alt-name': u'ipv6'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_ipv6 must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=interface_ipv6.interface_ipv6, is_container='container', presence=False, yang_name="interface-ipv6", rest_name="ipv6", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Interface ipv6 attributes for isis', u'cli-incomplete-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-incomplete-command': None, u'alt-name': u'ipv6'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True)""", }) self.__interface_ipv6 = t if hasattr(self, '_set'): self._set()
java
public void setObjects(Object object) { if (Collection.class.isAssignableFrom(object.getClass())) { this.objects = (Collection) object; } }
python
def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g_nums |int| or length-R iterable |int| or |None| -- Index/indices of the desired geometry/geometries ats_1 |int| or iterable |int| or |None| -- Index/indices of the first atom(s) ats_2 |int| or iterable |int| or |None| -- Index/indices of the second atom(s) invalid_error |bool|, optional -- If |False| (the default), |None| values are returned for results corresponding to invalid indices. If |True|, exceptions are raised per normal. Yields ------ dist |npfloat_| -- Interatomic distance in Bohrs between each atom pair of `ats_1` and `ats_2` from the corresponding geometries of `g_nums`. Raises ------ ~exceptions.IndexError If an invalid (out-of-range) `g_num` or `at_#` is provided. ~exceptions.ValueError If all iterable objects are not the same length. """ # Imports import numpy as np from .utils import pack_tups # Print the function inputs if debug mode is on if _DEBUG: # pragma: no cover print("g_nums = {0}".format(g_nums)) print("ats_1 = {0}".format(ats_1)) print("ats_2 = {0}".format(ats_2)) ## end if # Perform the None substitution arglist = self._none_subst(g_nums, ats_1, ats_2) # Expand/pack the tuples from the inputs tups = pack_tups(*arglist) # Dump the results if debug mode is on if _DEBUG: # pragma: no cover print(tups) ## end if # Construct the generator using the packed tuples. If 'None' expansion # was used, return None for any invalid indices instead of raising # an exception. for tup in tups: yield self._iter_return(tup, self.dist_single, invalid_error)