language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void free() { try { this.updateIfNewRow(-1); // Update any locked record. } catch (DBException ex) { ex.printStackTrace(); } if (m_modelListeners != null) { for (ThinTableModelListener thinTableModelListener : m_modelListeners)...
python
def _StructPackDecoder(wire_type, format): """Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack(). """ value_size = struct.calcsize(format) local_unpack = struct.unpack # Reusing _SimpleDeco...
java
@Override public AnnotationGroup convert(XBELAnnotationGroup source) { if (source == null) return null; List<Object> list = source.getAnnotationOrEvidenceOrCitation(); // Destination type AnnotationGroup dest = new AnnotationGroup(); // Capture XBELCitation elements of lis...
java
public void update(MatrixFunction function) { MatrixIterator it = iterator(); while (it.hasNext()) { double x = it.next(); int i = it.rowIndex(); int j = it.columnIndex(); it.set(function.evaluate(i, j, x)); } }
python
def entry_point(entry_point_name): """Use this to decorate a DNAnexus execution environment entry point. Example: .. code-block:: python @dxpy.entry_point('main') def hello(i): pass """ def wrap(f): ENTRY_POINT_TABLE[entry_point_name] = f @wraps(f) ...
java
public static Polygon removeDuplicateCoordinates(Polygon polygon, double tolerance) throws SQLException { Coordinate[] shellCoords = CoordinateUtils.removeRepeatedCoordinates(polygon.getExteriorRing().getCoordinates(),tolerance,true); LinearRing shell = FACTORY.createLinearRing(shellCoords); Arr...
java
public Map<String, Object> getSiteProperties() { Map<String, Object> properties = new HashMap<String, Object>(); Record recUser = this.getMainRecord(); String sitePrefix = ((PropertiesField)recUser.getField(UserInfo.PROPERTIES)).getProperty(MenusMessageData.SITE_PREFIX); ...
java
private Content getValue(VariableElement member) { String value = utils.constantValueExpresion(member); Content valueContent = new StringContent(value); Content code = HtmlTree.CODE(valueContent); return HtmlTree.TD(HtmlStyle.colLast, code); }
python
def load_scores_wiggle( fname ): """ Read a wiggle file and return a dict of BinnedArray objects keyed by chromosome. """ scores_by_chrom = dict() for chrom, pos, val in bx.wiggle.Reader( misc.open_compressed( fname ) ): if chrom not in scores_by_chrom: scores_by_chrom[chrom...
java
public static void initLogConfig(String logConfigpath) { try { LoggerContext context =(LoggerContext)LogManager.getContext(false); if(context!=null) { context.setConfigLocation(new File(logConfigpath).toURI()); context.reconfigure();//重新初始化Log4j2的配置上下文 }else { ConfigurationSource sour...
python
def get_children(self): """Return all the children of this object.""" if hasattr(self, '_cached_children'): children = self._toplevel().objects.filter( pk__in=[n.pk for n in self._cached_children] ) children._result_cache = self._cached_children ...
python
def _backup_bytes(target, offset, length): """ Read bytes from one file and write it to a backup file with the .bytes_backup suffix """ click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(targ...
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<AnnotatedDataset, LabelOperationMetadata> labelVideoAsync( String parent, HumanAnnotationConfig basicConfig, LabelVideoRequest.Feature feature) { DATASET_PATH_TEMPLATE.vali...
python
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None): ''' Wrapper around impacket.smbconnection.putFile() that allows a string to be uploaded, without first writing it as a local file ''' if HAS_SMBPROTOCOL: return _put_str_smbprotocol( conte...
java
static double randomTriangular (double low, double high, double mode) { double u = MathUtils.random.nextDouble(); double d = high - low; if (u <= (mode - low) / d) return low + Math.sqrt(u * d * (mode - low)); return high - Math.sqrt((1 - u) * d * (high - mode)); }
java
public DateFuncSup subtract(DateSeperator d) { date.setTime(date.getTime() - d.parse()); return this; }
python
def _format_str(string): """Attempt fast string handing by decoding directly into an array.""" if isinstance(string, _STRTYPES): if _IS_PYTHON3: array = _array.array('I') array.frombytes(string.encode(_utf32_codec)) else: # Python 2 if isinstance(string, unico...
python
def attach(self, container_id=None, sudo=False): '''attach to a container instance based on container_id Parameters ========== container_id: the container_id to delete sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the roo...
python
def pie(n_labels=5,mode=None): """ Returns a DataFrame with the required format for a pie plot Parameters: ----------- n_labels : int Number of labels mode : string Format for each item 'abc' for alphabet columns 'stocks' for random stock names """ return pd.DataFrame({'values':np.random.ra...
python
def isothermal_work_compression(P1, P2, T, Z=1): r'''Calculates the work of compression or expansion of a gas going through an isothermal process. .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) Parameters ---------- P1 : float Inlet pressure, [Pa] P2 : float Outle...
java
public static IRubyObject const_find(IRubyObject self, IRubyObject const_name) { RubyModule tclass = self.getRuntime().getObject(); RubyArray tparts = ((RubyString)const_name).split(self.getRuntime().getCurrentContext(), self.getRuntime().newString("::")); for(int i=0; i < tparts.getLength(); i+...
python
def update_stack(StackName=None, TemplateBody=None, TemplateURL=None, UsePreviousTemplate=None, StackPolicyDuringUpdateBody=None, StackPolicyDuringUpdateURL=None, Parameters=None, Capabilities=None, ResourceTypes=None, RoleARN=None, StackPolicyBody=None, StackPolicyURL=None, NotificationARNs=None, Tags=None, ClientRequ...
java
public void writeRawMessageSetExtension(final int fieldNumber, final ByteString value) throws IOException { writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP); writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fiel...
java
public boolean isWifiConnected() { try { if (connMan == null) { connMan = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); } NetworkInfo wifiNetInfo = connMan.getNetworkInfo(TYPE_WIFI); NetworkInfo wimaxNetInfo = connMan.getNetworkInfo(TYPE_WIMAX); if (wifiNetIn...
java
void sendBufferSync(ByteBuffer bb) { try { /* configure socket to be blocking * so that we dont have to do write in * a tight while loop */ sock.configureBlocking(true); if (bb != closeConn) { if (sock != null) { ...
python
def get_number(s, cast=int): """ Try to get a number out of a string, and cast it. """ import string d = "".join(x for x in str(s) if x in string.digits) return cast(d)
python
def cache_all(self): """Cache all available man pages""" respond = input( 'By default, cppman fetches pages on-the-fly if corresponding ' 'page is not found in the cache. The "cache-all" option is only ' 'useful if you want to view man pages offline. ' ...
python
def _reset(self): """ Reinitializes basis functions, iteration number and loss history. """ self.basis = np.random.randn(self.filterDim, self.outputDim) self.basis /= np.sqrt(np.sum(self.basis ** 2, axis=0)) self._iteration = 0 self.losses = {}
python
def conditions(self) -> \ Dict[str, Dict[str, Dict[str, Union[float, numpy.ndarray]]]]: """A nested dictionary containing the values of all |ConditionSequence| objects of all currently handled models. See the documentation on property |HydPy.conditions| for further informati...
java
public static Image getInstance(Image image) { if (image == null) return null; try { Class cs = image.getClass(); Constructor constructor = cs .getDeclaredConstructor(new Class[] { Image.class }); return (Image) constructor.newInstance(new Object[] { image }); } catch (Exception e) { throw new...
java
public T findItem (Predicate<T> p) { if (_items == null) { return null; } for (T item : _items) { if (p.apply(item)) { return item; } } return null; }
python
def all_contributors(soup, detail="brief"): "find all contributors not contrained to only the ones in article meta" contrib_tags = raw_parser.contributors(soup) contributors = format_authors(soup, contrib_tags, detail) return contributors
java
@Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { FileSplit fSplit = (FileSplit)split; // Initialize start and end of split start = fSplit.getStart(); end = start + fSplit.getLength(); final Path file = fSplit.get...
java
public com.google.protobuf.Duration getDefaultCookieExpiration() { return defaultCookieExpiration_ == null ? com.google.protobuf.Duration.getDefaultInstance() : defaultCookieExpiration_; }
java
public static List<CommerceTaxFixedRate> findByCommerceTaxMethodId( long commerceTaxMethodId, int start, int end) { return getPersistence() .findByCommerceTaxMethodId(commerceTaxMethodId, start, end); }
java
public final EObject entryRuleXbaseConstructorCall() throws RecognitionException { EObject current = null; EObject iv_ruleXbaseConstructorCall = null; try { // InternalSARL.g:10169:61: (iv_ruleXbaseConstructorCall= ruleXbaseConstructorCall EOF ) // InternalSARL.g:10170...
python
def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs): """Create an edge between two nodes. Args: tail_name: Start node identifier. head_name: End node identifier. label: Caption to be displayed near the edge. attrs: Any additional e...
java
public java.util.List<String> getMetadata() { if (metadata == null) { metadata = new com.amazonaws.internal.SdkInternalList<String>(); } return metadata; }
java
public ScheduledEntry<K, V> getByCompositeKey(K key) { Set<CompositeKey> candidateKeys = getCompositeKeys(key); ScheduledEntry<K, V> result = null; for (CompositeKey compositeKey : candidateKeys) { Integer second = secondsOfKeys.get(compositeKey); if (second != null) { ...
python
def delete_task_group(self, project, task_group_id, comment=None): """DeleteTaskGroup. [Preview API] Delete a task group. :param str project: Project ID or project name :param str task_group_id: Id of the task group to be deleted. :param str comment: Comments to delete. "...
python
def simple_atmo_opstring(haze, contrast, bias): """Make a simple atmospheric correction formula.""" gamma_b = 1 - haze gamma_g = 1 - (haze / 3.0) ops = ( "gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}" ).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast...
java
public Observable<ServiceResponse<Page<JobExecutionInner>>> listByAgentWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final DateTime createTimeMin, final DateTime createTimeMax, final DateTime endTimeMin, final DateTime endTimeMax, final Boolean isActive, fi...
python
def has_new_revision(self): """ :return: True if new revision exists, False if not. :rtype: boolean """ if self.history.current_revision is None: return self.state.revision_id is not None current_revision_id = self.history.current_revision.revision_id ...
python
def abort(status_code, message=None): """ Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided. :param status_code: The HTTP status code to return. :param message: The HTTP response body. Defaults to the messages ...
java
public Pager<Participant> getParticipants(Object projectIdOrPath, Integer mergeRequestIid, int itemsPerPage) throws GitLabApiException { return new Pager<Participant>(this, Participant.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, ...
java
public static String getCaller() { StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); if (stacks != null) { for (int i = 0; i < stacks.length; i++) { String cn = stacks[i].getClassName(); if (cn != null && !Constants.CLASSNAME_TO_ESCAPE.conta...
java
public static @NotNull String validName(@NotNull String value) { // convert to lowercase String text = value.toLowerCase(); // replace some special chars first text = StringUtils.replace(text, "ä", "ae"); text = StringUtils.replace(text, "ö", "oe"); text = StringUtils.replace(text, "ü", "ue");...
java
private static String cleanSoyDocHelper(String soyDoc) { // Change all newlines to "\n". soyDoc = NEWLINE.matcher(soyDoc).replaceAll("\n"); // Escape all @deprecated javadoc tags. // TODO(cushon): add this to the specification and then also generate @Deprecated annotations soyDoc = soyDoc.replace("...
java
protected List<R> visitChildrenAllowingConcurrentModification(ParentNode<? extends N> node) { List<R> results = new ArrayList<>(node.numChildren()); // use toArray to create a copy to avoid concurrent modification exception for (Node child : node.getChildren().toArray(EMPTY_NODE_ARRAY)) { // safe sinc...
python
def make_relative(base, obj): """Relativize the location URI of a File or Directory object.""" uri = obj.get("location", obj.get("path")) if ":" in uri.split("/")[0] and not uri.startswith("file://"): pass else: if uri.startswith("file://"): uri = uri_file_path(uri) ...
java
protected <T> T processInjectionPoint(final Member injectionTarget, final Class<T> injectionType, final GrpcClient annotation) { final List<ClientInterceptor> interceptors = interceptorsFromAnnotation(annotation); final String name = annotation.value(); final Channel channel; ...
python
def delete_key(self, key_to_delete): """Deletes the specified key :param key_to_delete: :return: """ log = logging.getLogger(self.cls_logger + '.delete_key') log.info('Attempting to delete key: {k}'.format(k=key_to_delete)) try: self.s3client.delete_...
python
def drop(self, async_=False, if_exists=False, **kw): """ Drop this table. :param async_: run asynchronously if True :return: None """ async_ = kw.get('async', async_) return self.parent.delete(self, async_=async_, if_exists=if_exists)
java
public final float toPoint() { if (unit == FontSizeUnit.PIXEL) { return (size / 4 * 3); } if (unit == FontSizeUnit.EM) { return (size * 12); } if (unit == FontSizeUnit.PERCENT) { return (size / 100 * 12); } if (unit ==...
java
public void setOwner(ListenerOwner owner) { super.setOwner(owner); if (this.getOwner() != null) { InitFieldHandler behavior = (InitFieldHandler)this.getOwner().getListener(InitFieldHandler.class.getName()); if (this.getOwner().getRecord().getEditMode() == DBConstants....
python
async def load_all_aldb(self, clear=True): """Read all devices ALDB.""" for addr in self.plm.devices: await self.load_device_aldb(addr, clear)
python
def setButton(self, which, button): """ Sets the button for this wizard for the inputed type. :param which | <XOverlayWizard.WizardButton> button | <QtGui.QPushButton> """ try: self._buttons[which].deleteLater() except KeyError: ...
java
public final void postMethodInvocation(Method method,Object[] arguments,Object output) { this.logEvent(FaxClientSpiProxyEventType.POST_EVENT_TYPE,method,arguments,output,null); }
java
public Content getSummaryTableTree(AbstractMemberWriter mw, ClassDoc cd, List<Content> tableContents, boolean showTabs) { Content caption; if (showTabs) { caption = getTableCaption(mw.methodTypes); generateMethodTypesScript(mw.typeMap, mw.methodTypes); } ...
java
protected String failMsg(final Throwable thrwbl, final String queue, final Job job) throws IOException { final JobFailure failure = new JobFailure(); failure.setFailedAt(new Date()); failure.setWorker(this.name); failure.setQueue(queue); failure.setPayload(job); failure.s...
java
public final byte[] wrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { if (!(this instanceof NullCipher)) { if (!initialized) { throw new IllegalStateException("Cipher not initialized"); } if (opmode != Cipher.WRAP_MODE) { ...
python
def daemon_mode(self, args, options): """ Open a ControlWebSocket to SushiBar server and listend for remote commands. Args: args (dict): chef command line arguments options (dict): additional compatibility mode options given on command line """ cws = Contr...
java
public ListenableFuture<List<V>> findAsync(Object... keys) { Timer timer = getMetrics().getTimer(MetricsType.DATA_PROVIDER_FIND.name()); List<Object> parameters = new ArrayList<>(); Collections.addAll(parameters, keys); ListenableFuture<List<V>> resultFuture = fetchAsync(parameters); ...
python
def get_end_time_str(self): """ :return: |attr_end_datetime| as a |str| formatted with |attr_end_time_format|. Return |NaT| if invalid datetime or format. :rtype: str :Sample Code: .. code:: python from datetimerange impor...
java
@Activate protected void activate(ComponentContext cc) { securityServiceRef.activate(cc); logger.log(Level.INFO, "BATCH_SECURITY_ENABLED"); }
python
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None): """Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)""" E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/...
java
@Pure public static String getAttributeValueWithDefault(Node document, String defaultValue, String... path) { assert document != null : AssertMessages.notNullParameter(0); return getAttributeValueWithDefault(document, true, defaultValue, path); }
java
public static CommerceOrderPayment findByPrimaryKey( long commerceOrderPaymentId) throws com.liferay.commerce.exception.NoSuchOrderPaymentException { return getPersistence().findByPrimaryKey(commerceOrderPaymentId); }
python
def register(dlgr_id, snapshot=None): """Register the experiment using configured services.""" try: config.get("osf_access_token") except KeyError: pass else: osf_id = _create_osf_project(dlgr_id) _upload_assets_to_OSF(dlgr_id, osf_id)
python
def _set_syslog_client(self, v, load=False): """ Setter method for syslog_client, mapped from YANG variable /logging/syslog_client (container) If this variable is read-only (config: false) in the source YANG file, then _set_syslog_client is considered as a private method. Backends looking to populat...
python
def to_matrix( xx, yy, zz, xy, yz, xz ): """ Convert a list of matrix components to a symmetric 3x3 matrix. Inputs should be in the order xx, yy, zz, xy, yz, xz. Args: xx (float): xx component of the matrix. yy (float): yy component of the matrix. zz (float): zz component of the...
java
public static Matcher getWildcardMatcher(String str, String expr, boolean whole) { expr = expr.replaceAll("\\?",".?"); expr = expr.replaceAll("\\*",".*?"); if(whole) expr = "^"+expr+"$"; Pattern pattern = Pattern.compile(expr/*, Pattern.DOTALL*/); return pattern.m...
java
private void createDatabaseIfNotExist(boolean drop) throws URISyntaxException, IOException, ClientProtocolException { boolean exist = checkForDBExistence(); if (exist && drop) { dropDatabase(); exist = false; } if (!exist) { URI ur...
java
@RequirePOST public synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter String mode, @QueryParameter String from ) throws IOException, ServletException { fi...
python
def dns_resolve(self): """ Perform DNS resolution on the contained addresses. :return: """ new_addresses = [] for address in self.addresses: try: info = getaddrinfo(address[0], address[1], 0, SOCK_STREAM, IPPROTO_TCP) except gaierror: ...
python
def urlargs_replace_text_in_arg(urlargs, regexp_argname, text_old, text_new): """Analyze `urlargs' (URL CGI GET query arguments in string form) and for each occurrence of argument matching `regexp_argname' replace every substring `text_old' by `text_new'. Return the resulting new URL. ...
java
@Deprecated public WaitFileConditionBuilder file(String filePath) { FileCondition condition = new FileCondition(); condition.setFilePath(filePath); container.setCondition(condition); this.buildAndRun(); return new WaitFileConditionBuilder(condition, this); }
java
public TemplateBuilder parameter(String name, String value) { action.getParameter().put(name, value); return this; }
python
def vizread (descpath, descsection, tabpath, tabwidth=8, **kwargs): """Read a headerless tabular text file into a stream of Holders. Arguments: descpath The path of the table description ini file. descsection The section in the description file to use. tabpath The path to the act...
java
private LexToken rdReal(int tokline, int tokpos, int tokOffset) throws LexException { String floatSyntax = "Expecting <digits>[.<digits>][e<+-><digits>]"; String value = rdNumber(10); String fraction = null; String exponent = null; boolean negative = false; push(); if (ch == '.') { rdCh(); ...
java
@Override public StreamImpl stream() throws IOException { if (_stream == null) { _stream = new JniStream(this); } _stream.init(); return _stream; }
java
protected Set<CacheEntryTag> getTags(Element element) { final Object key = element.getObjectKey(); if (key instanceof TaggedCacheEntry) { return ((TaggedCacheEntry) key).getTags(); } final Object value = element.getObjectValue(); if (value instanceof TaggedCacheEntry...
java
@Override public List<CPOption> getCPOptions(int start, int end) { return cpOptionPersistence.findAll(start, end); }
java
public SDVariable scalarMax(SDVariable in, Number value) { return scalarMax(null, in, value); }
java
public void marshall(S3Source s3Source, ProtocolMarshaller protocolMarshaller) { if (s3Source == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(s3Source.getBucketName(), BUCKETNAME_BINDING); ...
java
private void process(Path dir, Path file, WatchEvent.Kind<?> evtType) throws TTException, IOException, InterruptedException { // LOGGER.info("Processing " + file.getFileName() + " with event " // + evtType); IFilelistenerWriteTrx trx = null; String rootPath = getListenerRootPath(...
java
public static String unquote(String string) { if (string.startsWith("'") && string.endsWith("'")) { string = string.substring(1, string.length() - 1); if ((string.indexOf("\\n") != -1) || (string.indexOf("\\r") != -1) || (string.indexOf("\\'") != -1) || (string.indexOf("\\\"") != -1) || (...
python
def git_check(): """ Check that all changes , besides versioning files, are committed :return: """ # check that changes staged for commit are pushed to origin output = local('git diff --name-only | egrep -v "^(pynb/version.py)|(version.py)$" | tr "\\n" " "', capture=True).str...
python
def _get_file_name(tlobject): """``ClassName -> class_name.html``.""" name = tlobject.name if isinstance(tlobject, TLObject) else tlobject # Courtesy of http://stackoverflow.com/a/1176023/4759433 s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) result = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower...
java
public void setLaunchPathSummaries(java.util.Collection<LaunchPathSummary> launchPathSummaries) { if (launchPathSummaries == null) { this.launchPathSummaries = null; return; } this.launchPathSummaries = new java.util.ArrayList<LaunchPathSummary>(launchPathSummaries); ...
java
protected void renderSelectTagAttributes(ResponseWriter rw, String clientId, String name, SelectMultiMenu menu) throws IOException { rw.writeAttribute("id", clientId, null); rw.writeAttribute("name", name, null); StringBuilder sb; String s; sb = new StringBuilder(20); // optimize int sb.append("form-con...
python
def joined(subset=None, show_ip=False, show_ipv4=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are up according to S...
java
public void decode(TypedValueDecoder tvd) throws IllegalArgumentException { char[] buf; int start, end; if (mInputStart >= 0) { // shared buffer, common case buf = mInputBuffer; start = mInputStart; end = start + mInputLen; } else { ...
java
public void processDocument(BufferedReader document, Wordsi wordsi) { try { // Handle the context header, if one exists. Context headers are // assumed to be the first line in a document and to contain an // integer specifying which line the focus word is on.. St...
python
def create_user(name, username, email, password, token_manager=None, app_url=defaults.APP_URL): """ create a new user with the specified name, username email and password """ headers = token_manager.get_access_token_headers...
java
public String getValue(String name) { return System.getProperty(name, _map.get(name)); }
java
@Nonnull public static ESuccess flush (@Nullable final Flushable aFlushable) { if (aFlushable != null) try { aFlushable.flush (); return ESuccess.SUCCESS; } catch (final NullPointerException ex) { // Happens if a java.io.FilterOutputStream is already closed!...
python
def get_news(self): '''Get all the news from first page''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=heade...
python
def scoped_to(self, scope): """ Context manager to switch scopes. """ previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
python
def invert_dependencies(targets): """ :API: public :return: the full graph of dependencies for `targets` and the list of roots. """ roots = set() inverted_deps = defaultdict(OrderedSet) # target -> dependent targets visited = set() path = OrderedSet() def invert(tgt): if tgt in path: path...