language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_fw_policy(self, policy_id): """Return the firewall policy, given its ID. """ policy = None try: policy = self.neutronclient.show_firewall_policy(policy_id) except Exception as exc: LOG.error("Failed to get firewall plcy for id %(id)s " ...
java
public String toQueryString() { if (this.parameters == null) { return String.format("filter=%s", this.name); } else { List<String> queries = new ArrayList<String>(); for(Map.Entry<String, String> parameter : this.parameters.entrySet()) { queries.add(S...
java
void reload(NetworkConfig config) { try { log.trace("Load config data from " + config.path + " into " + config); final ConfigPropertyData read = configService.read(config.path, configInstanceId, config.getLastRevision()); // Abort if the server returns no config - we have the latest revision if (read ...
java
@BetaApi public final Operation setBackupTargetPool( ProjectRegionTargetPoolName targetPool, Float failoverRatio, TargetReference targetReferenceResource) { SetBackupTargetPoolHttpRequest request = SetBackupTargetPoolHttpRequest.newBuilder() .setTargetPool(targetPool == null...
python
def GetHTTPHeaders(self): """Returns the HTTP headers required for request authorization. Returns: A dictionary containing the required headers. """ http_headers = self._adwords_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' ...
python
def _status(self): """Return html saying whether this Action is reverted by another one or reverts another one.""" text = "" # Turns out that is related field in null, Django # doesn't even make it a property of the object # http://code.djangoproject.com/ticket/11920 ...
java
@GwtIncompatible("incompatible method") public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) { return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)); }
python
def hdrval(cls): """Construct dictionary mapping display column title to IterationStats entries. """ dict = {'Itn': 'Iter'} dict.update(cls.hdrval_objfun) dict.update({'Rsdl': 'Rsdl', 'F': 'F_Btrack', 'Q': 'Q_Btrack', 'It_Bt': 'IterBTrack', 'L': 'L'}...
java
@XmlElementDecl(namespace = "http://schema.intuit.com/finance/v3", name = "Class", substitutionHeadNamespace = "http://schema.intuit.com/finance/v3", substitutionHeadName = "IntuitObject") public JAXBElement<Class> createClass(Class value) { return new JAXBElement<Class>(_Class_QNAME, Class.class, null, val...
java
@Override public void write(byte[] b, int off, int len) { this.checkIncreaseArray(len); System.arraycopy(b, off, this.buffer, this.pos, len); this.pos += len; }
java
public FileDeleteFromComputeNodeOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; }
python
def import_reference(self, ): """Import the currently loaded reference This will also update the status to :data:`Reftrack.IMPORTED`. :returns: None :rtype: None :raises: :class:`ReftrackIntegrityError` """ assert self.status() in (self.LOADED, self.UNLOADED),\ ...
python
def fuller_scaling(target, DABo, To, Po, temperature='pore.temperature', pressure='pore.pressure'): r""" Uses Fuller model to adjust a diffusion coefficient for gases from reference conditions to conditions of interest Parameters ---------- target : OpenPNM Object The...
java
public static IntBuffer stride(IntBuffer buffer) { int rank = rank(buffer); val buffer2 = (Buffer) buffer; val ret = (IntBuffer) buffer2.position(1 + rank); return ret.slice(); }
java
public static <K, V> Map<K, V> toMap(Iterator<? extends V> values, Function1<? super V, K> computeKeys) { if (computeKeys == null) throw new NullPointerException("computeKeys"); Map<K, V> result = Maps.newLinkedHashMap(); while(values.hasNext()) { V v = values.next(); result.put(computeKeys.apply(v), v);...
java
public static long count(int n, int m) { if(n == m) { return NumberUtil.factorial(n); } return (n > m) ? NumberUtil.factorial(n, n - m) : 0; }
java
public ResultMap getResultMap(Configuration configuration) { if (this.resultMap != null) { return this.resultMap; } if (entityClassColumns == null || entityClassColumns.size() == 0) { return null; } List<ResultMapping> resultMappings = new ArrayList<Result...
java
public void addExStrFeats(double weight, Object xObj, Object yObj, List<String>[] fvStrs) { FeatureVector[] fvs = new FeatureVector[fvStrs.length]; for (int i=0; i<fvs.length; i++) { fvs[i] = new FeatureVector(); for (String featName : fvStrs[i]) { fvs[i].add(feat...
python
def detail( self, participant1: Address, participant2: Address, block_identifier: BlockSpecification, channel_identifier: ChannelID = None, ) -> ChannelDetails: """ Returns a ChannelDetails instance with all the details of the channel a...
java
static void closeQuietly(ResultSet ps) { if (ps != null) { try { ps.getStatement().close(); // ps.close(); } catch (Exception e) { // Should go with the connection anyway. // j...
java
@Override public RTMPConnection removeConnection(String sessionId) { log.debug("Removing connection with session id: {}", sessionId); if (log.isTraceEnabled()) { log.trace("Connections ({}) at pre-remove: {}", connMap.size(), connMap.values()); } // remove from map ...
java
private boolean configUpdated() { try { URL url = ctx.getResource(resourcesDir + configResource); URLConnection con; if (url == null) return false ; con = url.openConnection(); long lastModified = con.getLastModified(); long XHP_LAST_MODIFI...
java
@Override public final String format(String key, ClassAnnotation primaryClass) { if ("class.givenClass".equals(key)) { return shorten(primaryClass.getPackageName(), className); } if ("simpleClass".equals(key)) { return ClassName.extractSimpleName(className); }...
java
public boolean bufferAckEnabled() { String bufSize = get(Names.CONNECTION_BUFFER_SIZE); return bufSize != null && Integer.parseInt(bufSize) > 0; }
java
public static Map<String,String> formatExportedVars( Instance instance ) { // The map we will return Map<String, String> exportedVars = new HashMap<> (); // Iterate over the instance and its ancestors. // There is no loop in parent relations, so no risk of conflict in variable names. for( Instance inst = in...
python
def connection(self): """Get a steady, cached PostgreSQL connection from the pool.""" if self._connections: if not self._connections.acquire(self._blocking): raise TooManyConnections try: con = self._cache.get(0) except Empty: con = sel...
java
public static void mark(Metrics metrics, String component, String methodName, String eventType) { if (metrics != null) { mark(metrics.getMeter(component, methodName, eventType)); } }
python
def pack_img(header, img, quality=95, img_fmt='.jpg'): """Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be ...
python
def _check_select(self): """ interactive mode of select tasks """ if not self.interactive: return super(OneScheduler, self)._check_select() # waiting for running tasks if self.running_task > 0: return is_crawled = [] def run(proj...
java
public synchronized boolean isLocalValuePresent(ConfigProperty configProperty) { checkArgument(configProperty != null, "Config property cannot be null"); String value = baseConfig.getString(configProperty.getName()); return value != null; }
python
def compare_and_set(self, expect, update): ''' Atomically sets the value to `update` if the current value is equal to `expect`. :param expect: The expected current value. :param update: The value to set if and only if `expect` equals the current value. ''' ...
java
public void writeFile(String filePath, byte[] data) throws IOException { Object lock = retrieveLock(filePath); synchronized (lock) { IO.writeFile(filePath, data); } }
python
def _encode_header(key: str, pdict: Dict[str, str]) -> str: """Inverse of _parse_header. >>> _encode_header('permessage-deflate', ... {'client_max_window_bits': 15, 'client_no_context_takeover': None}) 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover' """ if not pd...
python
def rename(self, new_name, database=None): """ Rename table inside MapD. References to the old table are no longer valid. Parameters ---------- new_name : string database : string Returns ------- renamed : MapDTable """ m ...
python
def print_results(args): """Print comics.""" min_comics, filename = args with codecs.open(filename, 'a', 'utf-8') as fp: for name, url in sorted(load_result(json_file).items()): if name in exclude_comics: continue if has_gocomics_comic(name): p...
java
public static void convert(String inFile, String outFile) throws IOException, org.nd4j.linalg.exception.ND4JIllegalStateException { SameDiff tg = TFGraphMapper.getInstance().importGraph(new File(inFile)); tg.asFlatFile(new File(outFile)); }
python
def update_particle(self, part, chi=0.729843788, c=2.05): """Constriction factor update particle method. Notes ----- Looks for a list of neighbours attached to a particle and uses the particle's best position and that of the best neighbour. """ neighbour_...
java
public static boolean createPath(File root, String relativePathToCreate) { File target = new File(root, relativePathToCreate); if (!target.exists()) { return target.mkdirs(); } else { return true; } }
python
def find_by_external_tracker(self, url, id_): """ Find a list of bugs by searching an external tracker URL and ID. param url: ``str``, the external ticket URL, eg "http://tracker.ceph.com". (Note this is the base URL.) param id_: ``str``, the external ticket ID, eg "1...
python
def mksls(src, dst=None): ''' Convert a kickstart file to an SLS file ''' mode = 'command' sls = {} ks_opts = {} with salt.utils.files.fopen(src, 'r') as fh_: for line in fh_: if line.startswith('#'): continue if mode == 'command': ...
java
public com.squareup.okhttp.Call postSamlConfigurationAsync(Boolean post, Boolean apply, Boolean delete, String action, String location, List<String> path, String serviceRanking, String idpUrl, String idpCertAlias, Boolean idpHttpRedirect, String serviceProviderEntityId, String assertionConsumerServiceURL, String spPriv...
python
def regions(self): """gets the regions value""" url = "%s/regions" % self.root params = {"f": "json"} return self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
java
public static <A> AnyGene<A> of( final A allele, final Supplier<? extends A> supplier, final Predicate<? super A> validator ) { return new AnyGene<>(allele, supplier, validator); }
java
public Void executeDDL(List<String> inputSql) throws SQLException { if (!getAutoCommit()) commit(); // Check for IF [NOT] EXISTS statements List<String> sql = getActualSql(inputSql); if (!sql.isEmpty()) { try { Operation<Void, UpdateDatabaseDdlMetadata> operation = ...
java
public void showRPN(final StringBuilder sb) throws Exception { for (final EquPart part : rpn) { sb.append(part.toString()); sb.append("\n"); } }
python
def overlay_boxes(self, image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `lab...
python
def template_to_dict_iter(item, debug=0): """ Returns infobox parsetree value using etree.iter() Preferred template_to_dict() algorithm, uses etree.iter() to iterate over elements, accumulating tail text in order, but not preserving `<ext>` tags (references, etc.). The advantage is that it pick...
python
def create_indication_data(msg_id, sequence_number, source_id, delta_time, \ protocol_ver): ''' Create a singled indication XML from the template and the included sequence_number, delta_time, and protocol_ver Returns the completed indication XML ''' data_template = "...
java
private Transaction onBegin() { Transaction tx; if (((StatelessSessionImpl) s).getTransactionCoordinator().isTransactionActive()) { tx = ((StatelessSessionImpl) s).getTransaction(); } else { tx = s.beginTransaction(); } return t...
python
def run(self): """ Runs all tasks in this runner on the executor. Blocks until all tasks have been completed. :return: """ for task in self.get_next_tasks(None): self.executor.add_task(task, None) while not self.executor.is_done(): done_tas...
java
public String getParameter(String name) { String[] p = getParameterMap().get(name); if (p != null) { return p[0]; } return null; }
python
def add(self, provider, front=False): """ Args: provider (ConfigProvider): Provider to add front (bool): If True, add provider to front of list """ if provider: i = self.provider_id_slot(provider) if i is not None: self.prov...
java
private void saveViolation(SensorContext sensorContext, CxxReportIssue issue) { NewIssue newIssue = sensorContext.newIssue().forRule(RuleKey.of(getRuleRepositoryKey(), issue.getRuleId())); Set<InputFile> affectedFiles = new HashSet<>(); List<NewIssueLocation> newIssueLocations = new ArrayList<>(); ...
java
public PagedList<DscConfigurationInner> listByAutomationAccount(final String resourceGroupName, final String automationAccountName, final String filter, final Integer skip, final Integer top, final String inlinecount) { ServiceResponse<Page<DscConfigurationInner>> response = listByAutomationAccountSinglePageAsy...
python
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._country is not None: return False if self._expiry_time is not None: return False return True
java
public ResumeAppStreamResponse resumeAppStream(String app, String stream) { ResumeAppStreamRequest request = new ResumeAppStreamRequest(); request.setApp(app); request.setStream(stream); return resumeAppStream(request); }
java
@Override public Group findGroup(String chainName, String pdbResnum, int modelnr) throws StructureException { // if structure is xray there will be only one "model". if ( modelnr > models.size()) throw new StructureException(" no model nr " + modelnr + " in this structure. (contains "+models.size()+")...
java
public static void validateSimonName(String name) { if (!checkName(name)) { throw new SimonException("Simon name must match following pattern: '" + SimonUtils.NAME_PATTERN.pattern() + "', used name: " + name); } }
python
def _sim_prediction_bayes(self, h, simulations): """ Simulates a h-step ahead mean prediction Parameters ---------- h : int How many steps ahead for the prediction simulations : int How many simulations to perform Returns ---------- ...
java
private Boolean isGoodCharacters(String data) { //PI57228 // if the last character is a CR or LF, then this fails int index = data.length() - 1; if (index < 0) { // empty string, quit now with success return true; } String error = null; char c = da...
python
def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1): """ plots the data at fixed x-value, so z vs x """ if simple=='auto': simple=self.simple # get the min and max if ymin=="auto": ...
java
public static nstimeout get(nitro_service service) throws Exception{ nstimeout obj = new nstimeout(); nstimeout[] response = (nstimeout[])obj.get_resources(service); return response[0]; }
java
public Pie center(Object width, Object height) { this.center = new Object[]{width, height}; return this; }
java
public void setSubjectPublicKey(byte[] key) throws IOException { if (key == null) { subjectPublicKey = null; subjectPublicKeyBytes = null; } else { subjectPublicKeyBytes = key.clone(); subjectPublicKey = X509Key.parse(new DerValue(subjectPublicKeyBytes)); ...
java
protected int checkMapping(final int articleID, final int revisionCounter) throws SQLException { PreparedStatement statement = null; ResultSet result = null; // Check for the correct revisionCounter mapping try { statement = this.connection.prepareStatement("SEL...
java
private static boolean shouldRetry(final int status, final String content) { switch (status) { case 200: return false; case 404: return analyse404Response(content); case 500: return analyse500Response(content); case ...
java
public IEntityGroupStore newInstance() throws GroupsException { try { return new RDBMEntityGroupStore(); } catch (Exception ex) { log.error("ReferenceEntityGroupStoreFactory.newInstance(): " + ex); throw new GroupsException(ex); } }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case XbasePackage.XFEATURE_CALL__FEATURE_CALL_ARGUMENTS: return featureCallArguments != null && !featureCallArguments.isEmpty(); case XbasePackage.XFEATURE_CALL__EXPLICIT_OPERATION_CALL: return explicitOperationCall != EXPLICIT_OP...
python
def get(cls, filename): """ Get the absolute path of a file added through C{SparkContext.addFile()}. """ path = os.path.join(SparkFiles.getRootDirectory(), filename) return os.path.abspath(path)
java
protected HttpHandler getHttpHandler() { // Use bean names so that we don't consider the hierarchy String[] beanNames = getBeanFactory().getBeanNamesForType(HttpHandler.class); if (beanNames.length == 0) { throw new ApplicationContextException( "Unable to start ReactiveWebApplicationContext due to missing...
java
public static <T, R, E extends Exception> R uncheck(FunctionWithExceptions<T, R, E> function, T t) { try { return function.apply(t); } catch (Exception exception) { throwAsUnchecked(exception); return null; } }
java
public void deleteShard(ApplicationDefinition appDef, String shard) { checkServiceState(); m_olap.deleteShard(appDef, shard); }
java
public static boolean isNumeric(String in) { char c = 0; for (int i = in.length(); i > 0; i--) { c = in.charAt(i - 1); if (!Character.isDigit(c)) { return false; } } return true; }
java
@Override public int compareTo(ValueArray<FloatValue> o) { FloatValueArray other = (FloatValueArray) o; int min = Math.min(position, other.position); for (int i = 0; i < min; i++) { int cmp = Float.compare(data[i], other.data[i]); if (cmp != 0) { return cmp; } } return Integer.compare(positio...
java
final private void fillCallerData(String callerFQCN, LogRecord record) { StackTraceElement[] steArray = new Throwable().getStackTrace(); int selfIndex = -1; for (int i = 0; i < steArray.length; i++) { final String className = steArray[i].getClassName(); if (classNa...
java
private XSpellChecker GetSpellChecker(XLinguServiceManager mxLinguSvcMgr) { try { if (mxLinguSvcMgr != null) { return mxLinguSvcMgr.getSpellChecker(); } } catch (Throwable t) { // If anything goes wrong, give the user a stack trace printMessage(t); } return null; }
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "contentStream", scope = CreateDocument.class) public JAXBElement<CmisContentStreamType> createCreateDocumentContentStream( CmisContentStreamType value) { return new JAXBElement<CmisContentStreamType>( _CreateDocume...
java
public static <C> C getProxy(final Class<C> configInterface) { return getProxy(configInterface, Optional.empty()); }
java
protected void returnToFreePool(MCWrapper mcWrapper) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(this, tc, "returnToFreePool", gConfigProps.cfName); } if (mcWrapper.shouldBeDestroyed() || mcWrapper.hasFatalErrorNotificationOccurred(fatalErrorNotifica...
python
def get_trend(self): """ Get the trend for the last two metric values using the interval defined in the metric :return: a tuple with the metric value for the last interval and the trend percentage between the last two intervals """ """ """ # TODO: We j...
java
public static JsonObject serialize(InstanceContext context) { return serialize(context.uri(), context.component().network()); }
java
@Nullable private DirectoryEntry lookUp( File dir, Iterable<Name> names, Set<? super LinkOption> options, int linkDepth) throws IOException { Iterator<Name> nameIterator = names.iterator(); Name name = nameIterator.next(); while (nameIterator.hasNext()) { Directory directory = toDirector...
python
def _compare_or_regex_search(a, b, regex=False): """ Compare two array_like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array_like or scalar ...
python
def parse(self, input, **kwargs): """Parse the given input. :param input: String containing the text to be parsed. :raises thriftrw.errors.ThriftParserError: For parsing errors. """ return self._parser.parse(input, lexer=self._lexer, **kwargs)
java
public void FinalizeContent( int lenPos ) { if (lenPos == Tag.Indefinite_Length) { this.write(0); this.write(0); } else { int length = this.pos - lenPos - 1; if (length <= 0x7F) { this.buffer[lenPos] = (byte) length; } else { int count; byte[] buf = new byte[4]; ...
python
def to(self, to): """ [Edge-only] especifica el destino del lado """ if self._type.lower() != 'edge': raise ValueError('Cannot set From/To to non-edge objects') self._to = to return self
python
def resolution_profile(self, graph, partition_type, resolution_range, weights=None, bisect_func=lambda p: p.bisect_value(), min_diff_bisect_value=1, min_diff_resolution=1e-3, linear_bisection=False, number_iterations=1, **kwargs ): ...
java
public static boolean isUsableLocalPort(int port) { if (false == isValidPort(port)) { // 给定的IP未在指定端口范围中 return false; } try { ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName(LOCAL_IP)).close(); return true; } catch (Exception e) { return false; } }
python
def html2groff(data, name): """Convert HTML text from cplusplus.com to Groff-formatted text.""" # Remove sidebar try: data = data[data.index('<div class="C_doc">'):] except ValueError: pass # Pre replace all for rp in pre_rps: data = re.compile(rp[0], rp[2]).sub(rp[1], d...
java
public static List<Entity> toEntities(com.google.appengine.api.datastore.Key parent, Object entity) { List<Entity> entities = new ArrayList<Entity>(); Class<?> clazz = entity.getClass(); if (!clazz.isAnnotationPresent(org.eiichiro.acidhouse.Entity.class)) { throw new IllegalArgumentException("Entity [" + cl...
python
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): """ Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected. """ if present: if not expected: raise exc_unexpected(*exc_args) ...
java
public Evaluator addGroupSubscriptions(String group, List<Subscription> subs) { List<Subscription> oldSubs = subscriptions.put(group, subs); if (oldSubs == null) { LOGGER.debug("added group {} with {} subscriptions", group, subs.size()); } else { LOGGER.debug("updated group {}, {} subscriptions ...
python
def cast(source, target): """Currently Literal to *Scalar implicit casts are allowed""" import ibis.expr.operations as ops # TODO: don't use ops here if not castable(source, target): raise com.IbisTypeError('Source is not castable to target type!') # currently it prevents column -> scalar imp...
java
protected Identifier newIdentifier() { while(true) { Identifier id = new Identifier(); boolean available; synchronized(sockets) { available = !sockets.containsKey(id); } if(available) { synchronized(idCheckers) { for(IdentifierAvailabilityChecker idChecker : idCheckers) { if(!idCheck...
java
public SIMPIterator getTransmitMessageIterator() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getTransmitMessageIterator"); // TODO : This method needs to throw a runtime invalid exception to comms SIMPIterator msgItr = null; try { msgItr = getQu...
java
public synchronized void waitOnIgnoringInterruptions() { if (tc.isEntryEnabled()) SibTr.entry(tc, "waitOnIgnoringInterruptions"); boolean interrupted; do { interrupted = false; try { waitOn(); } catch (InterruptedException e) ...
java
public static long[] xorI(long[] v, long[] o) { assert (o.length <= v.length) : "Bit set sizes do not agree."; for(int i = 0; i < o.length; i++) { v[i] ^= o[i]; } return v; }
java
public static PersistentDependency createDepend(PathImpl backing, long digest) { Jar jar = create(backing); return new JarDigestDepend(jar.getJarDepend(), digest); }
python
def get_pipeline_id(app='', name=''): """Get the ID for Pipeline _name_. Args: app (str): Name of Spinnaker Application to search. name (str): Name of Pipeline to get ID for. Returns: str: ID of specified Pipeline. None: Pipeline or Spinnaker Appliation not found. """ ...
java
public void addWeather(byte[] source) throws IOException { AceWeather weather = new AceWeather(source); String wstId = weather.getValue("wst_id"); String climId = weather.getValue("clim_id"); String wid = weather.getId(); if (this.weatherMap.containsKey(wid)) { LOG....