language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String tagStyle(String tag, String style, String... content) {
return openTagStyle(tag, style, content) + closeTag(tag);
} |
java | @Override
public void componentResized(ComponentEvent event) {
final int SIZE = getWidth() < getHeight() ? getWidth() : getHeight();
setPreferredSize(new java.awt.Dimension(SIZE, SIZE));
if (SIZE < getMinimumSize().width || SIZE < getMinimumSize().height) {
setPreferredSize(getM... |
python | def convert_tags_to_dict(item):
"""
Convert AWS inconvenient tags model of a list of {"Key": <key>, "Value": <value>} pairs
to a dict of {<key>: <value>} for easier querying.
This returns a proxied object over given item to return a different tags format as the tags
attribute is read-only and we ca... |
python | def dictmerge(a, b, name=None):
""" Deeply merge two ``dict``s that consist of lists, dicts, and scalars.
This function (recursively) merges ``b`` INTO ``a``, does not copy any values, and returns ``a``.
based on https://stackoverflow.com/a/15836901/5042831
NOTE: tuples and arbitrary objects are NOT ha... |
python | def color_text_boxes(ax, labels, colors, color_arrow=True):
"""Color text boxes.
Instead of this function, one can pass annotate_kwargs and plot_kwargs to
plot_line_ids function.
"""
assert len(labels) == len(colors), \
"Equal no. of colors and lables must be given"
boxes = ax.findobj(m... |
python | def getDocumentIDs(aleph_search_result, number_of_docs=-1):
"""
Get IDs, which can be used as parameters for other functions.
Args:
aleph_search_result (dict): returned from :func:`searchInAleph`
number_of_docs (int, optional): how many :class:`DocumentID` from set
... |
java | @Override
public void decode(final FacesContext context) {
if (context == null) {
throw new NullPointerException();
}
if ((context.isPostback() && !isOnPostback()) || !isRendered()) {
return;
}
ActionEvent e = new ActionEvent(this);
PhaseId p... |
java | public void
restore() {
if (saved_pos < 0) {
throw new IllegalStateException("no previous state");
}
byteBuffer.position(saved_pos);
byteBuffer.limit(saved_end);
saved_pos = -1;
saved_end = -1;
} |
java | void renameDataFile(boolean wasNio) {
writeLock.lock();
try {
if (fa.isStreamElement(fileName + ".new")) {
deleteFile(wasNio);
fa.renameElement(fileName + ".new", fileName);
}
} finally {
writeLock.unlock();
}
} |
python | def _independent_lattice(self, shape, lattice=None):
""" Helper to construct the list of nodes and edges. """
I, J = shape
if lattice is not None:
end_I = min(I, max(lattice[..., 3])) - 1
end_J = min(J, max(lattice[..., 4])) - 1
unvisited_nodes = deque([(i, j... |
java | public ServiceFuture<Void> scaleAsync(String resourceGroupName, String accountName, String streamingEndpointName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(scaleWithServiceResponseAsync(resourceGroupName, accountName, streamingEndpointName), serviceCallback);
} |
java | public void write(String s) throws IOException
{
int n = s.length();
for (int i = 0; i < n; i++)
{
m_os.write(s.charAt(i));
}
} |
java | private void createVersion(Node fileNode, InputStream inputStream, String autoVersion, List<String> mixins) throws RepositoryException
{
if (!fileNode.isNodeType(VersionHistoryUtils.MIX_VERSIONABLE))
{
if (fileNode.canAddMixin(VersionHistoryUtils.MIX_VERSIONABLE))
{
fi... |
java | public final <C extends Collection<? super E>> C copyInto(C collection) {
checkNotNull(collection);
if (iterable instanceof Collection) {
collection.addAll(Collections2.cast(iterable));
} else {
for (E item : iterable) {
collection.add(item);
}
}
return collection;
} |
python | def _collect_metrics(repo, path, recursive, typ, xpath, branch):
"""Gather all the metric outputs.
Args:
path (str): Path to a metric file or a directory.
recursive (bool): If path is a directory, do a recursive search for
metrics on the given path.
typ (str): The type of me... |
python | def prune(self, node_thres, edge_thres, paths, color_nodes_by_selftime):
"""Prune the profile"""
# compute the prune ratios
for function in compat_itervalues(self.functions):
try:
function.weight = function[TOTAL_TIME_RATIO]
except UndefinedEvent:
... |
java | private static ClassNode adjustWithTraits(final MethodNode directMethodCallCandidate, final ClassNode receiver, final ClassNode[] args, final ClassNode returnType) {
if (directMethodCallCandidate instanceof ExtensionMethodNode) {
ExtensionMethodNode emn = (ExtensionMethodNode) directMethodCallCandid... |
java | protected double quantile(double p, int xmin, int xmax) {
while (xmax - xmin > 1) {
int xmed = (xmax + xmin) / 2;
if (cdf(xmed) > p) {
xmax = xmed;
} else {
xmin = xmed;
}
}
if (cdf(xmin) >= p)
return xm... |
java | public static boolean isPathContained(List<String> allowedPaths, String targetPath) {
if (allowedPaths == null || allowedPaths.isEmpty() || targetPath == null) {
return false;
}
//Remove trailing slashes, if applicable
if (!targetPath.isEmpty() &&
targetPath.cha... |
python | def urlparse(url):
"""Parse the URL in a Python2/3 independent fashion.
:param str url: The URL to parse
:rtype: Parsed
"""
value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url
parsed = _urlparse.urlparse(value)
path, query = parsed.path, parsed.query
hostname = parsed.hostna... |
python | def get_insert_idx(pos_dict, name):
"Return the position to insert a given function doc in a notebook."
keys,i = list(pos_dict.keys()),0
while i < len(keys) and str.lower(keys[i]) < str.lower(name): i+=1
if i == len(keys): return -1
else: return pos_dict[keys[i]] |
java | public static String unicodeUTF8mb4String(String s) {
if (Strings.isNullOrEmpty(s)) return "";
int len = s.length();
StringBuilder sbd = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (c > '\u9fa5') { //非正常汉字范围
if (c >= '\uff00' && c <= '\uffef') { /... |
java | private int getPosAfterModifier(int startAt, AnalyzedTokenReadings[] tokens) {
if ((startAt + 1) < tokens.length && MODIFIERS.contains(tokens[startAt].getToken())) {
startAt++;
}
if ((startAt + 1) < tokens.length && (StringUtils.isNumeric(tokens[startAt].getToken()) || tokens[startAt].hasPosTag("ZAL")... |
python | def group(iterable, key=lambda ele: ele):
""" Groups an iterable by a specified attribute, or using a specified key access function. Returns tuples of grouped elements.
>>> dogs = [Dog('gatsby', 'Rruff!', 15), Dog('william', 'roof', 12), Dog('edward', 'hi', 15)]
>>> groupby(dogs, 'weight')
[(Dog('gats... |
java | public final void setTypeName(final String typeName) {
if (typeName == null) {
type = LOOKING_AT;
} else if (typeName.equalsIgnoreCase(TYPES[0])) {
type = MATCHES;
} else if (typeName.equalsIgnoreCase(TYPES[1])) {
type = LOOKING_AT;
} else if (t... |
java | protected void add(IIsotope isotope) {
Integer atomicNum = isotope.getAtomicNumber();
assert atomicNum != null;
List<IIsotope> isotopesForElement = isotopes[atomicNum];
if (isotopesForElement == null) {
isotopesForElement = new ArrayList<>();
isotopes[atomicNum] =... |
java | public static void bindComponent(final AbstractBinder binder, final Injector injector, final Class<?> type,
final boolean hkManaged, final boolean singleton) {
if (hkManaged) {
optionalSingleton(
binder.bindAsContract(type),
... |
java | @Deprecated
public static <T> BiRecordGetter<T, RuntimeException> createBiRecordGetterByTargetClass(final Class<? extends T> targetClass) {
if (Object[].class.isAssignableFrom(targetClass)) {
return new BiRecordGetter<T, RuntimeException>() {
@Override
public... |
java | @Override
public void setup(Context context)
throws IOException ,InterruptedException {
this.context = context;
inputLabels = context.getConfiguration().getStrings(SimpleJob.BEFORE_SUMMARIZER_OUTPUT_LABELS);
boolean label =
context.getConfiguration().getStrings(Si... |
java | public <T> T getLocal (Class<T> key)
{
for (Object attr : _locattrs) {
if (key.isInstance(attr)) {
return key.cast(attr);
}
}
return null;
} |
java | private ODocument getEdgeWithPossibleId(String start, String end, List<String> ids) {
List<ODocument> edges = getEdgesBetweenModels(start, end);
for (ODocument edge : edges) {
if (ids.contains(OrientModelGraphUtils.getIdFieldValue(edge))) {
return edge;
}
... |
python | def data_find(data, path):
"""Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elm = [
el
for el in data
if isinstance(el, (tuple, list)) and el[0] == path_parts[0]
... |
python | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Alert
for i in self.stats:
ifrealname = i['interface_name'].split(':')[0]
# Convert rate in bps ( to be ... |
python | def maintenance_sleeper(api, response, sleep=300):
"""
Pauses the execution if sevenbridges api is under maintenance.
:param api: Api instance.
:param response: requests.Response object.
:param sleep: Time to sleep in between the requests.
"""
while response.status_code == 503:
logge... |
python | def return_period_from_string(arg):
"""
Takes a string such as "days=1,seconds=30" and strips the quotes
and returns a dictionary with the key/value pairs
"""
period = {}
if arg[0] == '"' and arg[-1] == '"':
opt = arg[1:-1] # remove quotes
else:
opt = arg
for o in opt... |
python | def p_parallelblock(self, p):
'parallelblock : FORK block_statements JOIN'
p[0] = ParallelBlock(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
python | def element_to_extension_element(element):
"""
Convert an element into a extension element
:param element: The element instance
:return: An extension element instance
"""
exel = ExtensionElement(element.c_tag, element.c_namespace,
text=element.text)
exel.attrib... |
java | final void closeChildWrappers()
{
TraceComponent tc = getTracer();
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
// Close any child wrappers in the child wrapper list.
if (childWrappers != null && !childWrappers.isEmpty()) {
if (isTraceOn && tc.isDe... |
java | public final ClassTextInfo createClassInfo(@NotNull final Class<?> clasz, @NotNull final Locale locale,
@NotNull final Class<? extends Annotation> annotationClasz) {
Contract.requireArgNotNull("clasz", clasz);
Contract.requireArgNotNull("locale", locale);
Contract.requireArgNot... |
java | public void writeDialog() throws IOException {
if (isForwarded()) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_START_WRITE_LIST_1, getListId()));
}
JspWriter out = getJsp().getJspContext().getOut();
... |
python | def _DoSubstitute(args, context, callback, trace):
"""Variable substitution, i.e. {foo}
We also implement template formatters here, i.e. {foo|template bar} as well
as {.template FOO} for templates that operate on the root of the data dict
rather than a subtree.
"""
name, formatters = args
if ... |
python | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_fabric_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "o... |
python | def mode(self, target, *data):
"""set user or channel mode"""
self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True) |
python | def append_cookie(self, cookie, name, payload, typ, domain=None, path=None,
timestamp="", max_age=0):
"""
Adds a cookie to a SimpleCookie instance
:param cookie:
:param name:
:param payload:
:param typ:
:param domain:
:param path:
... |
java | public void putEDBObjectEntry(String key, Object value, String type) {
put(key, new EDBObjectEntry(key, value, type));
} |
python | def construct_sign_and_send_raw_middleware(private_key_or_account):
"""Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.Loca... |
java | public void writeSmallLongArray( long[] values ) {
int byteSize = values.length * 8 + 1;
this.addUnsignedByte( ( short ) values.length );
doWriteLongArray( values, byteSize );
} |
python | def close(self):
"""Close the tough connection.
You are allowed to close a tough connection by default
and it will not complain if you close it more than once.
You can disallow closing connections by setting
the closeable parameter to something false. In this case,
clo... |
python | def _create_temporary_projects(enabled_regions, args):
"""
Creates a temporary project needed to build an underlying workflow
for a global workflow. Returns a dictionary with region names as keys
and project IDs as values
The regions in which projects will be created can be:
i. regions specifie... |
java | public ExternalID getSeasonExternalID(int tvID, int seasonNumber, String language) throws MovieDbException {
return tmdbSeasons.getSeasonExternalID(tvID, seasonNumber, language);
} |
python | def update(self, response, **kwargs):
'''
If a record matching the instance already exists in the database, update
both the column and venue column attributes, else create a new record.
'''
response_cls = super(
LocationResponseClassLegacyAccessor, self)._get_instance... |
java | public static int deepHashCode(Object obj)
{
Set<Object> visited = new HashSet<>();
LinkedList<Object> stack = new LinkedList<>();
stack.addFirst(obj);
int hash = 0;
while (!stack.isEmpty())
{
obj = stack.removeFirst();
if (obj == null || visi... |
java | public void startElement(
String elementNamespaceURI,
String elementLocalName,
String elementName)
throws SAXException
{
if (m_needToCallStartDocument)
startDocumentInternal();
// time to fire off startlement event.
if (m_tracer != null) {
su... |
java | public static IBlockState ParseBlockType( String s )
{
if( s == null )
return null;
Block block = (Block)Block.REGISTRY.getObject(new ResourceLocation( s ));
if( block instanceof BlockAir && !s.equals("air") ) // Minecraft returns BlockAir when it doesn't recognise the string
... |
java | public static Stream<MutableLongTuple> stream(
Order order, LongTuple min, LongTuple max)
{
if (order == null)
{
return null;
}
Utils.checkForEqualSize(min, max);
MutableLongTuple localMin = LongTuples.copy(min);
MutableLongTuple localMax ... |
python | def zrange(key, start, stop, host=None, port=None, db=None, password=None):
'''
Get a range of values from a sorted set in Redis by index
CLI Example:
.. code-block:: bash
salt '*' redis.zrange foo_sorted 0 10
'''
server = _connect(host, port, db, password)
return server.zrange(ke... |
python | def aggregation_not_used_text_element(feature, parent):
"""Retrieve reference title header string from definitions."""
_ = feature, parent # NOQA
header = aggregation_not_used_text['string_format']
return header.capitalize() |
python | def get_fixed_argv(self): # pragma: no cover
"""Get proper arguments for re-running the command.
This is primarily for fixing some issues under Windows.
First, there was a bug in Windows when running an executable
located at a path with a space in it. This has become a
non-iss... |
java | boolean left(float[] a, float[] b, float[] c) {
float u1 = b[0] - a[0];
float v1 = b[2] - a[2];
float u2 = c[0] - a[0];
float v2 = c[2] - a[2];
return u1 * v2 - v1 * u2 < 0;
} |
java | protected String getBinding(ProfileRequestContext<?, ?> context) {
SAMLBindingContext samlBinding = this.samlBindingContextLookupStrategy.apply(context);
return samlBinding != null ? samlBinding.getBindingUri() : null;
} |
java | protected void storeReference(Object obj) {
refMap.put(new IdentityWrapper(obj), Short.valueOf(refId++));
} |
python | def one_of(*validators):
"""Returns a validator function that succeeds only if the input passes at least one of the provided validators.
:param callable validators: the validator functions
:returns: a function which returns True its input passes at least one of the validators, and raises TypeError
... |
python | def getInfo(self):
"""
Returns a DevInfo instance, a named tuple with the following items:
- bustype: one of BUS_USB, BUS_HIL, BUS_BLUETOOTH or BUS_VIRTUAL
- vendor: device's vendor number
- product: device's product number
"""
devinfo = _hidraw_devinfo()
... |
python | async def msetup(self, text_channel):
"""Creates the gui
Args:
text_channel (discord.Channel): The channel for the embed ui to run in
"""
if self.mready:
logger.warning("Attempt to init music when already initialised")
return
if self.state !... |
python | def get_pretrained_file_names(embedding_name=None):
"""Get valid token embedding names and their pre-trained file names.
To load token embedding vectors from an externally hosted pre-trained token embedding file,
such as those of GloVe and FastText, one should use
`mxnet.contrib.text.embedding.create(... |
java | @Override
protected void handleTransliterate(Replaceable text,
Position pos, boolean incremental) {
int start = pos.start;
int limit = pos.limit;
StringBuilder buf = new StringBuilder(prefix);
int prefixLen = prefix.length();
boolean re... |
java | @Override
public void actionCommit() {
List<Throwable> errors = new ArrayList<Throwable>();
try {
// if new create it first
if (m_group.getId() == null) {
CmsGroup newGroup = getCms().createGroup(
m_paramOufqn + m_group.getSimpleName(),
... |
python | def connection(self, name=None):
"""return a named connection.
This function will return a named connection by either finding one
in its pool by the name or creating a new one. If no name is given,
it will use the name of the current executing thread as the name of
the connecti... |
python | def extract_blocking(obj):
"""Extract index and watch from :class:`Blocking`
Parameters:
obj (Blocking): the blocking object
Returns:
tuple: index and watch
"""
if isinstance(obj, tuple):
try:
a, b = obj
except:
raise TypeError("Not a Blocking... |
python | def get_bug_simple(self, bugid):
"""
Get a single bug object. Similar to python-bugzilla's getbugsimple().
param bugid: integer, a bug's number.
returns: deferred that when fired returns an AttrDict representing this
bug.
"""
payload = {'ids': bugid}
... |
java | public void setupCellPositoin(final CellPosition address) {
ArgUtils.notNull(address, "address");
setupCellPositoin(address.getRow(), address.getColumn());
} |
python | def video_time_to_gyro_sample(self, t):
"""Convert video time to gyroscope sample index and interpolation factor
Parameters
-------------------
t : float
Video timestamp
Returns
--------------------
n : int
Sample index that precedes t
... |
python | def bind_handler(self, svc_ref):
"""
Called if a command service has been found.
Registers the methods of this service.
:param svc_ref: A reference to the found service
:return: True if the commands have been registered
"""
if svc_ref in self._bound_references:
... |
java | static boolean isFieldUnitIgnored(String pattern, int field) {
int fieldLevel = CALENDAR_FIELD_TO_LEVEL[field];
int level;
char ch;
boolean inQuote = false;
char prevCh = 0;
int count = 0;
for (int i = 0; i < pattern.length(); ++i) {
ch = pattern.char... |
java | public SyncInfo getActivitySyncInfo() {
// The overview of this method is
// 1. setup a source of event
// 2. Filter based on the paths associated with this mountId
// 3. Build History for each of the syncPoint
// 4. If heurstics function returns sync, then we sync the syncPoint
if (mPollingThr... |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "skipCount", scope = GetRenditions.class)
public JAXBElement<BigInteger> createGetRenditionsSkipCount(BigInteger value) {
return new JAXBElement<BigInteger>(_GetTypeChildrenSkipCount_QNAME,
BigInteger.class, GetRenditio... |
python | def open_dxfile(dxid, project=None, mode=None, read_buffer_size=dxfile.DEFAULT_BUFFER_SIZE):
'''
:param dxid: file ID
:type dxid: string
:rtype: :class:`~dxpy.bindings.dxfile.DXFile`
Given the object ID of an uploaded file, returns a remote file
handler that is a Python file-like object.
E... |
python | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = po... |
java | private Class<?> getClassImpl(final String name) throws UtilEvalError {
Class<?> c = null;
// Check the cache
if (this.classCache.containsKey(name))
return this.classCache.get(name);
// Unqualified (simple, non-compound) name
final boolean unqualifiedName = !Name.isCo... |
python | def deploy_config(model, initial_instance_count, instance_type, endpoint_name=None, tags=None):
"""Export Airflow deploy config from a SageMaker model
Args:
model (sagemaker.model.Model): The SageMaker model to export the Airflow config from.
instance_type (str): The EC2 instance type to deploy... |
java | private void initShowAnimation(TypedArray attrs) {
int index = R.styleable.ActionButton_show_animation;
if (attrs.hasValue(index)) {
int animResId = attrs.getResourceId(index, Animations.NONE.animResId);
showAnimation = Animations.load(getContext(), animResId);
LOGGER.trace("Initialized Action Button show ... |
python | def set_prev_freeness(self, is_free):
"""
Sets (or unsets) the flag controlling whether the previous chunk is free.
:param is_free: if True, sets the previous chunk to be free; if False, sets it to be allocated
"""
level = silence_logger()
size_field = self.state.memory.... |
java | public List<Group> getGroups(int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "groups");
return (response.readEntity(new GenericType<List<Group>>() {}));
} |
java | public static <T, U extends InputStream> T withStream(U stream, @ClosureParams(value=FirstParam.class) Closure<T> closure) throws IOException {
try {
T result = closure.call(stream);
InputStream temp = stream;
stream = null;
temp.close();
return resu... |
java | public void addSplitsForSha1() {
Validate.notNull(tableOperations, "tableOperations must not be null");
String hexadecimal = "123456789abcde";
SortedSet<Text> edgeSplits = new TreeSet<>();
SortedSet<Text> textSplits = new TreeSet<>();
Collection<Text> existingEdgeSplits = null;
... |
java | public JobStatus withNewEventId() {
return new JobStatus(jobId, description, state, Double.NaN, status, getNextEventId());
} |
python | def add_crosshair_to_image(fname, opFilename):
""" convert an image by adding a cross hair """
im = Image.open(fname)
draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=(255, 255, 255))
draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255))
del draw
im.save(opFilename) |
python | def save(self, *args, **kwargs):
""" custom save method to update counts """
# the following lines determines if the comment is being created or not
# in case the comment exists the pk attribute is an int
created = type(self.pk) is not int
super(UpdateCountsMixin, self).save(*ar... |
python | def set(self, quote_id, customer_data, store_view=None):
"""
Add customer information into a shopping cart
:param quote_id: Shopping cart ID (quote ID)
:param customer_data, dict of customer details, example
{
'firstname': 'testFirstname',
'la... |
java | public String getAccessModifier()
{
if ( _fieldDecl == null )
return "";
Collection<Modifier> modifiers = _fieldDecl.getModifiers();
if (modifiers.contains(Modifier.PRIVATE))
return "private";
if (modifiers.contains(Modifier.PROTECTED))
re... |
python | def get_bank(self, *args, **kwargs):
"""Pass through to provider BankLookupSession.get_bank"""
# Implemented from kitosid template for -
# osid.resource.BinLookupSession.get_bin
return Bank(
self._provider_manager,
self._get_provider_session('bank_lookup_session')... |
java | @Override
public V getBest(String s, int offset, int length) {
return getBest(0, s, offset, length);
} |
java | private DevVarLongStringArray subcribeIDLInEventString(final String eventTypeAndIDL, final String deviceName,
final String objName) throws DevFailed {
// event name like "idl5_archive" or "archive"
String event = eventTypeAndIDL;
int idl... |
java | @javax.annotation.Nullable
synchronized ViewData getView(View.Name viewName, Clock clock, State state) {
MutableViewData view = getMutableViewData(viewName);
return view == null ? null : view.toViewData(clock.now(), state);
} |
python | def visit_Assign(self, node):
"""
Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passman... |
python | def handle_nextPageTemplate(self, pt):
'''
if pt has also templates for even and odd page convert it to list
'''
has_left_template = self._has_template_for_name(pt + '_left')
has_right_template = self._has_template_for_name(pt + '_right')
if has_left_template and has_rig... |
java | public void setActionSequence (String action)
{
// sanity check
if (action == null) {
log.warning("Refusing to set null action sequence " + this + ".", new Exception());
return;
}
// no need to noop
if (action.equals(_action)) {
return;
... |
python | def filename(self):
"""Filename of the attachment, without the full 'attachment' path."""
if self.value and 'value' in self._json_data and self._json_data['value']:
return self._json_data['value'].split('/')[-1]
return None |
python | def split_content_version(self):
"""
Remove and return the version(s) from the cached content. First the
internal version, and if versioning is activated, the template one.
And finally save the content, but only if all versions match.
The content saved is the encoded one (if "com... |
java | public static String getWindowsVisualStyle() {
String style = UIManager.getString("win.xpstyle.name");
if (style == null) {
// guess the name of the current XPStyle
// (win.xpstyle.colorName property found in awt_DesktopProperties.cpp in
// JDK source)
sty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.