language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def apply_with_summary(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to `input_layer` and create a summary.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**... |
java | public <T> T read(Class<T> clazz, Name dn) {
return ldapTemplate.findByDn(dn, clazz);
} |
java | void writeSection(RecoverableUnitSectionImpl target, int unwrittenDataSize) throws InternalLogException
{
if (tc.isEntryEnabled())
Tr.entry(tc, "writeSection", new java.lang.Object[] { this, target, new Integer(unwrittenDataSize) });
// If the parent recovery log instance has experience... |
java | private void setSelectPositionX(int posX, int width) {
m_markerStyle.setLeft(posX, Unit.PX);
m_markerStyle.setWidth(width, Unit.PX);
m_overlayLeftStyle.setWidth(posX, Unit.PX);
m_overlayTopStyle.setLeft(posX, Unit.PX);
m_overlayTopStyle.setWidth(width, Unit.PX);
m_overl... |
java | @Override
@Deprecated
public void loadServerInstances(final String serverGroup, final AsyncCallback<List<ServerInstance>> callback) {
final List<ServerInstance> instancesOfGroup = new LinkedList<ServerInstance>();
loadHostsAndServerInstances(new SimpleCallback<List<HostInfo>>() {
@Ov... |
python | def popitem(self):
"""Remove and return the `(key, value)` pair least recently used that
has not already expired.
"""
with self.__timer as time:
self.expire(time)
try:
key = next(iter(self.__links))
except StopIteration:
... |
java | public static void removeEntry(final File zip, final String path) {
operateInPlace(zip, new InPlaceAction() {
public boolean act(File tmpFile) {
removeEntry(zip, path, tmpFile);
return true;
}
});
} |
python | def open(cls, typename):
"""Create an OMAPI open message with given typename.
@type typename: bytes
@rtype: OmapiMessage
"""
return cls(opcode=OMAPI_OP_OPEN, message=[(b"type", typename)], tid=-1) |
python | def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') |
python | def check_if_modified_since(self, dt, etag=None):
"""Validate If-Modified-Since with current request conditions."""
dt = dt.replace(microsecond=0)
if request.if_modified_since and dt <= request.if_modified_since:
raise SameContentException(etag, last_modified=dt) |
java | protected int add_child(int idx, IonValueLite child)
{
_isNullValue(false); // if we add children we're not null anymore
child.setContext(this.getContextForIndex(child, idx));
if (_children == null || _child_count >= _children.length) {
int old_len = (_children == null) ? 0 : _ch... |
java | public ExtViewQuery image(String url, Callback callback) {
if (!TextUtils.isEmpty(url) && view instanceof ImageView) {
Picasso.with(context).load(url).into((ImageView) view, callback);
}
return self();
} |
python | def urlinfo(self, domain, response_group = URLINFO_RESPONSE_GROUPS):
'''
Provide information about supplied domain as specified by the response group
:param domain: Any valid URL
:param response_group: Any valid urlinfo response group
:return: Traffic and/or content data of the d... |
java | private void readProjectProperties(Document cdp)
{
WorkspaceProperties props = cdp.getWorkspaceProperties();
ProjectProperties mpxjProps = m_projectFile.getProjectProperties();
mpxjProps.setSymbolPosition(props.getCurrencyPosition());
mpxjProps.setCurrencyDigits(props.getCurrencyDigits());
... |
java | private void setHeadersComplete() {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "completed headers have been received stream " + myID);
}
headersCompleted = true;
muxLink.setContinuationExpected(false);
} |
java | public String create(List<String> sortedIncludedHeaders, HashFunction hashFunction) {
// Add the method and uri
StringBuilder canonicalRequest = new StringBuilder();
canonicalRequest.append(method).append(NEW_LINE);
String canonicalUri = CANONICALIZE_PATH.apply(uri);
canonicalReq... |
java | private static Iterable<String> getAssociationTables(EntityClass entityClass) {
Iterable<Settable> association = filter(entityClass.getElements(),
and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
return transform(association, new Function<Settable, Str... |
python | def level(self, name, no=None, color=None, icon=None):
"""Add, update or retrieve a logging level.
Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
level, you... |
java | public Buffer readFrom(InputStream in) throws IOException {
readFrom(in, Long.MAX_VALUE, true);
return this;
} |
python | def is_newer_b(a, bfiles):
"""
check that all b files have been modified more recently than a
"""
if isinstance(bfiles, basestring):
bfiles = [bfiles]
if not op.exists(a): return False
if not all(op.exists(b) for b in bfiles): return False
atime = os.stat(a).st_mtime # modification... |
python | def make_entropy_col_consensus(bg_freqs):
"""Consensus according to maximal relative entropy term (MET).
For a given column i, choose the residue j with the highest relative
entropy term::
f_ij ln(f_ij/b_j)
where f_ij = column aa frequency, b_j = background aa frequency.
Source: http://b... |
java | private void checkReferenceEquality(Node n, String typeName, String fileName) {
if (n.getToken() == Token.SHEQ
|| n.getToken() == Token.EQ
|| n.getToken() == Token.SHNE
|| n.getToken() == Token.NE) {
JSType firstJsType = n.getFirstChild().getJSType();
JSType lastJsType = n.getLas... |
java | public static IntPoint Divide(IntPoint point1, IntPoint point2) {
IntPoint result = new IntPoint(point1);
result.Divide(point2);
return result;
} |
java | protected void init(
String userAdmin,
String userGuest,
String userExport,
String userDeletedResource,
String groupAdministrators,
String groupUsers,
String groupGuests) {
// check if all required user and group names are not null or empty
if (Cm... |
python | def populate(self, ticket=None):
"""
Populate the database with types retrieved from the AFIP.
If no ticket is provided, the most recent available one will be used.
"""
ticket = ticket or AuthTicket.objects.get_any_active('wsfe')
client = clients.get_client('wsfe', ticke... |
java | public Set<java.util.Map.Entry<String, T>> entrySet()
{
return lookupMap.entrySet();
} |
python | def cmvn(vec, variance_normalization=False):
""" This function is aimed to perform global cepstral mean and
variance normalization (CMVN) on input feature vector "vec".
The code assumes that there is one observation per row.
Args:
vec (array): input feature matrix
(size:(num... |
python | def make_sqlite_url(filename: str) -> str:
"""
Makes an SQLAlchemy URL for a SQLite database.
"""
absfile = os.path.abspath(filename)
return "sqlite://{host}/{path}".format(host="", path=absfile) |
python | def __refresh(self):
"""Update local knowledge of values (to be used to create new skeletal instances). MUST be called within
lock."""
raw_values = self.__get_values()
if not raw_values:
raise RefreshException('Point has no values')
# individual templates
tem... |
python | def current_revision(self):
"""
:return: The current :class:`revision.data.Revision`.
:rtype: :class:`revision.data.Revision`
"""
if self.current_index is None:
return None
if len(self.revisions) > self.current_index:
return self.revisions[self.cu... |
python | def get_jsapi_signature(self, noncestr, ticket, timestamp, url):
"""
获取 JSAPI 签名
https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/
:param noncestr: nonce string
:param ticket: JS-SDK ticket
:param timestamp: 时间戳
:param url: URL
:return: 签名
... |
java | public void addMetaBeanProperty(MetaBeanProperty mp) {
MetaProperty staticProperty = establishStaticMetaProperty(mp);
if (staticProperty != null) {
staticPropertyIndex.put(mp.getName(), mp);
} else {
SingleKeyHashMap propertyMap = classPropertyIndex.getNotNull(theCached... |
java | @Override
public double calculateExpectedDisagreement() {
ensureDistanceFunction();
if (coincidenceMatrix == null) {
coincidenceMatrix = CodingAnnotationStudy.countCategoryCoincidence(study);
}
if (study.getCategoryCount() <= 1) {
throw new InsufficientDataException("An ann... |
java | public static boolean nonEmptyIntersection(
Comparator<String> comparator, String[] first, String[] second) {
if (first == null || second == null || first.length == 0 || second.length == 0) {
return false;
}
for (String a : first) {
for (String b : second) {
if (comparator.compare(... |
python | def decompose(df, period=365, lo_frac=0.6, lo_delta=0.01):
"""Create a seasonal-trend (with Loess, aka "STL") decomposition of observed time series data.
This implementation is modeled after the ``statsmodels.tsa.seasonal_decompose`` method
but substitutes a Lowess regression for a convolution in its tren... |
java | public void valueUnbound( HttpSessionBindingEvent event )
{
if ( _log.isDebugEnabled() )
{
_log.debug( "The page flow stack is being unbound from the session." );
}
while ( ! isEmpty() )
{
PageFlowController jpf = pop( null ).getPageFlow();
... |
java | private static double shapiroWilkW(double[] x) {
Arrays.sort(x);
int n = x.length;
if(n<3) {
throw new IllegalArgumentException("The provided collection must have more than 2 elements.");
}
if (n > 5000) {
throw new IllegalArgumentException("The p... |
java | public static <T> Parser<T> longest(Parser<? extends T>... parsers) {
if (parsers.length == 0) return never();
if (parsers.length == 1) return parsers[0].cast();
return new BestParser<T>(parsers, IntOrder.GT);
} |
java | protected String findPattern(String strPattern, String text, int grp) {
Pattern pattern = Pattern.compile(strPattern, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(text);
if (matcher.find(0))
return matcher.group(grp);
return null;
} |
python | def _read_regpol_file(reg_pol_path):
'''
helper function to read a reg policy file and return decoded data
'''
returndata = None
if os.path.exists(reg_pol_path):
with salt.utils.files.fopen(reg_pol_path, 'rb') as pol_file:
returndata = pol_file.read()
return returndata |
python | def add_margins(df, vars, margins=True):
"""
Add margins to a data frame.
All margining variables will be converted to factors.
Parameters
----------
df : dataframe
input data frame
vars : list
a list of 2 lists | tuples vectors giving the
variables in each dimensi... |
java | public void startElement(
StylesheetHandler handler, String uri, String localName, String rawName, Attributes attributes)
throws org.xml.sax.SAXException
{
final String resultNS;
NamespaceAlias na = new NamespaceAlias(handler.nextUid());
setPropertiesFromAttributes(handler, rawName,... |
java | public static <INPUT extends Comparable<INPUT>> void executeLargeUpdates(Collection<INPUT> inputs, Consumer<List<INPUT>> consumer,
IntFunction<Integer> partitionSizeManipulations) {
Iterable<List<INPUT>> partitions = toUniqueAndSortedPartitions(inputs, partitionSizeManipulations);
for (List<INPUT> partition... |
java | protected void addViolation(MethodNode node, String message) {
addViolation((ASTNode) node, String.format(
"Violation in class %s. %s", node.getDeclaringClass().getNameWithoutPackage(), message
));
} |
java | @Override
public void afterCompletion(int status)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "afterCompletion : " + status + " : " + this);
// JPA 5.9.1 Container Responsibilities
// - After the JTA transaction has completed (either by tr... |
python | def night_mode(self):
"""bool: The speaker's night mode.
True if on, False if off, None if not supported.
"""
if not self.is_soundbar:
return None
response = self.renderingControl.GetEQ([
('InstanceID', 0),
('EQType', 'NightMode')
])
... |
java | private static void setValue(Object target, String field, Object value) {
// TODO: Should we do this for all numbers, not just '0'?
if ("0".equals(field)) {
if (!(target instanceof Collection)) {
throw new IllegalArgumentException(
"Cannot evaluate '0... |
python | def delete_item(TableName=None, Key=None, Expected=None, ConditionalOperator=None, ReturnValues=None, ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None, ConditionExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None):
"""
Deletes a single item in a table by primary key. You ... |
python | def __send_exc_clear(self, log_if_exc_set=None):
"""Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO
level.
"""
if not (log_if_exc_set is None or self.__send_exc is None):
logger.info(log_if_exc_set)
self.__send... |
python | def hash(buf, encoding="utf-8"):
"""
Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes
"""
if isins... |
java | public boolean canTrackerBeUsed(
String taskTracker, String trackerHost, TaskInProgress tip) {
synchronized (lockObject) {
return !tip.hasFailedOnMachine(trackerHost);
}
} |
java | private double computeQuantile(double ration, int totalCount) throws IllegalStateException, IllegalArgumentException {
if (ration <= 0.0D || ration >= 1.0D) {
throw new IllegalArgumentException("Expected ratio between 0 and 1 excluded: " + ration);
}
final double expectedCount = ration * totalCount;
// ... |
java | ContentValues toContentValues() {
ContentValues contentValues = new ContentValues();
mBuilder.fillContentValues(contentValues);
contentValues.put(JobStorage.COLUMN_NUM_FAILURES, mFailureCount);
contentValues.put(JobStorage.COLUMN_SCHEDULED_AT, mScheduledAt);
contentValues.put(Job... |
python | def retrieve_all_pages(api_endpoint, **kwargs):
"""
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator,
this method loads all pages into a single results list
:param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get`
:param kwa... |
python | def create_review(self, commit=github.GithubObject.NotSet, body=None, event=github.GithubObject.NotSet, comments=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/pulls/:number/reviews <https://developer.github.com/v3/pulls/reviews/>`_
:param commit: github.Commit.Commit
... |
java | @Override
public <T> long deleteObject(String name, T obj) throws CpoException {
return getCurrentResource().deleteObject( name, obj);
} |
java | @Nonnull
public static <T1, T2> LToSrtBiFunction<T1, T2> toSrtBiFunctionFrom(Consumer<LToSrtBiFunctionBuilder<T1, T2>> buildingFunction) {
LToSrtBiFunctionBuilder builder = new LToSrtBiFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
python | def std_hash(word, salt):
"""Generates a cryptographically strong (sha512) hash with this nodes
salt added."""
try:
password = word.encode('utf-8')
except UnicodeDecodeError:
password = word
word_hash = sha512(password)
word_hash.update(salt)
hex_hash = word_hash.hexdigest(... |
java | public static ConstraintViolationException instantiate(
final SerializationStreamReader streamReader) throws SerializationException {
final String message = streamReader.readString();
@SuppressWarnings("unchecked")
final Set<ConstraintViolation<?>> set = (Set<ConstraintViolation<?>>) streamReader.read... |
python | def _add_to_graph(self, term, parents):
"""
Add a term and all its children to ``graph``.
``parents`` is the set of all the parents of ``term` that we've added
so far. It is only used to detect dependency cycles.
"""
if self._frozen:
raise ValueError(
... |
python | def cloud_cover_to_irradiance_clearsky_scaling(self, cloud_cover,
method='linear',
**kwargs):
"""
Estimates irradiance from cloud cover in the following steps:
1. Determine clear sky GHI using ... |
python | def get_repo_info(repo_name, profile='github', ignore_cache=False):
'''
Return information for a given repo.
.. versionadded:: 2016.11.0
repo_name
The name of the repository.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. co... |
java | private PublishDocumentResponse publishDocument(PublishDocumentRequest request) {
checkNotNull(request, "request should not be null.");
checkNotNull(request.getDocumentId(), "documentId should not be null.");
InternalRequest internalRequest = this.createRequest(HttpMethodName.PUT, request, DOC, ... |
python | def translate_poco_step(self, step):
"""
处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤
Parameters
----------
step 一个完整的操作,如click
prev_step 前一个步骤,应该是截图
Returns
-------
"""
ret = {}
prev_step = self._steps[-1]
if prev_step... |
python | def StripTypeInfo(rendered_data):
"""Strips type information from rendered data. Useful for debugging."""
if isinstance(rendered_data, (list, tuple)):
return [StripTypeInfo(d) for d in rendered_data]
elif isinstance(rendered_data, dict):
if "value" in rendered_data and "type" in rendered_data:
retu... |
python | def init_menu():
"""Initialize menu before first request."""
# Register breadcrumb root
item = current_menu.submenu('breadcrumbs.settings')
item.register('', _('Account'))
item = current_menu.submenu('breadcrumbs.{0}'.format(
current_app.config['SECURITY_BLUEPRINT_NAME']))
if current_ap... |
python | def _W(self, mu, weights, y=None):
"""
compute the PIRLS weights for model predictions.
TODO lets verify the formula for this.
if we use the square root of the mu with the stable opt,
we get the same results as when we use non-sqrt mu with naive opt.
this makes me think... |
python | def add_input_variable(self, var):
"""Adds the argument variable as one of the input variable"""
assert(isinstance(var, Variable))
self.input_variable_list.append(var) |
python | def load_obj(self, jref, getter=None, parser=None):
""" load a object(those in spec._version_.objects) from a JSON reference.
"""
obj = self.__resolver.resolve(jref, getter)
# get root document to check its swagger version.
tmp = {'_tmp_': {}}
version = utils.get_swagger... |
python | def insert(self, value, index):
'''Accepts a :value: and :index: parameter and inserts
a new key, value member at the desired index.
Note: Inserting with a negative index will have the following behavior:
>>> l = [1, 2, 3, 4]
>>> l.insert(-1, 5)
>>> l
[1, 2, 3, 5... |
python | def _format_extname(self, ext):
"""Pretty print given extension name and number tuple."""
if ext is None:
outs = ext
else:
outs = '{0},{1}'.format(ext[0], ext[1])
return outs |
python | def get_scratch_predictions(self, path_to_scratch, results_dir, scratch_basename='scratch', num_cores=1,
exposed_buried_cutoff=25, custom_gene_mapping=None):
"""Run and parse ``SCRATCH`` results to predict secondary structure and solvent accessibility.
Annotations are sto... |
java | public static List<BitextRule> getBitextRules(Language source,
Language target, File externalBitextRuleFile) throws IOException, ParserConfigurationException, SAXException {
List<BitextRule> bRules = new ArrayList<>();
//try to load the bitext pattern rules for the language...
BitextPatternRuleLoader ... |
java | public static Date adddDaysToCurrentDate(int numberOfDays) {
Date date = new Date();
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.add(Calendar.DATE, numberOfDays);
return instance.getTime();
} |
java | public long distance(String a, String b)
{
Long[] itemA = get(a);
if (itemA == null) return Long.MAX_VALUE / 3;
Long[] itemB = get(b);
if (itemB == null) return Long.MAX_VALUE / 3;
return ArrayDistance.computeAverageDistance(itemA, itemB);
} |
java | @Override
public SortedSet<String> getAttributeSortedStringSet(String name) {
try {
TreeSet<String> attrSet = new TreeSet<String>();
LdapUtils.collectAttributeValues(originalAttrs, name, attrSet, String.class);
return attrSet;
}
catch (NoSuchAttributeException e) {
// The attribute does not exist - c... |
java | public final Node getPropertyNode(String propertyName) {
Property p = getSlot(propertyName);
return p == null ? null : p.getNode();
} |
python | def _dcm_to_q(self, dcm):
"""
Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array
"""
assert(dcm.shape == (3, 3))
q = np.zeros(4)... |
python | def make_epsilons(matrix, seed, correlation):
"""
Given a matrix N * R returns a matrix of the same shape N * R
obtained by applying the multivariate_normal distribution to
N points and R samples, by starting from the given seed and
correlation.
"""
if seed is not None:
numpy.random.... |
python | def regexp_extract(str, pattern, idx):
r"""Extract a specific group matched by a Java regex, from the specified string column.
If the regex did not match, or the specified group did not match, an empty string is returned.
>>> df = spark.createDataFrame([('100-200',)], ['str'])
>>> df.select(regexp_extr... |
java | private void renderItemValue(MenuItem item) {
// only proceed if there's a label to be updated..
Label lblForVal = itemIdToLabel.get(item.getId());
if (lblForVal == null) return;
//
// First we use the visitor again to call the right method in the visitor based on it's type.
... |
java | public boolean isBound(@NonNull BeaconConsumer consumer) {
synchronized(consumers) {
// Annotation doesn't guarantee we get a non-null, but raising an NPE here is excessive
//noinspection ConstantConditions
return consumer != null && consumers.get(consumer) != null &&
... |
java | @Override
public int compareTo(Object arg0) {
Interval that = (Interval)arg0;
return this.bounds.compareTo(that.getBounds());
} |
java | public KnowledgeRuntimeManager newRuntimeManager(KnowledgeRuntimeManagerType type) {
RuntimeManager runtimeManager;
final String identifier = _identifierRoot + IDENTIFIER_COUNT.incrementAndGet();
final ClassLoader origTCCL = Classes.setTCCL(_classLoader);
try {
runtimeManager... |
java | @Override
public boolean add(T obj) {
if (obj.getDRIndex() != null)
throw new IllegalArgumentException("Cannot insert an object into a Store which is already in a store (drIndex=" + obj.getDRIndex() + ")");
obj.setDRIndex(items.size());
return items.add(obj);
} |
java | public static ImageIcon getHelpIcon() {
if (helpIcon == null) {
helpIcon = DisplayUtils.getScaledIcon(new ImageIcon(ExtensionHelp.class.getResource("/resource/icon/16/201.png")));
}
return helpIcon;
} |
python | def getContactUIDForUser(self):
"""Get the UID of the user associated with the authenticated user
"""
membership_tool = api.get_tool("portal_membership")
member = membership_tool.getAuthenticatedMember()
username = member.getUserName()
r = self.portal_catalog(
... |
java | protected final PrcAccEntityWithSubaccCreate<RS, IHasId<Object>, Object>
createPutPrcAccEntityWithSubaccCreate(
final Map<String, Object> pAddParam) throws Exception {
PrcAccEntityWithSubaccCreate<RS, IHasId<Object>, Object> proc =
new PrcAccEntityWithSubaccCreate<RS, IHasId<Object>, Object>();
... |
python | def get_unicode_property(self, i):
"""Get Unicode property."""
index = i.index
prop = []
value = []
try:
c = next(i)
if c.upper() in _ASCII_LETTERS:
prop.append(c)
elif c != '{':
raise SyntaxError("Unicode prope... |
java | public boolean actionSupportsHttpMethod(String actionMethodName, HttpMethod httpMethod) {
if (restful()) {
return restfulActionSupportsHttpMethod(actionMethodName, httpMethod) || standardActionSupportsHttpMethod(actionMethodName, httpMethod);
} else {
return standardActionSupport... |
python | def parse_compound_list(path, compounds):
"""Parse a structured list of compounds as obtained from a YAML file
Yields CompoundEntries. Path can be given as a string or a context.
"""
context = FilePathContext(path)
for compound_def in compounds:
if 'include' in compound_def:
f... |
python | def list_build_configurations_for_product_version(product_id, version_id, page_size=200, page_index=0, sort="", q=""):
"""
List all BuildConfigurations associated with the given ProductVersion
"""
data = list_build_configurations_for_project_raw(product_id, version_id, page_size, page_index, sort, q)
... |
python | def transform_member(self, node, results):
"""Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module.
"""
mod_member = results.get("mod_member")
pref = mod_member.prefix
member = results.get... |
python | def get_subs(subs_file='subreddits.txt', blacklist_file='blacklist.txt') -> List[str]:
"""
Get subs based on a file of subreddits and a file of blacklisted subreddits.
:param subs_file: List of subreddits. Each sub in a new line.
:param blacklist_file: List of blacklisted subreddits. Each sub in a new... |
python | def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs)) |
python | def run(self, schedule_type, lookup_id, **kwargs):
"""
Loads Schedule linked to provided lookup
"""
log = self.get_logger(**kwargs)
log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id))
task_run = QueueTaskRun()
task_run.task_id = self.request.id or uuid4()
... |
java | static byte [] asHostData(NavigableSet<ChannelSpec> specs)
throws JSONException, IllegalArgumentException {
JSONStringer js = new JSONStringer();
js.array();
for (ChannelSpec spec: specs) {
js.value(spec.asJSONValue());
}
js.endArray();
return js.t... |
java | public static Class<?> resolveArgument(Type genericType, Class<?> targetType) {
Class<?>[] arguments = resolveArguments(genericType, targetType);
if (arguments == null)
return Unknown.class;
if (arguments.length != 1)
throw new IllegalArgumentException("Expected 1 type a... |
python | def get_form(self, id=None, *args, **kwargs):
"""Find form by ID, as well as standard BeautifulSoup arguments.
:param str id: Form ID
:return: BeautifulSoup tag if found, else None
"""
if id:
kwargs['id'] = id
form = self.find(_form_ptn, *args, **kwargs)
... |
python | def export(vault_client, opt):
"""Export contents of a Secretfile from the Vault server
into a specified directory."""
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for resource in ctx.resources():
resource.export(opt.directory) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.