language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {...
java
public int getCountOfContextNodeList(XPathContext xctxt) throws javax.xml.transform.TransformerException { // assert(null != m_contextNodeList, "m_contextNodeList must be non-null"); // If we're in a predicate, then this will return non-null. SubContextList iter = m_isTopLevel ? null : xctxt.ge...
java
private GeometryCollection asGeomCollection(CrsId crsId) throws IOException { try { String subJson = getSubJson("geometries", "A geometrycollection requires a geometries parameter") .replaceAll(" ", ""); String noSpaces = subJson.replace(" ", ""); if (noSp...
python
def funk(p, x, y): """ Function misfit evaluation for best-fit tanh curve f(x[:]) = alpha*tanh(beta*x[:]) alpha = params[0] beta = params[1] funk(params) = sqrt(sum((y[:] - f(x[:]))**2)/len(y[:])) Output is RMS misfit x=xx[0][:] y=xx[1][:]q """ alpha=p[0] beta...
python
def get_error_page(self): """ Method returning error page. Should return string. By default it find element with class ``error-page`` and returns text of ``h1`` header. You can change this method accordingly to your app. Error page returned from this method is used in decorator...
java
public void randomWait(long min, long max) { final long waitTime = randomLong(min, max); try { Thread.sleep(waitTime); } catch (InterruptedException interruptedException) { // ignored } }
python
def report(self, job_ids=None, array_ids=None, output=True, error=True, status=Status, name=None): """Iterates through the output and error files and write the results to command line.""" def _write_contents(job): # Writes the contents of the output and error files to command line out_file, err_file...
python
def y_lower_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the y-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's y_lower_limit will be set to this. :raises ValueError: if ...
java
@Override public CreatePortfolioResult createPortfolio(CreatePortfolioRequest request) { request = beforeClientExecution(request); return executeCreatePortfolio(request); }
python
def plot(self, y_axis='attenuation', x_axis='energy', logx=False, logy=False, mixed=True, all_layers=False, all_elements=False, all_isotopes=False, items_to_plot=None, time_unit='us', offset_us=0., source_to_detector_m=16., time_resolution_us=0.16, t_star...
java
public static boolean doesStringContainOpenQuote(String text) { boolean doubleQuote = false; boolean singleQuote = false; boolean escapedByBackSlash = false; // do not parse comment if (commentPattern.matcher(text).find()) return false; for (int i = 0; i < te...
python
def delete(self, file_, delete_file=True): """ Deletes file_ references in Key Value store and optionally the file_ it self. """ image_file = ImageFile(file_) if delete_file: image_file.delete() default.kvstore.delete(image_file)
java
public static INDArray firstIndex(INDArray array, Condition condition, int... dimension) { if (!(condition instanceof BaseCondition)) throw new UnsupportedOperationException("Only static Conditions are supported"); return Nd4j.getExecutioner().exec(new FirstIndex(array, condition, dimension...
java
public static <T> Set<T> enumerationToSet(Enumeration<T> enumeration) { Set<T> set = new HashSet<>(); while (enumeration.hasMoreElements()) { set.add(enumeration.nextElement()); } return set; }
java
public synchronized void add(VisitState visitState) { final boolean wasEntirelyBroken = isEntirelyBroken(); if (visitState.lastExceptionClass != null) brokenVisitStates++; visitStates.add(visitState); assert brokenVisitStates <= visitStates.size(); if (wasEntirelyBroken && ! isEntirelyBroken()) workbenchBroke...
java
public int previous() { int index; // offset in ICU4C if (search_.reset_) { index = search_.endIndex(); // m_search_->textLength in ICU4C search_.isForwardSearching_ = false; search_.reset_ = false; setIndex(index); } else { index = ...
python
def combine_HSPs(a): """ Combine HSPs into a single BlastLine. """ m = a[0] if len(a) == 1: return m for b in a[1:]: assert m.query == b.query assert m.subject == b.subject m.hitlen += b.hitlen m.nmismatch += b.nmismatch m.ngaps += b.ngaps ...
java
protected static boolean loadDefaultConf(String packageName) throws ParseException { if (packageName.endsWith(".conf")) { return false; } packageName = packageName.replaceAll("\\$[0-9]+$", ""); Resource defaultConf = new ClasspathResource((packageName.replaceAll("\\.", ...
python
def autocorrfunc(freq, power): """ Calculate autocorrelation function(s) for given power spectrum/spectra. Parameters ---------- freq : numpy.ndarray 1 dimensional array of frequencies. power : numpy.ndarray 2 dimensional power spectra, 1st axis units, 2nd axis frequencies. ...
python
def list_roles(self, principal_name, principal_type): """ Parameters: - principal_name - principal_type """ self.send_list_roles(principal_name, principal_type) return self.recv_list_roles()
python
def get_ancestors(self): """ Get all unique instance ancestors """ ancestors = list(self.get_parents()) ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors]) ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)] for ancestor in anc...
python
def bayesian(self, params=None): ''' Run the Bayesian Bandit algorithm which utilizes a beta distribution for exploration and exploitation. Parameters ---------- params : None For API consistency, this function can take a parameters argument, but ...
java
private Token attributesBlock() { Matcher matcher = scanner.getMatcherForPattern("^&attributes\\b"); if (matcher.find(0) && matcher.group(0) != null) { this.scanner.consume(11); CharacterParser.Match match = this.bracketExpression(); this.scanner.consume(match.getEnd(...
python
def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.]) """ return np.array(quaternion[1:4], dtype=np.float64, copy=True)
python
def _load_data_alignment(self, chain1, chain2): """ Extract the sequences from the PDB file, perform the alignment, and load the coordinates of the CA of the common residues. """ parser = PDB.PDBParser(QUIET=True) ppb = PDB.PPBuilder() structure1 = parser.get_str...
java
void put(String uuid, CachingIndexReader reader, int n) { LRUMap cacheSegment = docNumbers[getSegmentIndex(uuid.charAt(0))]; //UUID key = UUID.fromString(uuid); String key = uuid; synchronized (cacheSegment) { Entry e = (Entry)cacheSegment.get(key); if (e != null) ...
python
def getrange(self, key, start, end): """Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is alway...
python
def get(cls, sensor_type): """ Shortcut that acquires the default Sensor of a given type. Parameters ---------- sensor_type: int Type of sensor to get. Returns ------- result: Future A future that resolve...
java
private Optional tryCreate(Constructor<?> constructor) { Object[] args = new Object[constructor.getParameterCount()]; Object arg; Optional<Object> resolved; int i = 0; for (Parameter parameter : constructor.getParameters()) { resolved = context.resolve(parameter); if (!resolved.isPresent...
java
static Key str2Key(String s) { Key k = str2Key_impl(s); assert key2Str_impl(k, decodeType(s)).equals(s) : "bijection fail " + s + " <-> " + k; return k; }
java
public static boolean isNumberStr(String arg) { if (StringUtils.isEmpty(arg)) { return false; } return check(arg, NUMBER_STR_PARTER); }
python
def rhombohedral(a: float, alpha: float): """ Convenience constructor for a rhombohedral lattice. Args: a (float): *a* lattice parameter of the rhombohedral cell. alpha (float): Angle for the rhombohedral lattice in degrees. Returns: Rhombohedral lat...
python
def get_uninvoiced_hours(entries, billable=None): """Given an iterable of entries, return the total hours that have not been invoiced. If billable is passed as 'billable' or 'nonbillable', limit to the corresponding entries. """ statuses = ('invoiced', 'not-invoiced') if billable is not None: ...
python
def prep_doc(self, doc_obj): """ This method Validates, gets the Python value, checks unique indexes, gets the db value, and then returns the prepared doc dict object. Useful for save and backup functions. @param doc_obj: @return: """ doc = doc_obj._da...
python
def rebuild( self, gridRect ): """ Rebuilds the tracker item. """ scene = self.scene() if ( not scene ): return self.setVisible(gridRect.contains(self.pos())) self.setZValue(100) path = QPainterPath() path....
java
public void mutateIndex(StaticBuffer key, List<Entry> additions, List<Entry> deletions) throws BackendException { indexStore.mutateEntries(key, additions, deletions, storeTx); }
python
def pendingvalidation(self, warnonly=None): """Perform any pending validations Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5) Returns: ...
python
def splitlines(self, keepends=False): """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ # Py2 unicode.splitli...
python
def to_frame(self, slot=SLOT.SCAN_MAP): """ Return the current configuration as a YubiKeyFrame object. """ payload = self.scanmap.ljust(64, b'\0') return yubikey_frame.YubiKeyFrame(command=slot, payload=payload)
java
@Nonnull @ReturnsMutableCopy public ICommonsList <CSSStyleRule> getAllStyleRules () { return m_aRules.getAllMapped (r -> r instanceof CSSStyleRule, r -> (CSSStyleRule) r); }
java
public static boolean isAncestorOrSame(URI descendant, URI ancestor) { Preconditions.checkNotNull(descendant, "input can not be null"); Preconditions.checkNotNull(ancestor, "input can not be null"); if (!stringSame(descendant.getScheme(), ancestor.getScheme())) { return false; } if (!stringS...
python
def js(): "returns home directory of js" return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'js')
java
public ListPipelinesResult withPipelines(PipelineSummary... pipelines) { if (this.pipelines == null) { setPipelines(new java.util.ArrayList<PipelineSummary>(pipelines.length)); } for (PipelineSummary ele : pipelines) { this.pipelines.add(ele); } return thi...
python
def _map_arguments(self, input_dict): """Map from the top-level arguments to the arguments provided to the indiviudal links """ data = input_dict.get('data') comp = input_dict.get('comp') library = input_dict.get('library') models = input_dict.get('models') hpx_or...
java
@Override public UnitFactory getUnitFactory() throws DataSourceReadException { initializeIfNeeded(); UnitFactory result = null; DataSourceBackend b = null; for (DataSourceBackend backend : getBackends()) { result = backend.getUnitFactory(); b = backend; ...
python
def pretty(self,verbose=0): """Return pretty list description of parameter""" # split prompt lines and add blanks in later lines to align them plines = self.prompt.split('\n') for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1] plines = '\n'.join(plines) nam...
java
public void blockUser(Integer targetUserId) throws IOException { String tailUrl = GitlabUser.USERS_URL + "/" + targetUserId + GitlabUser.BLOCK_URL; retrieve().method(POST).to(tailUrl, Void.class); }
java
private static String getPreDefOuFqn(CmsObject cms, HttpServletRequest request, boolean logout) { if (logout && (request.getAttribute(PARAM_PREDEF_OUFQN) == null)) { String oufqn = cms.getRequestContext().getOuFqn(); if (!oufqn.startsWith(CmsOrganizationalUnit.SEPARATOR)) { ...
python
def setPrevUpNextLinks(self, prev=None, up=None, next=None): """Sets Prev link to point to the LogEntry object "prev". Set that object's Next link to point to us. Sets the "up" link to the URL 'up' (if up != None.) Sets the Next link to the entry 'next' (if next != None), or to nothing if next == ''."""...
java
static ImmutableSet<ExecutableElement> propertyMethodsIn(Set<ExecutableElement> abstractMethods) { ImmutableSet.Builder<ExecutableElement> properties = ImmutableSet.builder(); for (ExecutableElement method : abstractMethods) { if (method.getParameters().isEmpty() && method.getReturnType().getKin...
python
def db_for_write(self, model, **hints): """ If given some hints['instance'] that is saved in a db, use related fields from the same db. Otherwise if passed a class or instance to model, return the salesforce alias if it's a subclass of SalesforceModel. """ if 'instance' i...
java
protected void parseIntegerLists(TokenList tokens) { TokenList.Token t = tokens.getFirst(); if( t == null || t.next == null ) return; int state = 0; TokenList.Token start = null; TokenList.Token prev = t; boolean last = false; while( true ) { ...
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = ApplyPolicy.class) public JAXBElement<CmisExtensionType> createApplyPolicyExtension( CmisExtensionType value) { return new JAXBElement<CmisExtensionType>( _GetPropertiesExtension_QNAME, CmisExte...
python
def hugepage_support(user, group='hugetlb', nr_hugepages=256, max_map_count=65536, mnt_point='/run/hugepages/kvm', pagesize='2MB', mount=True, set_shmmax=False): """Enable hugepages on system. Args: user (str) -- Username to allow access to hugepages to group ...
java
public CmsRelationType addRelationType(String name, String type) throws CmsConfigurationException { // check if new relation types can still be added if (m_frozen) { throw new CmsConfigurationException(Messages.get().container(Messages.ERR_NO_CONFIG_AFTER_STARTUP_0)); } Cms...
java
public void marshall(DescribeCopyProductStatusRequest describeCopyProductStatusRequest, ProtocolMarshaller protocolMarshaller) { if (describeCopyProductStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
python
def valUserCert(self, byts, cacerts=None): ''' Validate the PEM encoded x509 user certificate bytes and return it. Args: byts (bytes): The bytes for the User Certificate. cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates. Raises: OpenSS...
java
private List<Tuple2<String, String>> getHelpOptions() { final List<Tuple2<String, String>> options = new ArrayList<>(); options.add(Tuple2.of("Q", CliStrings.RESULT_QUIT)); options.add(Tuple2.of("R", CliStrings.RESULT_REFRESH)); options.add(Tuple2.of("+", CliStrings.RESULT_INC_REFRESH)); options.add(Tuple2....
java
private String getText(JsonNode jsonObject, String nodeName) { JsonNode subNode = jsonObject.get(nodeName); if (subNode == null) { return null; } if (!subNode.isTextual()) { throw new IllegalStateException(nodeName + " from credential process should be textual, ...
python
def packto(self, namedstruct, stream): """ Pack a struct to a stream :param namedstruct: struct to pack :param stream: a buffered stream :return: appended bytes size """ # Default implementation data = self.pack(namedstruct) ...
python
def add(self, *args, **kwargs): """Add a new record to the section""" if self.start and self.start.state == 'done' and kwargs.get('log_action') != 'done': raise ProgressLoggingError("Can't add -- process section is done") self.augment_args(args, kwargs) kwargs['log_action'...
java
@Override public MtasSpanWeight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException { if (q1 == null || q2 == null) { return null; } else { MtasSpanIntersectingQueryWeight w1 = new MtasSpanIntersectingQueryWeight( q1.createWeight(searcher, need...
python
def fetch(self): """ Fetch a AssetVersionInstance :returns: Fetched AssetVersionInstance :rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionInstance """ params = values.of({}) payload = self._version.fetch( 'GET', s...
java
public String trimLeading(String str) { if (str == null) { return null; } int length = str.length(); for (int i=0; i<length; i++) { if (str.charAt(i) > ' ') { return str.substring(i); } } return ""; }
java
@PostConstruct public void init() { //init Bus and LifeCycle listeners if (bus != null && sendLifecycleEvent ) { ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class); if (null != slcm) { ServiceListenerImpl svrListener = new...
java
@Override public void runInvalidation() { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) { LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[RUN_INVALIDATION], appNameForLogging); } /* ...
python
def IterQueryInstances(self, FilterQueryLanguage, FilterQuery, namespace=None, ReturnQueryResultClass=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=DEFAULT_ITER_MAXOBJECTCOUNT, **extra): ...
java
public void readObject(java.io.DataInputStream dataInputStream, ObjectManagerState objectManagerState) throws ObjectManagerException { final String methodName = "readObject"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.ent...
java
public void start() throws Exception { // 1. Do prepare work // create an instance of state manager String statemgrClass = Context.stateManagerClass(config); LOG.info("Context.stateManagerClass " + statemgrClass); IStateManager statemgr; try { statemgr = ReflectionUtils.newInstance(statemg...
python
def if_else(self, pred, likely=None): """ A context manager which sets up two conditional basic blocks based on the given predicate (a i1 value). A tuple of context managers is yield'ed. Each context manager acts as a if_then() block. *likely* has the same meaning as in ...
java
public List<Milestone> getGroupMilestones(Object groupIdOrPath) throws GitLabApiException { return (getGroupMilestones(groupIdOrPath, getDefaultPerPage()).all()); }
java
public void setLoggedOutIndicatorPattern(String loggedOutIndicatorPattern) { if (loggedOutIndicatorPattern == null || loggedOutIndicatorPattern.trim().length() == 0) { this.loggedOutIndicatorPattern = null; } else { this.loggedOutIndicatorPattern = Pattern.compile(loggedOutIndicatorPattern); } }
python
def table_as_df(self, table_name): """Return a table as a dataframe.""" self.table_must_exist(table_name) query = "SELECT * FROM `%s`" % table_name.lower() return pandas.read_sql(query, self.own_conn)
python
def report(self, req): """Adds a report request to the cache. Returns ``None`` if it could not be aggregated, and callers need to send the request to the server, otherwise it returns ``CACHED_OK``. Args: req (:class:`sc_messages.ReportRequest`): the request to b...
java
@Override public LogIterator getIterator(Zxid zxid) throws IOException { SimpleLogIterator iter = new SimpleLogIterator(this.logFile); while(iter.hasNext()) { Transaction txn = iter.next(); if(txn.getZxid().compareTo(zxid) >= 0) { iter.backward(); break; } } return it...
python
def parse_plain_scalar_indent(TokenClass): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: ...
java
protected void deliverInvokeTimeout(MAPDialog mapDialog, Invoke invoke) { for (MAPServiceListener serLis : this.serviceListeners) { serLis.onInvokeTimeout(mapDialog, invoke.getInvokeId()); } }
java
public void setDefinitions(java.util.Collection<DefinitionInformation> definitions) { if (definitions == null) { this.definitions = null; return; } this.definitions = new java.util.ArrayList<DefinitionInformation>(definitions); }
java
public WriteResponse write (String record) throws IOException { recordsAttempted.mark(); String encoded = encodeRecord(record); int returnCode = request (encoded); recordsSuccess.mark(); bytesWritten.mark(encoded.length()); return WRITE_RESPONSE_WRAPPER.wrap(returnCode); }
python
def find_this(search, source=SOURCE): """Take a string and a filename path string and return the found value.""" print("Searching for {what}.".format(what=search)) if not search or not source: print("Not found on source: {what}.".format(what=search)) return "" return str(re.compile(r'.*_...
java
public static <E> List<E> search(Iterator<E> iterator, Predicate<E> predicate) { final Function<Iterator<E>, ArrayList<E>> consumer = new ConsumeIntoCollection<>(new ArrayListFactory<E>()); final FilteringIterator<E> filtered = new FilteringIterator<E>(iterator, predicate); return consumer.apply...
python
async def uint(self, elem, elem_type, params=None): """ Integer types :param elem: :param elem_type: :param params: :return: """ if self.writing: return await x.dump_uint(self.iobj, elem, elem_type.WIDTH) else: return await ...
java
private static void reduce(int size) { for (int i = 0; i < maxSelectors - size; i++) { try { Selector selector = selectors.pop(); selector.close(); } catch (IOException e) { logger.error("SelectorFactory.reduce", e); } } }
java
public static org.neo4j.graphdb.Node createTemplateFieldInfoNode( final AbstractGraphDatabase graphDatabase, final TemplateFieldInfo fieldInfo) { final org.neo4j.graphdb.Node fieldNode = TemplateItemInfo .createTemplateItemNode(graphDatabase, fieldInfo); fieldNode .setProperty(TemplateXMLFields.FIELD_...
java
public void cancel() { try { // FileOutputStream is also closed cascadingly if (outStream != null) { outStream.close(); outStream = null; } // Clear encryptor: encryptor = null; } catch (IOException e) { ...
java
final void warnInvalidRecord(DnsRecordType type, ByteBuf content) { if (logger().isWarnEnabled()) { final String dump = ByteBufUtil.hexDump(content); logger().warn("{} Skipping invalid {} record: {}", logPrefix(), type.name(), dump.isEmpty() ? "<empty>" : dump);...
python
def ParseFromUnicode(self, value): """Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse """ precondition.AssertType(value, Text) value = value.strip() super(ClientURN, self).ParseFromUnicode(value) mat...
java
public static <T> T parse(byte[] in, Class<T> mapTo) { try { JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE); return p.parse(in, defaultReader.getMapper(mapTo)); } catch (Exception e) { return null; } }
java
public static char matchBracket(char c) { if(openBrackets.containsKey(c)) { return openBrackets.get(c); } else if(closingBrackets.containsKey(c)) { return closingBrackets.get(c); } return c; }
java
protected void addInvalidValues(Set<ConstraintViolation<T>> invalidValues) { if (invalidValues != null) { for (ConstraintViolation invalidValue : invalidValues) { results.addMessage(translateMessage(invalidValue)); } } }
java
public StoreAsBinaryConfigurationBuilder disable() { attributes.attribute(ENABLED).set(false); getBuilder().memory().storageType(StorageType.OBJECT); return this; }
python
def on_header(self, name: bytes, value: bytes) -> None: """ header 回调 """ name_ = decode_bytes(name).casefold() val = decode_bytes(value) if name_ == "cookie": # 加载上次的 cookie self._cookies.load(val) if name_ in self._headers: # ...
java
public void setGravity(double gravity) { if(Double.isInfinite(gravity) || Double.isNaN(gravity) || gravity <= 0) throw new IllegalArgumentException("Gravity must be positive, not " + gravity); this.gravity = gravity; }
java
public JSONArray element( Map value, JsonConfig jsonConfig ) { if( value instanceof JSONObject ){ elements.add( value ); return this; }else{ return element( JSONObject.fromObject( value, jsonConfig ) ); } }
java
public static Iterable<Map<String, Object>> scan(final DataStore dataStore, final String table, final @Nullable String fromKeyExclusive, final long limit, ...
java
protected static String buildMessage(String msg) { StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2]; return caller.getClassName() + "." + caller.getMethodName() + "(): \n" + msg; }
python
def find_source_files(input_path, excludes): """ Get a list of filenames for all Java source files within the given directory. """ java_files = [] input_path = os.path.normpath(os.path.abspath(input_path)) for dirpath, dirnames, filenames in os.walk(input_path): if is_excluded(dirpat...
python
def get_single_hdd_only_candidate_model( data, minimum_non_zero_hdd, minimum_total_hdd, beta_hdd_maximum_p_value, weights_col, balance_point, ): """ Return a single candidate hdd-only model for a particular balance point. Parameters ---------- data : :any:`pandas.DataFrame` ...
python
def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = requests.get(url, headers=requisite_h...
python
def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]: """ For the given iterable of object iterations, return an iterable of the most common object at each position of the inner iterations. E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m...