language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected GenericDataSourceBase<OUT, ?> translateToDataFlow() { String name = this.name != null ? this.name : this.inputFormat.toString(); if (name.length() > 100) { name = name.substring(0, 100); } @SuppressWarnings({ "unchecked", "rawtypes" }) GenericDataSourceBase<OUT, ?> source = new GenericDataSour...
java
public static String paceFormat(final Number value, final TimeMillis interval) { return paceFormat(value, interval.millis()); }
java
public Observable<EntityRole> getEntityRoleAsync(UUID appId, String versionId, UUID entityId, UUID roleId) { return getEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).map(new Func1<ServiceResponse<EntityRole>, EntityRole>() { @Override public EntityRole call(Servic...
java
private Section parseSection(boolean mediaQuery) { Section section = new Section(); parseSectionSelector(mediaQuery, section); tokenizer.consumeExpectedSymbol("{"); while (tokenizer.more()) { if (tokenizer.current().isSymbol("}")) { tokenizer.consumeExpectedSy...
java
protected com.sun.jersey.api.client.Client getJerseyClient() { final ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(clientConfig); ...
python
def set_default_reference(self, method, reference): """ Set the default reference for a method. :arg method: name of a method :type method: :class:`str` {reference} """ if method not in self._available_methods: raise ValueError('Unknown method: {0}'....
python
def process_commmon(self): ''' Some data processing common for all services. No need to override this. ''' data = self.data data_content = data['content'][0] ## Paste the output of a command # This is deprecated after piping support if data['comma...
java
public void setDesiredWeightsAndCapacities(java.util.Collection<DesiredWeightAndCapacity> desiredWeightsAndCapacities) { if (desiredWeightsAndCapacities == null) { this.desiredWeightsAndCapacities = null; return; } this.desiredWeightsAndCapacities = new java.util.ArrayLi...
python
def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr): """ Link atoms (AIL expressions) in the given expression to corresponding variables identified previously. :param variable_manager: Variable manager of the function. :param ailment.Block block: AIL bloc...
python
def query_instance(vm_=None, call=None): ''' Query an instance upon creation from the Joyent API ''' if isinstance(vm_, six.string_types) and call == 'action': vm_ = {'name': vm_, 'provider': 'joyent'} if call == 'function': # Technically this function may be called other ways too, ...
java
protected WebElement getFirstElement(Elements elems) { DocumentWebElement documentWebElement = Iterables.getFirst(elems.as(InternalWebElements.class).wrappedNativeElements(), null); return documentWebElement == null ? null : documentWebElement.getWrappedWebElement(); }
python
def toPlanarPotential(Pot): """ NAME: toPlanarPotential PURPOSE: convert an Potential to a planarPotential in the mid-plane (z=0) INPUT: Pot - Potential instance or list of such instances (existing planarPotential instances are just copied to the output) OUTPUT: pl...
java
public void trace(Object message, Throwable t) { differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, t); }
python
def _render_conditions(conditions): """Render the conditions part of a query. Parameters ---------- conditions : list A list of dictionary items to filter a table. Returns ------- str A string that represents the "where" part of a query See Also -------- render...
java
public String createRunner(Vector<Object> runnerParams) { try { Runner runner = XmlRpcDataMarshaller.toRunner(runnerParams); service.createRunner(runner); log.debug( "Created Runner: " + runner.getName() ); return SUCCESS; } catch (Exception e...
java
@Override public Model read(Configuration config) { String name = config.getName(); Descriptor desc = getDescriptor(); if (IMPLEMENTATION_RULES.equals(name)) { return new V1RulesComponentImplementationModel(config, desc); } else if (OPERATION.equals(name)) { r...
java
@Deprecated public static final StyleSheet parse(String css) throws IOException, CSSException { URL base = new URL("file:///base/url/is/not/specified"); //Cannot determine the base URI in this method but we need some base URI for relative URLs return getCSSParserFactory().parse(css, getNetworkProcessor(), ...
python
def maybe_curry(maybe_fn, first_arg) -> 'Function | Any': """ If maybe_fn is a function, curries it and passes in first_arg. Otherwise returns maybe_fn. """ if not callable(maybe_fn): return maybe_fn return tz.curry(maybe_fn)(first_arg)
java
private List<CollectionJsonData> determineQueryProperties() { if (!getHttpMethod().equals(HttpMethod.GET)) { return Collections.emptyList(); } return getQueryMethodParameters().stream() // .map(queryProperty -> new CollectionJsonData() // .withName(queryProperty.getName()) // .withValue("")) ...
java
public static <T extends Number & Comparable<?>> NumberExpression<T> asNumber(T value) { return asNumber(constant(value)); }
java
private Node createBootstrapField(String fieldName, String labelText, Element input, boolean showError) { Validate.notNull(input, "You must define an input-element."); Validate.notNull(fieldName, "You must define a fieldName."); LOG.trace("Creating Bootstrap field with fieldname = '{...
python
def api_retrieve(self, api_key=None): """ Call the stripe API's retrieve operation for this model. :param api_key: The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY. :type api_key: string """ api_key = api_key or self.default_api_key return self.stripe_class.retrieve( id=sel...
java
@Override public void schema(Class<?> type) { Objects.requireNonNull(type); _context.schema(type); }
java
public static DescriptorExtensionList<CaptchaSupport, Descriptor<CaptchaSupport>> all() { return Jenkins.getInstance().<CaptchaSupport, Descriptor<CaptchaSupport>>getDescriptorList(CaptchaSupport.class); }
java
protected static void destroyProcess(String pid, long sleeptimeBeforeSigkill, boolean inBackground) { terminateProcess(pid); sigKill(pid, false, sleeptimeBeforeSigkill, inBackground); }
python
def create(provider, count=1, name=None, **kwargs): r''' Create one or more cloud servers Args: * provider (str): Cloud provider, e.g. ec2, digitalocean * count (int) =1: Number of instances * name (str) =None: Name of server(s) * \**kwargs: Provider-specific flags ''' ...
java
public Object set(int index, Object element) { if ((index < m_iStartIndex) || (index >= m_iStartIndex + m_iMaxSize)) { // Out of bounds, re-adjust bounds int iNewStart = index - m_iMaxSize / 2; // index should be right in the middle if (iNewStart < 0) iNewSt...
java
public void actionDelete() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); try { getCms().deletePropertyDefinition(getParamPropertyName()); ...
python
def insert_right(self, item): 'Insert a new item. If equal keys are found, add to the right' k = self._key(item) i = bisect_right(self._keys, k) self._keys.insert(i, k) self._items.insert(i, item)
java
public final List<DataSlice> flatten(Object store) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "flatten"); List<DataSlice> slices = null; // d395685 try { ...
python
def mission_request_send(self, target_system, target_component, seq, force_mavlink1=False): ''' Request the information of the mission item with the sequence number seq. The response of the system to this message should be a MISSION_ITEM message. ...
java
@SuppressWarnings("unchecked") private static Deserializer<?> getDeserializer(Configuration conf) { String deserializerClassName = conf.get(HBaseBackfillMerger.CONFKEY_DESERIALIZER); if (deserializerClassName == null) { throw new RuntimeException("Configuration didn't set " + deserialize...
java
private void fireNewCurrentSolution(SolutionType newCurrentSolution, Evaluation newCurrentSolutionEvaluation, Validation newCurrentSolutionValidation){ for(SearchListener<? super SolutionType> l : getSearchListeners()){ ...
java
public static <T> List<T> take(List<T> self, int num) { return (List<T>) take((Iterable<T>)self, num); }
python
def _load_prev(self): """Load the next days data (or file) without decrementing the date. Repeated calls will not decrement date/file and will produce the same data Uses info stored in object to either decrement the date, or the file. Looks for self._load_by_date flag. ...
java
@Override public double getValue(double quantile) { if (quantile < 0.0 || quantile > 1.0 || Double.isNaN( quantile )) { throw new IllegalArgumentException(quantile + " is not in [0..1]"); } if (values.length == 0) { return 0.0; } int posx = Arrays.bi...
python
def public_ip_addresses_list(resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all public IP addresses within a resource group. :param resource_group: The resource group name to list public IP addresses within. CLI Example: .. code-block:: bash salt-call azurear...
python
def igmpize(self, ip=None, ether=None): """Called to explicitely fixup associated IP and Ethernet headers Parameters: self The instantiation of an IGMP class. ip The instantiation of the associated IP class. ether The instantiation of the associated Ethernet. Returns: Tru...
python
def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. ...
python
def main(): """ NAME apwp.py DESCRIPTION returns predicted paleolatitudes, directions and pole latitude/longitude from apparent polar wander paths of Besse and Courtillot (2002). SYNTAX apwp.py [command line options][< filename] OPTIONS -h prints help messa...
java
@SuppressWarnings("unchecked") @Override public T param(final String paramName, final Supplier<Object> supplier) { context().param(paramName, supplier); return (T) this; }
python
def zernike(zernike_indexes,labels,indexes): """Compute the Zernike features for the labels with the label #s in indexes returns the score per labels and an array of one image per zernike feature """ # # "Reverse_indexes" is -1 if a label # is not to be processed. Otherwise # reverse_index[...
java
protected void pushToGrid(OpDescriptor descriptor, boolean flush) { // we should just add op to queue here //deviceQueues.get().add(descriptor); // FIXME: following code should be removed, since it's just executing supers instead of batching execCounter.incrementAndGet(); Op ...
java
protected Parser parser(Key jobKey) { ParserProvider pp = ParserService.INSTANCE.getByInfo(_parse_type); if (pp != null) { return pp.createParser(this, jobKey); } throw new H2OIllegalArgumentException("Unknown file type. Parse cannot be completed.", "Attempted to invoke a parser for Pa...
python
def includes(self): """Return all of the include directories for this chip as a list.""" incs = self.combined_properties('includes') processed_incs = [] for prop in incs: if isinstance(prop, str): processed_incs.append(prop) else: ...
java
public void setDateAttribute(String name, Date value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof DateAttribute)) { throw new IllegalStateException("Cannot set date value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ...
java
public <T> T get(URI uri, Class<T> classType) { HttpConnection connection = Http.GET(uri); InputStream response = executeToInputStream(connection); try { return getResponse(response, classType, getGson()); } finally { close(response); } }
java
public static EndpointCaller initializeEndpointCaller(Properties properties) { EndpointCaller ec; try { LOG.debug("Initializing endpoint caller. Checking whether '{}' is in classpath.", TRACING_ENDPOINT_CALLER_CLASSNAME); Class<?> tracingEndpointCallerClass = ...
python
def log(ctx, archive_name): ''' Get the version log for an archive ''' _generate_api(ctx) ctx.obj.api.get_archive(archive_name).log()
python
def _get(self, pos): """loads widget at given position; handling invalid arguments""" res = None, None if pos is not None: try: res = self[pos], pos except (IndexError, KeyError): pass return res
java
public static boolean shouldRaid(Configuration conf, FileSystem srcFs, FileStatus stat, Codec codec, List<FileStatus> lfs) throws IOException { Path p = stat.getPath(); long blockNum = 0L; if (stat.isDir() != codec.isDirRaid) { return false; } if (tooNewForRaid(stat)) { retur...
python
def threshold(requestContext, value, label=None, color=None): """ Takes a float F, followed by a label (in double quotes) and a color. (See ``bgcolor`` in the render\_api_ for valid color names & formats.) Draws a horizontal line at value F across the graph. Example:: &target=threshold(12...
python
def create_textfile_with_contents(filename, contents, encoding='utf-8'): """ Creates a textual file with the provided contents in the workdir. Overwrites an existing file. """ ensure_directory_exists(os.path.dirname(filename)) if os.path.exists(filename): os.remove(filename) outstrea...
java
@Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case BpsimPackage.BETA_DISTRIBUTION_TYPE: return createBetaDistributionType(); case BpsimPackage.BINOMIAL_DISTRIBUTION_TYPE: return createBinomialDistributionType(); case BpsimPackage.BOOLEAN_PARAMETER_TYPE: return createBo...
python
def match(self, category, pattern): """Match the category.""" return fnmatch.fnmatch(category, pattern, flags=self.FNMATCH_FLAGS)
java
public DependencyCustomizer ifAnyMissingClasses(String... classNames) { return new DependencyCustomizer(this) { @Override protected boolean canAdd() { for (String className : classNames) { try { DependencyCustomizer.this.loader.loadClass(className); } catch (Exception ex) { return...
java
protected Object doInvoke(Object... args) throws Exception { ReflectionUtils.makeAccessible(getBridgedMethod()); try { return getBridgedMethod().invoke(getBean(), args); } catch (IllegalArgumentException ex) { assertTargetBean(getBridgedMethod(), getBean(), args); throw new IllegalStateException( ...
python
def view_dupl_sources(token, dstore): """ Show the sources with the same ID and the truly duplicated sources """ fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures'] dic = group_array(dstore['source_info'].value[fields], 'source_id') sameid = [] dupl = [] for source_id, group...
python
def _missing_(cls, value): """Lookup function used when value is not found.""" if not (isinstance(value, int) and 0 <= value <= 1): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) extend_enum(cls, 'Unassigned [%d]' % value, value) return cls(value) su...
python
def extend(self, other: Operation) -> None: """Append gates from circuit to the end of this circuit""" if isinstance(other, Circuit): self.elements.extend(other.elements) else: self.elements.extend([other])
java
public static void calculateCoverate(Path bamPath, Path sqlPath) throws IOException, AlignmentCoverageException { BamManager bamManager = new BamManager(bamPath); // Check if the bam index (.bai) does not exit, then create it if (!bamPath.getParent().resolve(bamPath.getFileName().toString() + "...
python
def print_diskinfo(diskinfo, widelayout, incolor): ''' Disk information output function. ''' sep = ' ' if opts.relative: import math base = max([ disk.ocap for disk in diskinfo ]) for disk in diskinfo: if disk.ismntd: ico = _diskico else: ico = _unmnico...
java
private void generatePartialMatch() { partialMatch = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) { j = partialMatch[j - 1]; } if (pattern[j] == pattern[i]) { ...
java
private void encodeFooter(final FacesContext context, final ResponseWriter responseWriter, final Sheet sheet) throws IOException { // footer final UIComponent footer = sheet.getFacet("footer"); if (footer != null) { responseWriter.startElement("div", null); ...
python
def coerce_quotes(quotes): """Coerce a quote type into an acceptable value, or raise an error.""" orig, quotes = quotes, str(quotes) if quotes else None if quotes not in [None, '"', "'"]: raise ValueError("{!r} is not a valid quote type".format(orig)) return quotes
java
private ClassDescriptor[] getMultiJoinedClassDescriptors(ClassDescriptor cld) { DescriptorRepository repository = cld.getRepository(); Class[] multiJoinedClasses = repository.getSubClassesMultipleJoinedTables(cld, true); ClassDescriptor[] result = new ClassDescriptor[multiJoinedClasses.l...
python
def find_files_for_tar(self, context, silent_build): """ Return [(filename, arcname), ...] for all the files. """ if not context.enabled: return files = self.find_files(context, silent_build) for path in files: relname = os.path.relpath(path, con...
python
def get_book_ids_by_comment(self, comment_id): """Gets the list of ``Book`` ``Ids`` mapped to a ``Comment``. arg: comment_id (osid.id.Id): ``Id`` of a ``Comment`` return: (osid.id.IdList) - list of book ``Ids`` raise: NotFound - ``comment_id`` is not found raise: NullArgum...
python
def get_config_from_env(cls): """ .. deprecated:: 2.5.3 Gets configuration out of environment. Returns list of dicts - list of namenode representations """ core_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'core-site.xml') core_configs = cls.read_core_c...
java
private void isparentlogger(Logger logchannel) { // get all log channels List<Logger> referenz = getLoggers(); Iterator<Logger> it_logger = referenz.iterator(); while (it_logger.hasNext()) { Logger child_test = it_logger.next(); // if the logchannel has th...
java
public static TimeOfDay fromMillisOfDay(long millisOfDay, Chronology chrono) { chrono = DateTimeUtils.getChronology(chrono); chrono = chrono.withUTC(); return new TimeOfDay(millisOfDay, chrono); }
java
protected MailtoModel newMailtoModel(final Object[] params) { final MailtoModel model = new MailtoModel(newMailToAddressModel(params), newMailToViewModel(params)); return model; }
java
public FSArray getEntity_attributes() { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_entity_attributes == null) jcasType.jcas.throwFeatMissing("entity_attributes", "de.julielab.jules.types.ace.Entity"); return (FSArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((...
python
def table_output(data): '''Get a table representation of a dictionary.''' if type(data) == DictType: data = data.items() headings = [ item[0] for item in data ] rows = [ item[1] for item in data ] columns = zip(*rows) if len(columns): widths = [ max([ len(str(y)) for y in row ]) ...
java
public void appendXMLToAutomaticStyle(final XMLUtil util, final Appendable appendable) throws IOException { this.pageLayoutStyle.appendXMLToAutomaticStyle(util, appendable); }
python
def main(**kwargs): """ Draw a couple of simple graphs and optionally generate an HTML file to upload them """ draw_lines() draw_histogram() draw_bar_chart() destination = "-r /report" if use_html: generate_html() command = "dx-build-report-html {h} {d}".format(h=html_fil...
java
public ScheduledInstancesNetworkInterface withPrivateIpAddressConfigs(ScheduledInstancesPrivateIpAddressConfig... privateIpAddressConfigs) { if (this.privateIpAddressConfigs == null) { setPrivateIpAddressConfigs(new com.amazonaws.internal.SdkInternalList<ScheduledInstancesPrivateIpAddressConfig>(pri...
java
public Observable<Void> resubmitAsync(String resourceGroupName, String workflowName, String triggerName, String historyName) { return resubmitWithServiceResponseAsync(resourceGroupName, workflowName, triggerName, historyName).map(new Func1<ServiceResponse<Void>, Void>() { @Override publi...
java
private void performNextWrite() { Append append = getNextAppend(); if (append == null) { return; } long traceId = LoggerHelpers.traceEnter(log, "storeAppend", append); Timer timer = new Timer(); storeAppend(append) .whenComplete((v, e) -> { ...
python
def pip(self, points, sorted_col=0, radius=0): """ Point-in-Polygon for the z=0 projection. This function enhances the performance of ``Polygon.contains()`` by verifying only the points which are inside the bounding box of the polygon. To do it fast, it needs the points ar...
java
private void writeObject(ObjectOutputStream outStream) throws IOException { PutField fields = outStream.putFields(); fields.put(BEGIN_DEFAULT, beginDefaultContext); outStream.writeFields(); }
python
def palettize(arr, colors, values): """From start *values* apply *colors* to *data*. """ new_arr = np.digitize(arr.ravel(), np.concatenate((values, [max(np.nanmax(arr), values.max()) + 1]))) ...
python
def map_data(self, map_name): """Return the map data for a map by name or path.""" with gfile.Open(os.path.join(self.data_dir, "Maps", map_name), "rb") as f: return f.read()
python
def settlement_method(self): """ [str] 交割方式,’CashSettlementRequired’ - 现金交割, ‘PhysicalSettlementRequired’ - 实物交割(期货专用) """ try: return self.__dict__["settlement_method"] except (KeyError, ValueError): raise AttributeError( "Instrument(order...
java
@Override public Date getPreviousStart(long base, int prevRawOffset, int prevDSTSavings, boolean inclusive) { int[] fields = Grego.timeToFields(base, null); int year = fields[0]; if (year > endYear) { return getFinalStart(prevRawOffset, prevDSTSavings); } Date d =...
java
public DoubleMatrix2D solve(DoubleMatrix2D B) { if (B.rows() != dim) { log.error("wrong dimension of vector b: expected " + dim + ", actual " + B.rows()); throw new RuntimeException("wrong dimension of vector b: expected " + dim + ", actual " + B.rows()); } // with scaling, we must solve U.Q.U.z = U.b...
java
private void buildSubJobBatchWorkUnits() { List<Flow> flows = this.split.getFlows(); parallelBatchWorkUnits = new ArrayList<BatchFlowInSplitWorkUnit>(); // Build all sub jobs from flows in split synchronized (subJobs) { for (Flow flow : flows) { subJobs.add(PartitionedStepBuilder.buildFlowInS...
python
def calculate_size(name, include_value, local_only): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES data_size += BOOLEAN_SIZE_IN_BYTES return data_size
java
Observable<ChatResult> synchroniseConversation(String conversationId) { return checkState().flatMap(client -> client.service().messaging() .queryMessages(conversationId, null, 1) .map(result -> { if (result.isSuccessful() && result.getResult() != null) { ...
python
def convert(ast): """Convert BEL1 AST Function to BEL2 AST Function""" if ast and ast.type == "Function": # Activity function conversion if ( ast.name != "molecularActivity" and ast.name in spec["namespaces"]["Activity"]["list"] ): print("name", ast.n...
python
def _filter_unique_identities(uidentities, matcher): """Filter a set of unique identities. This function will use the `matcher` to generate a list of `FilteredIdentity` objects. It will return a tuple with the list of filtered objects, the unique identities not filtered and a table mapping uuids wi...
python
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
python
def namedb_get_names_owned_by_address( cur, address, current_block ): """ Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name. """ unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block ) ...
python
def _timing_char(message): """ >>> message = 'MORSE CODE' >>> _timing_char(message) 'M------ O---------- R------ S---- E C---------- O---------- D------ E' """ s = '' inter_symb = ' ' inter_char = ' ' * 3 inter_word = inter_symb * 7 for i, word in enumerate(_s...
java
public static int probRound(double value, Random rand) { if (value >= 0) { double lower = Math.floor(value); double prob = value - lower; if (rand.nextDouble() < prob) { return (int)lower + 1; } else { return (int)lower; } } else { double lower = Math.floor(Math.abs(value)...
java
public static long randomLongLessThan(long maxExclusive) { checkArgument( maxExclusive > Long.MIN_VALUE, "Cannot produce long less than %s", Long.MIN_VALUE); return randomLong(Long.MIN_VALUE, maxExclusive); }
python
def next(self): """ Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...} """ try: entry = {} row = self._csv_reader.next() for i in range(0, le...
python
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() if self.is_pk_composite(): return [[getattr(item, pk) for pk in pk_name] for item in lst] else: return [getattr(item, pk_name) for item in...
python
def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency""" return Pauli.sigma(qubit, 'I', coefficient)
python
def called_with(self, *args, **kwargs): """ Before evaluating subsequent predicates, calls :attr:`subject` with given arguments (but unlike a direct call, catches and transforms any exceptions that arise during the call). """ self._args = args self._kwargs = kwargs ...