language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _raise_redirect_exceptions(response): """Return the new url or None if there are no redirects. Raise exceptions if appropriate. """ if response.status_code not in [301, 302, 307]: return None new_url = urljoin(response.url, response.headers['location']) if 'reddits/search' in new_u...
java
public static String appendParameters(String url, Map<String, String[]> params, boolean encode) { if (CmsStringUtil.isEmpty(url)) { return null; } if ((params == null) || params.isEmpty()) { return url; } int pos = url.indexOf(URL_DELIMITER); Stri...
python
def theta_str(theta, taustr=TAUSTR, fmtstr='{coeff:,.1f}{taustr}'): r""" Format theta so it is interpretable in base 10 Args: theta (float) angle in radians taustr (str): default 2pi Returns: str : theta_str - the angle in tau units Example1: >>> # ENABLE_DOCTEST ...
java
static MinimizedCondition unoptimized(Node n) { checkNotNull(n.getParent()); MeasuredNode pos = new MeasuredNode(n, null, 0, false); MeasuredNode neg = new MeasuredNode(null, null, Integer.MAX_VALUE, true); return new MinimizedCondition(pos, neg); }
python
def preprocess_frame(frame): """Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5] """ # Normalize from [0.0, 1.0] -> [-0.5, 0.5] frame = common_layers.convert_r...
python
def server(description=None, **kwargs): '''Create the :class:`.WSGIServer` running :func:`hello`.''' description = description or 'Pulsar Hello World Application' return wsgi.WSGIServer(hello, description=description, **kwargs)
python
def get_ast(token): """ Recursively unrolls token attributes into dictionaries (token.children into lists). Returns: a dictionary of token's attributes. """ node = {} # Python 3.6 uses [ordered dicts] [1]. # Put in 'type' entry first to make the final tree format somewhat # ...
java
public static boolean contains(LatLong[] latLongs, LatLong latLong) { boolean result = false; for (int i = 0, j = latLongs.length - 1; i < latLongs.length; j = i++) { if ((latLongs[i].latitude > latLong.latitude) != (latLongs[j].latitude > latLong.latitude) && (latLong.lo...
java
public JSONObject bodyTracking(byte[] image, String dynamic, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); String base64Content = Base64Util.encode(image); request.addBody("image", base64Content); request.addBod...
java
public static Evaluator definitionEvaluator( HandlerDefinition hda) { return definitionEvaluators.computeIfAbsent(hda.evaluator(), key -> { try { return hda.evaluator().getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException ...
python
def to_mongo(self, range_obj): """ takes the range object used for this chunker type and converts it into a string that can be use for a mongo query that filters by the range returns ------- dict """ if isinstance(range_obj, (pd.DatetimeIndex, tup...
java
static boolean remove(final Collection<?> c, final Object element) { if (N.isNullOrEmpty(c)) { return false; } return c.remove(element); }
python
def getRaDecRanges(self, numLines): """Pick suitable values for ra and dec ticks Used by plotGrid and labelAxes """ x1, x2, y1, y2 = mp.axis() ra0, dec0 = self.pixToSky(x1, y1) ra1, dec1 = self.pixToSky(x2, y2) #Deal with the case where ra range straddles 0. ...
java
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed //clear the existing values from the table DefaultTableModel model = (DefaultTableModel) rules.getModel(); model.setRowCount(0); //remove existing match rule...
python
def update_pipe_channel(self, uid, channel_name, label): # pylint: disable=unused-argument ''' Update this consumer to listen on channel_name for the js widget associated with uid ''' pipe_group_name = _form_pipe_channel_name(channel_name) if self.channel_layer: curr...
python
def _unique_ordered_lines(line_numbers): """ Given a list of line numbers, return a list in which each line number is included once and the lines are ordered sequentially. """ if len(line_numbers) == 0: return [] # Ensure lines are unique by putting them in ...
python
def ebic_select(self, gamma=0): """Uses Extended Bayesian Information Criteria for model selection. Can only be used in path mode (doesn't really make sense otherwise). See: Extended Bayesian Information Criteria for Gaussian Graphical Models R. Foygel and M. Drton NIPS...
python
def ssh_init_sec_context( self, target, desired_mech=None, username=None, recv_token=None ): """ Initialize a GSS-API context. :param str username: The name of the user who attempts to login :param str target: The hostname of the target to connect to :param str desir...
java
protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){ JRDesignExpression exp = new JRDesignExpression(); exp.setText("$V{" + var.getName() + "}"); exp.setValueClass(var.getValueClass()); return exp; }
java
public Section addCrosscuttingConceptsSection(SoftwareSystem softwareSystem, File... files) throws IOException { return addSection(softwareSystem, "Crosscutting Concepts", files); }
python
def add_plot_posterior_option_group(parser): """Adds the options needed to configure plots of posterior results. Parameters ---------- parser : object ArgumentParser instance. """ pgroup = parser.add_argument_group("Options for what plots to create and " ...
java
private static void removePrefixFromChildren(Element el, String prefix) throws MarshalException { NodeList nl = el.getChildNodes(); String localPrefix = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeType() != Node.ELEMENT_NODE) { continue; } localPrefix =...
python
def spin1_a(self): """Returns the dimensionless spin magnitude of mass 1.""" return coordinates.cartesian_to_spherical_rho( self.spin1x, self.spin1y, self.spin1z)
python
def text2text_distill_iterator(source_txt_path, target_txt_path, distill_txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of files.""" for inputs, targets, dist_targets in zip( txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path), ...
java
public static BeanMapping create(String mappingName) { BeanMappingObject config = BeanMappingConfigHelper.getInstance().getBeanMappingObject(mappingName); if (config == null) { throw new BeanMappingException("can not found mapping config for name[" + mappingName + "]"); } re...
java
private static Iterable<Action> validMovementsFor(List<Integer> state) { int emptyTile = state.indexOf(0); // array index which corresponds to the empty tile of the board switch(emptyTile){ // Ad-hoc computation of the available movements for a fixed 3x3 board. // NOTE: There ar...
python
def transform_deprecated_concepts(rdf, cs): """Transform deprecated concepts so they are in their own concept scheme.""" deprecated_concepts = [] for conc in rdf.subjects(RDF.type, SKOSEXT.DeprecatedConcept): rdf.add((conc, RDF.type, SKOS.Concept)) rdf.add((conc, OWL.deprecated, Litera...
java
public String encodeAuthAmqPlain(String username, String password) { AmqpBuffer bytes = new AmqpBuffer(); bytes.putShortString("LOGIN"); bytes.putTypeIdentifier("Longstr"); bytes.putLongString(username); bytes.putShortString("PASSWORD"); bytes.putTypeIdentifi...
python
def _rolling_window(a, window, axis=-1): """ Make an ndarray with a rolling window along axis. Parameters ---------- a : array_like Array to add rolling window to axis: int axis position along which rolling window will be applied. window : int Size of rolling window ...
java
public List<DSLMappingEntry> getEntries(final DSLMappingEntry.Section section) { final List<DSLMappingEntry> list = new LinkedList<DSLMappingEntry>(); for ( final Iterator<DSLMappingEntry> it = this.entries.iterator(); it.hasNext(); ) { final DSLMappingEntry entry = it.next(); if...
java
public ServiceFuture<AzureReachabilityReportInner> beginGetAzureReachabilityReportAsync(String resourceGroupName, String networkWatcherName, AzureReachabilityReportParameters parameters, final ServiceCallback<AzureReachabilityReportInner> serviceCallback) { return ServiceFuture.fromResponse(beginGetAzureReachab...
java
void invalidateToStringCache() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "invalidateToStringCache"); // Invalidate the toString cache. cachedToString = null; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) ...
java
public static CPOptionCategory findByGroupId_First(long groupId, OrderByComparator<CPOptionCategory> orderByComparator) throws com.liferay.commerce.product.exception.NoSuchCPOptionCategoryException { return getPersistence().findByGroupId_First(groupId, orderByComparator); }
java
public Waiter<DescribeExportTasksRequest> exportTaskCancelled() { return new WaiterBuilder<DescribeExportTasksRequest, DescribeExportTasksResult>().withSdkFunction(new DescribeExportTasksFunction(client)) .withAcceptors(new ExportTaskCancelled.IsCancelledMatcher()) .withDefaultP...
java
private void readCalendar(Calendar calendar) { ProjectCalendar mpxjCalendar = m_projectFile.addCalendar(); mpxjCalendar.setName(calendar.getName()); m_calendarMap.put(calendar.getID(), mpxjCalendar); for (WeekDay day : calendar.getWeekDays().getWeekDay()) { readWeekDay(mpxjCal...
python
def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """Iterable to get every convolution window per loop iteration. For example: `convolved([1, 2, 3, 4], kernel_size=2)` will produce the following result: `[[1, 2], [2, 3], [3, 4]]`. `convolve...
python
def _escape(value): """Escape a string (key or value) for InfluxDB's line protocol. :param str|int|float|bool value: The value to be escaped :rtype: str """ value = str(value) for char, escaped in {' ': '\ ', ',': '\,', '"': '\"'}.items(): value = value.repl...
java
private void writeQuotedAndEscaped(CharSequence string) { if (string != null && string.length() != 0) { int len = string.length(); writer.write('\"'); for (int i = 0; i < len; ++i) { char cp = string.charAt(i); if ((cp < 0x7f && ...
java
public void dropTable(String tblName, Transaction tx) { // Remove the file RecordFile rf = getTableInfo(tblName, tx).open(tx, true); rf.remove(); // Optimization: remove from the TableInfo map tiMap.remove(tblName); // remove the record from tblcat RecordFile tcatfile = tcatInfo.open(tx, true);...
python
def StartKvmSession(self, serviceProfile=None, blade=None, rackUnit=None, frameTitle=None, dumpXml=None): """ Starts KVM session. launches the KVM session for the specific service profile, blade or rackUnit. - serviceProfile specifies an object of type lsServer. Launches KVM session with which the service pr...
java
public List<CmsSiteMatcher> getAllMatchers() { List<CmsSiteMatcher> result = Lists.newArrayList(); switch (getSSLMode()) { case LETS_ENCRYPT: case MANUAL_EP_TERMINATION: List<CmsSiteMatcher> baseMatchers = Lists.newArrayList(); baseMatchers.add(m_...
java
public static void setPreferencesHandler(Object target, Method prefsHandler) { boolean enablePrefsMenu = (target != null && prefsHandler != null); if (enablePrefsMenu) { setHandler(new OSXAdapter("handlePreferences", target, prefsHandler)); } // If we're setting a handler, en...
python
def set_led(self, led, action=None, cabinet=Required, frame=Required, board=Required): """Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this...
python
def append_allow_trust_op(self, trustor, asset_code, authorize, source=None): """Append an :class:`AllowTrust <stellar_base.operation.AllowTrust>` operation to the list of operations. ...
python
def trunk_section_lengths(nrn, neurite_type=NeuriteType.all): '''list of lengths of trunk sections of neurites in a neuron''' neurite_filter = is_type(neurite_type) return [morphmath.section_length(s.root_node.points) for s in nrn.neurites if neurite_filter(s)]
python
def expressions(self): """ list(Expression): List of the expressions """ if self._expressions is None: expressions = [n.expression for n in self.nodes] expressions = [e for e in expressions if e] self._expressions = expressions return self....
java
protected static List<CentroidMapping> calculateDistances(double[][] baseCentroids, double[][] targetCentroids, int centroidNum) { // ベース中心点配列とマージ対象中心点配列の各々のユークリッド距離を算出 List<CentroidMapping> allDistance = new ArrayList<>(); for (int baseIndex = 0; baseIndex < centroidNum; baseIn...
java
public static <K,V> Cache<K,V> newSoftMemoryCache(int size) { return new MemoryCache<>(true, size); }
python
def create_pep_protein_quant_lookup(fns, pqdb, poolnames, featcolnr, patterns, storefuns, isobqcolpattern=None, psmnrpattern=None): """Does the work when creating peptide and protein quant lookups. This loops through storing options and par...
java
public static List<File> createTiffFiles(File imageFile, int index) throws IOException { return createTiffFiles(imageFile, index, false); }
java
@Override protected Asset readJson(final String assetId) throws IOException, BadVersionException { FileInputStream fis = null; try { fis = DirectoryUtils.createFileInputStream(createFromRelative(assetId + ".json")); Asset ass = processJSON(fis); return ass; ...
python
def _get_db_table(self, data_path, extension): """ Query a database and return query result as a recarray Parameters ---------- data_path : str Path to the database file extension : str Type of database, either sql or db Returns -...
python
def write (stream_or_path, holders, **kwargs): """Very simple writing in ini format. The simple stringification of each value in each Holder is printed, and no escaping is performed. (This is most relevant for multiline values or ones containing pound signs.) `None` values are skipped. Arguments: ...
java
public static boolean endsWith(CharSequence s, String end) { return (s.length() >= end.length() && s.subSequence(s.length() - end.length(), s.length()).equals(end)); }
python
def simulate_source(self, src_dict=None): """ Inject simulated source counts into the data. Parameters ---------- src_dict : dict Dictionary defining the spatial and spectral properties of the source that will be injected. """ self._fitcac...
java
public void addExceptionHandler(Block block, String handler, List<? extends TypeMirror> thrownTypes) { Label label = getLabel(handler); if (!thrownTypes.isEmpty()) { for (TypeMirror thrownType : thrownTypes) { exceptionTableList.add(new Exceptio...
java
protected final ByteBuf copyAndCompose(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf next) { ByteBuf newCumulation = alloc.ioBuffer(cumulation.readableBytes() + next.readableBytes()); try { newCumulation.writeBytes(cumulation).writeBytes(next); } catch (Throwable cause) { ...
python
def rm_hard_link(self, iso_path=None, joliet_path=None, udf_path=None): # type: (Optional[str], Optional[str], Optional[str]) -> None ''' Remove a hard link from the ISO. If the number of links to a piece of data drops to zero, then the contents will be removed from the ISO. Thu...
python
def mousePressEvent(self, event): """ Creates the mouse event for dragging or activating this tab. :param event | <QtCore.QMousePressEvent> """ self._moveItemStarted = False rect = QtCore.QRect(0, 0, 12, self.height()) # drag the tab off if not self...
python
def _extract_storage_api_response_error(message): """ A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the messag...
java
public static void copy(Reader r, Writer w, boolean close) throws IOException { char[] buf = new char[DEFAULT_BUFFER_SIZE]; int len; try { while ((len = r.read(buf)) != -1) { w.write(buf, 0, len); } } finally { if (close) { ...
python
def list(self, date_created_before=values.unset, date_created=values.unset, date_created_after=values.unset, limit=None, page_size=None): """ Lists MediaInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memor...
java
public Observable<Page<DomainInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<DomainInner>>, Page<DomainInner>>() { @Override public Page<DomainInner> call(ServiceResponse<Page...
java
private boolean isPacketLongEnough(DatagramPacket packet, int expectedLength, String name) { final int length = packet.getLength(); if (length < expectedLength) { logger.warn("Ignoring too-short " + name + " packet; expecting " + expectedLength + " bytes and got " + lengt...
python
def count_matrix(self): # TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data? """Compute the transition count matrix from hidden state trajectory. Returns ------- C : numpy.array with shape (nstates,nstates) C[i,j] is the nu...
python
def get_inner_data(dictionary): """Gets 2nd-level data into 1st-level dictionary :param dictionary: dict :return: with 2nd-level data """ out = {} for key in dictionary.keys(): inner_keys = dictionary[key].keys() for inner_key in inner_keys: new_key = key + " " + i...
python
def monitor(args, watch): """ reloads the script given by argv when src files changes """ watch = watch if isinstance(watch, (list, tuple)) else [watch] watch = [Path(entry).expand().abspath() for entry in watch] event_handler = RunScriptChangeHandler(args) observer = Observer() for entr...
python
def get_min_instability(self, min_voltage=None, max_voltage=None): """ The minimum instability along a path for a specific voltage range. Args: min_voltage: The minimum allowable voltage. max_voltage: The maximum allowable voltage. Returns: Minimum d...
python
def dp990(self, value=None): """ Corresponds to IDD Field `dp990` Dew-point temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `dp990` Unit: C if `value` is ...
java
public ServiceFuture<PacketCaptureResultInner> getAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, final ServiceCallback<PacketCaptureResultInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCap...
java
private Description doUnboxingCheck(VisitorState state, ExpressionTree... expressions) { for (ExpressionTree tree : expressions) { Type type = ASTHelpers.getType(tree); if (type == null) { throw new RuntimeException("was not expecting null type"); } if (!type.isPrimitive()) { ...
java
public static LocalDateIterable createLocalDateIterable( String rdata, LocalDate start, DateTimeZone tzid, boolean strict) throws ParseException { return new RecurrenceIterableWrapper( RecurrenceIteratorFactory.createRecurrenceIterable( rdata, loca...
java
public boolean columnValueIsBinary(String namespace, String storeName) { Boolean cachedValue = getCachedValueIsBinary(namespace, storeName); if(cachedValue != null) return cachedValue.booleanValue(); String cqlKeyspace = CQLService.storeToCQLName(namespace); String tableName = C...
java
public Matrix4d reflection(double a, double b, double c, double d) { double da = a + a, db = b + b, dc = c + c, dd = d + d; m00 = 1.0 - da * a; m01 = -da * b; m02 = -da * c; m03 = 0.0; m10 = -db * a; m11 = 1.0 - db * b; m12 = -db * c; m13 = 0.0; ...
python
def save_image(xdata: DataAndMetadata.DataAndMetadata, file): """ Saves the nparray data to the file-like object (or string) file. """ # we need to create a basic DM tree suitable for an image # we'll try the minimum: just an data list # doesn't work. Do we need a ImageSourceList too? # and ...
java
@NonNull private synchronized CrashReportData legacyLoad(@NonNull Reader reader) throws IOException { int mode = NONE, unicode = 0, count = 0; char nextChar; char[] buf = new char[40]; int offset = 0, keyLength = -1, intVal; boolean firstChar = true; final CrashRepor...
python
def get_last(self, n=1): """ Retrieve the last n rows from the table :param n: number of rows to return :return: list of rows """ rows = [] # Get values from the partial db first if self.tracker.dbcon_part and check_table_exists(self.tracker.dbcon_part, se...
java
public List<List<List<Writable>>> executeToSequenceBatch(List<List<Writable>> inputExample){ List<List<List<Writable>>> ret = new ArrayList<>(); for(List<Writable> record : inputExample) ret.add(execute(record, null).getRight()); return ret; }
java
private static BinaryMemcacheRequest handleKeepAliveRequest(KeepAliveRequest msg) { BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(); request .setOpcode(OP_NOOP) .setKeyLength((short) 0) .setExtras(Unpooled.EMPTY_BUFFER) ....
java
public EClass getIfcCoordinatedUniversalTimeOffset() { if (ifcCoordinatedUniversalTimeOffsetEClass == null) { ifcCoordinatedUniversalTimeOffsetEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(121); } return ifcCoordinatedUniversalTimeOffsetECla...
java
public ServiceFuture<VirtualNetworkInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualNetworkName, VirtualNetworkInner parameters, final ServiceCallback<VirtualNetworkInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, v...
java
public static LongBinding floorDiv(final ObservableLongValue x, final long y) { return createLongBinding(() -> Math.floorDiv(x.get(), y), x); }
java
public FessMessages addConstraintsTypeFloatMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeFloat_MESSAGE)); return this; }
java
@Override public int write(ByteBuffer src) { int toTransfer = Math.min(src.remaining(), data.length - offset); src.get(data, offset, toTransfer); offset += toTransfer; return toTransfer; }
python
def addValue(self, source, value): """Adds a value from the given source.""" if self.source is None or self.fn(self.value, value): self.value = value self.source = source
java
@Override public CPDefinitionSpecificationOptionValue findByCPDefinitionId_Last( long CPDefinitionId, OrderByComparator<CPDefinitionSpecificationOptionValue> orderByComparator) throws NoSuchCPDefinitionSpecificationOptionValueException { CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValue...
java
private void logMigration(DbMigration migration, boolean wasSuccessful) { BoundStatement boundStatement = logMigrationStatement.bind(wasSuccessful, migration.getVersion(), migration.getScriptName(), migration.getMigrationScript(), new Date()); session.execute(boundStatement); }
python
def feed(self, key_press): """ Add a new :class:`KeyPress` to the input queue. (Don't forget to call `process_keys` in order to process the queue.) """ assert isinstance(key_press, KeyPress) self.input_queue.append(key_press)
java
protected void authenticateConnection (AuthingConnection conn) { Authenticator author = _author; for (ChainedAuthenticator cauthor : _authors) { if (cauthor.shouldHandleConnection(conn)) { author = cauthor; break; } } author.au...
python
def createCategoryFilter(self, retina_name, filter_name, body, ): """get filter for classifier Args: filter_name, str: A unique name for the filter. (required) body, FilterTrainingObject: The list of positive and negative (optional) example items. (required) retina_na...
java
public void setSystem(ParticleSystem system) { this.system = system; emitters.clear(); system.setRemoveCompletedEmitters(false); for (int i = 0; i < system.getEmitterCount(); i++) { emitters.add(system.getEmitter(i)); } }
java
public void sendRequestToWc(FramePPHeaders frame) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "H2StreamProcessor.sendRequestToWc()"); } if (null == frame) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { ...
java
public void setActivate(RuleProxyField ruleProxyField, RuleContext ruleContext) { if (ruleProxyField.isInActive()) // only do it if the field changes { m_activateFields.add(ruleProxyField.getProxyField()); ruleContext.addActivate(ruleProxyField); } }
java
protected byte[] BuildNewIndex(int[] Offsets,HashMap Used,byte OperatorForUnusedEntries) throws IOException { int unusedCount = 0; int Offset=0; int[] NewOffsets = new int[Offsets.length]; // Build the Offsets Array for the Subset for (int i=0;i<Offsets.length;++i) { NewOffsets[i] = Offset; // If th...
python
def main(func=None, argv=None, input_stream=stdin, output_stream=stdout, error_stream=stderr, exit=True): """runs a function as a command. runs a function as a command - reading input from `input_stream`, writing output into `output_stream` and providing arguments from `argv`. Example Usage: ...
python
def verify_selenium_server_is_running(self): """ Start the Selenium standalone server, if it isn't already running. Returns a tuple of two elements: * A boolean which is True if the server is now running * The Popen object representing the process so it can be terminated ...
python
def main(self, din): """ :param din: bit in :return: True if 100% correlation """ self.shr = self.shr[1:] + [din] if self.cooldown > 0: self.cooldown = self.cooldown - 1 return False if self.shr != self.HEADER: return False ...
python
def _import_submodules(package_name): """ Import all submodules of a module, recursively Adapted from: http://stackoverflow.com/a/25083161 :param package_name: Package name :type package_name: str :rtype: dict[types.ModuleType] """ package = sys.modules[package_name] out = {} for lo...
python
def sphinxify(docstring, context, buildername='html'): """ Runs Sphinx on a docstring and outputs the processed documentation. Parameters ---------- docstring : str a ReST-formatted docstring context : dict Variables to be passed to the layout template to control how its ...
python
def do_list_organizations(self, line): '''Get list of organization on DCNM.''' org_list = self.dcnm_client.list_organizations() if not org_list: print('No organization found.') return org_table = PrettyTable(['Organization Name']) for org in org_list: ...