language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public boolean containsKey(Object key)
{
purge();
Entry entry = getEntry(key);
if (entry == null) return false;
return entry.getValue() != null;
} |
python | def _fft_convolve_gpu(data_g, h_g, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False):
""" fft convolve for gpu buffer
"""
assert_bufs_type(np.complex64,data_g,h_g)
if data_g.shape != h_g.shape:
raise ValueError("data and kernel must have same size! %s vs %s "%(str(data_g.shape),str(h_g.shape)))
if plan is None:
plan = fft_plan(data_g.shape)
if inplace:
res_g = data_g
else:
if res_g is None:
res_g = OCLArray.empty(data_g.shape,data_g.dtype)
res_g.copy_buffer(data_g)
if not kernel_is_fft:
kern_g = OCLArray.empty(h_g.shape,h_g.dtype)
kern_g.copy_buffer(h_g)
fft(kern_g,inplace=True, plan = plan)
else:
kern_g = h_g
fft(res_g,inplace=True, plan = plan)
#multiply in fourier domain
_complex_multiply_kernel(res_g,kern_g)
fft(res_g,inplace = True, inverse = True, plan = plan)
return res_g |
java | public void marshall(GetAuthorizerRequest getAuthorizerRequest, ProtocolMarshaller protocolMarshaller) {
if (getAuthorizerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAuthorizerRequest.getApiId(), APIID_BINDING);
protocolMarshaller.marshall(getAuthorizerRequest.getAuthorizerId(), AUTHORIZERID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public ZealotKhala orNotLikePattern(String field, String pattern) {
return this.doLikePattern(ZealotConst.OR_PREFIX, field, pattern, true, false);
} |
java | synchronized PageWrapper getRootPage() {
return this.pageByOffset.values().stream()
.filter(page -> page.getParent() == null)
.findFirst().orElse(null);
} |
java | @Override
public RoundedMoney divide(Number divisor) {
BigDecimal bd = MoneyUtils.getBigDecimal(divisor);
if (isOne(bd)) {
return this;
}
RoundingMode rm = monetaryContext.get(RoundingMode.class);
if(rm==null){
rm = RoundingMode.HALF_EVEN;
}
BigDecimal dec = number.divide(bd, rm);
return new RoundedMoney(dec, currency, rounding).with(rounding);
} |
python | def refresh_db(full=False, **kwargs):
'''
Updates the remote repos database.
full : False
Set to ``True`` to force a refresh of the pkg DB from all publishers,
regardless of the last refresh time.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
salt '*' pkg.refresh_db full=True
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
if full:
return __salt__['cmd.retcode']('/bin/pkg refresh --full') == 0
else:
return __salt__['cmd.retcode']('/bin/pkg refresh') == 0 |
python | def transfer_user(self, username, transfer_address, owner_privkey):
"""
Transfer name on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx) |
java | public static void elementMult( DMatrix2 a , DMatrix2 b , DMatrix2 c ) {
c.a1 = a.a1*b.a1;
c.a2 = a.a2*b.a2;
} |
python | def disconnect(self):
"""Disconnect from event stream."""
_LOGGING.debug('Disconnecting from stream: %s', self.name)
self.kill_thrd.set()
self.thrd.join()
_LOGGING.debug('Event stream thread for %s is stopped', self.name)
self.kill_thrd.clear() |
python | def save(self, output: Union[str, BinaryIO], series: Optional[str] = None,
deps: Iterable=tuple(), create_missing_dirs: bool=True) -> "Model":
"""
Serialize the model to a file.
:param output: Path to the file or a file object.
:param series: Name of the model series. If it is None, it will be taken from \
the current value; if the current value is empty, an error is raised.
:param deps: List of the dependencies.
:param create_missing_dirs: create missing directories in output path if the output is a \
path.
:return: self
"""
check_license(self.license)
if series is None:
if self.series is None:
raise ValueError("series must be specified")
else:
self.series = series
if isinstance(output, str) and create_missing_dirs:
dirs = os.path.split(output)[0]
if dirs:
os.makedirs(dirs, exist_ok=True)
self.set_dep(*deps)
tree = self._generate_tree()
self._write_tree(tree, output)
self._initial_version = self.version
return self |
java | public static String javaStringEscape(@NonNull String string) {
StringBuilder b = new StringBuilder();
for (char c : string.toCharArray()) {
if (c >= 128) {
b.append("\\u").append(String.format("%04X", (int) c));
} else {
b.append(c);
}
}
return b.toString();
} |
java | private boolean isExistCmisObject(String path) {
try {
session.getObjectByPath(path);
return true;
}
catch (CmisObjectNotFoundException e) {
return false;
}
} |
java | private String getDataType(String[] items) {
for (String item : items) {
if (XsdDatatypeEnum.ENTITIES.isDataType(item)) {
return item;
}
}
return items[0];
} |
python | def _closing_bracket_index(self, text, bpair=('(', ')')):
"""Return the index of the closing bracket that matches the opening bracket at the start of the text."""
level = 1
for i, char in enumerate(text[1:]):
if char == bpair[0]:
level += 1
elif char == bpair[1]:
level -= 1
if level == 0:
return i + 1 |
java | private Object decodeResult(IoBuffer data) {
log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0));
processHeaders(data);
Input input = new Input(data);
String target = null;
byte b = data.get();
//look for SOH
if (b == 0) {
log.debug("NUL: {}", b); //0
log.debug("SOH: {}", data.get()); //1
} else if (b == 1) {
log.debug("SOH: {}", b); //1
}
int targetUriLength = data.getShort();
log.debug("targetUri length: {}", targetUriLength);
target = input.readString(targetUriLength);
log.debug("NUL: {}", data.get()); //0
//should be junk bytes ff, ff, ff, ff
int count = data.getInt();
if (count == -1) {
log.debug("DC1: {}", data.get()); //17
count = 1;
} else {
data.position(data.position() - 4);
count = data.getShort();
}
if (count != 1) {
throw new RuntimeException("Expected exactly one result but got " + count);
}
String[] targetParts = target.split("[/]");
if (targetParts.length > 1) {
log.debug("Result sequence number: {}", targetParts[1]);
target = targetParts[2];
} else {
target = target.substring(1);
}
log.debug("Target: {}", target);
if ("onResult".equals(target)) {
//read return value
return input.readObject();
} else if ("onStatus".equals(target)) {
//read return value
return input.readObject();
}
//read return value
return Deserializer.deserialize(input, Object.class);
} |
java | private ConversionMethod verifyConversionExistence(List<ConversionMethod> conversions){
for (ConversionMethod method : conversions)
if(isPresentIn(method.getFrom(),sourceName) &&
isPresentIn(method.getTo() ,destinationName))
return method;
return null;
} |
python | def dephasing_operators(p):
"""
Return the phase damping Kraus operators
"""
k0 = np.eye(2) * np.sqrt(1 - p / 2)
k1 = np.sqrt(p / 2) * Z
return k0, k1 |
python | def GenerateCalendarDatesFieldValuesTuples(self):
"""Generates tuples of calendar_dates.txt values. Yield zero tuples if
this ServicePeriod should not be in calendar_dates.txt ."""
for date, (exception_type, _) in self.date_exceptions.items():
yield (self.service_id, date, unicode(exception_type)) |
java | public void marshall(EntityFilter entityFilter, ProtocolMarshaller protocolMarshaller) {
if (entityFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(entityFilter.getEventArns(), EVENTARNS_BINDING);
protocolMarshaller.marshall(entityFilter.getEntityArns(), ENTITYARNS_BINDING);
protocolMarshaller.marshall(entityFilter.getEntityValues(), ENTITYVALUES_BINDING);
protocolMarshaller.marshall(entityFilter.getLastUpdatedTimes(), LASTUPDATEDTIMES_BINDING);
protocolMarshaller.marshall(entityFilter.getTags(), TAGS_BINDING);
protocolMarshaller.marshall(entityFilter.getStatusCodes(), STATUSCODES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def editor(self, value):
"""
Setter for **self.__editor** attribute.
:param value: Attribute value.
:type value: Editor
"""
if value is not None:
assert type(value) is Editor, "'{0}' attribute: '{1}' type is not 'Editor'!".format("editor", value)
self.__editor = value |
python | def salm2map(salm, s, lmax, Ntheta, Nphi):
"""Convert mode weights of spin-weighted function to values on a grid
Parameters
----------
salm : array_like, complex, shape (..., (lmax+1)**2)
Input array representing mode weights of the spin-weighted function. This array may be
multi-dimensional, where initial dimensions may represent different times, for example, or
separate functions on the sphere. The final dimension should give the values of the mode
weights, in the order described below in the 'Notes' section.
s : int or array, int, shape (...)
Spin weight of the function. If `salm` is multidimensional and this is an array, its
dimensions must match the first dimensions of `salm`, and the different values are the spin
weights of the different functions represented by those dimensions. Otherwise, if `salm` is
multidimensional and `s` is a single integer, all functions are assumed to have the same
spin weight.
lmax : int
The largest `ell` value present in the input array.
Ntheta : int
Number of points in the output grid along the polar angle.
Nphi : int
Number of points in the output grid along the azimuthal angle.
Returns
-------
map : ndarray, complex, shape (..., Ntheta, Nphi)
Values of the spin-weighted function on grid points of the sphere. This array is shaped
like the input `salm` array, but has one extra dimension. The final two dimensions describe
the values of the function on the sphere.
See also
--------
spinsfast.map2salm : Roughly the inverse of this function.
Notes
-----
The input `salm` data should be given in increasing order of `ell` value, always starting with
(ell, m) = (0, 0) even if `s` is nonzero, proceeding to (1, -1), (1, 0), (1, 1), etc.
Explicitly, the ordering should match this:
[f_lm(ell, m) for ell in range(lmax+1) for m in range(-ell, ell+1)]
The input is converted to a contiguous complex numpy array if necessary.
The output data are presented on this grid of spherical coordinates:
np.array([[f(theta, phi)
for phi in np.linspace(0.0, 2*np.pi, num=2*lmax+1, endpoint=False)]
for theta in np.linspace(0.0, np.pi, num=2*lmax+1, endpoint=True)])
Note that `map2salm` and `salm2map` are not true inverses of each other for several reasons.
First, modes with `ell < |s|` should always be zero; they are simply assumed to be zero on input
to `salm2map`. It is also possible to define a `map` function that violates this assumption --
for example, having a nonzero average value over the sphere, if the function has nonzero spin
`s`, this is impossible. Also, it is possible to define a map of a function with so much
angular dependence that it cannot be captured with the given `lmax` value. For example, a
discontinuous function will never be perfectly resolved.
Example
-------
>>> s = -2
>>> lmax = 8
>>> Ntheta = Nphi = 2*lmax + 1
>>> modes = np.zeros(spinsfast.N_lm(lmax), dtype=np.complex128)
>>> modes[spinsfast.lm_ind(2, 2, 8)] = 1.0
>>> values = spinsfast.salm2map(modes, s, lmax, Ntheta, Nphi)
"""
if Ntheta < 2 or Nphi < 1:
raise ValueError("Input values of Ntheta={0} and Nphi={1} ".format(Ntheta, Nphi)
+ "are not allowed; they must be greater than 1 and 0, respectively.")
if lmax < 1:
raise ValueError("Input value of lmax={0} ".format(lmax)
+ "is not allowed; it must be greater than 0 and should be greater "
+ "than |s|={0}.".format(abs(s)))
import numpy as np
salm = np.ascontiguousarray(salm, dtype=np.complex128)
if salm.shape[-1] < N_lm(lmax):
raise ValueError("The input `salm` array of shape {0} is too small for the stated `lmax` of {1}. ".format(salm.shape, lmax)
+ "Perhaps you forgot to include the (zero) modes with ell<|s|.")
map = np.empty(salm.shape[:-1]+(Ntheta, Nphi), dtype=np.complex128)
if salm.ndim>1:
s = np.ascontiguousarray(s, dtype=np.intc)
if s.ndim != salm.ndim-1 or np.product(s.shape) != np.product(salm.shape[:-1]):
s = s*np.ones(salm.shape[:-1], dtype=np.intc)
_multi_salm2map(salm, map, s, lmax, Ntheta, Nphi)
else:
_salm2map(salm, map, s, lmax, Ntheta, Nphi)
return map |
python | def _get_attribute(self, attribute, name):
"""Device attribute getter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except Exception as ex:
self._raise_friendly_access_error(ex, name) |
python | def run_slurm(self, steps=None, **kwargs):
"""Run the steps via the SLURM queue."""
# Optional extra SLURM parameters #
params = self.extra_slurm_params
params.update(kwargs)
# Mandatory extra SLURM parameters #
if 'time' not in params: params['time'] = self.default_time
if 'job_name' not in params: params['job_name'] = self.job_name
if 'email' not in params: params['email'] = None
if 'dependency' not in params: params['dependency'] = 'singleton'
# Send it #
self.slurm_job = LoggedJobSLURM(self.command(steps),
base_dir = self.parent.p.logs_dir,
modules = self.modules,
**params)
# Return the Job ID #
return self.slurm_job.run() |
python | def _query(self, ResponseGroup="Large", **kwargs):
"""Query.
Query Amazon search and check for errors.
:return:
An lxml root element.
"""
response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs)
root = objectify.fromstring(response)
if (hasattr(root.Items.Request, 'Errors') and
not hasattr(root.Items, 'Item')):
code = root.Items.Request.Errors.Error.Code
msg = root.Items.Request.Errors.Error.Message
if code == 'AWS.ParameterOutOfRange':
raise NoMorePages(msg)
elif code == 'HTTP Error 503':
raise RequestThrottled(
"Request Throttled Error: '{0}', '{1}'".format(code, msg))
else:
raise SearchException(
"Amazon Search Error: '{0}', '{1}'".format(code, msg))
if hasattr(root.Items, 'TotalPages'):
if root.Items.TotalPages == self.current_page:
self.is_last_page = True
return root |
java | public PolicyExecutor create(String fullIdentifier, String owner) {
return new PolicyExecutorImpl((ExecutorServiceImpl) globalExecutor, fullIdentifier, owner, policyExecutors);
} |
python | def read_mm_uic2(fd, byte_order, dtype, count):
"""Read MM_UIC2 tag from file and return as dictionary."""
result = {'number_planes': count}
values = numpy.fromfile(fd, byte_order+'I', 6*count)
result['z_distance'] = values[0::6] // values[1::6]
#result['date_created'] = tuple(values[2::6])
#result['time_created'] = tuple(values[3::6])
#result['date_modified'] = tuple(values[4::6])
#result['time_modified'] = tuple(values[5::6])
return result |
java | @Nonnull
public CSSURI setURI (@Nonnull final String sURI)
{
ValueEnforcer.notNull (sURI, "URI");
if (CSSURLHelper.isURLValue (sURI))
throw new IllegalArgumentException ("Only the URI and not the CSS-URI value must be passed!");
m_sURI = sURI;
return this;
} |
python | def empirical_retinotopy_data(hemi, retino_type):
'''
empirical_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi
and retinotopy type t; it does this by looking at the properties in hemi and picking out any
combination that is commonly used to denote empirical retinotopy data. These common names are
stored in _empirical_retintopy_names, in order of preference, which may be modified.
The argument t should be one of 'polar_angle', 'eccentricity', 'weight'.
'''
dat = _empirical_retinotopy_names[retino_type.lower()]
hdat = {s.lower(): s for s in six.iterkeys(hemi.properties)}
return next((hemi.prop(hdat[s.lower()]) for s in dat if s.lower() in hdat), None) |
python | def render_syntax_error(
project: 'projects.Project',
error: SyntaxError
) -> dict:
"""
Renders a SyntaxError, which has a shallow, custom stack trace derived
from the data included in the error, instead of the standard stack trace
pulled from the exception frames.
:param project:
Currently open project.
:param error:
The SyntaxError to be rendered to html and text for display.
:return:
A dictionary containing the error response with rendered display
messages for both text and html output.
"""
return render_error(
project=project,
error=error,
stack=[dict(
filename=getattr(error, 'filename'),
location=None,
line_number=error.lineno,
line=error.text.rstrip()
)]
) |
java | public Observable<Page<MediaServiceInner>> listByResourceGroupAsync(String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName).map(new Func1<ServiceResponse<List<MediaServiceInner>>, Page<MediaServiceInner>>() {
@Override
public Page<MediaServiceInner> call(ServiceResponse<List<MediaServiceInner>> response) {
PageImpl<MediaServiceInner> page = new PageImpl<>();
page.setItems(response.body());
return page;
}
});
} |
python | def os_version_info_ex():
'''
Helper function to return the results of the GetVersionExW Windows API call.
It is a ctypes Structure that contains Windows OS Version information.
Returns:
class: An instance of a class containing version info
'''
if not HAS_WIN32:
return
class OSVersionInfo(ctypes.Structure):
_fields_ = (('dwOSVersionInfoSize', DWORD),
('dwMajorVersion', DWORD),
('dwMinorVersion', DWORD),
('dwBuildNumber', DWORD),
('dwPlatformId', DWORD),
('szCSDVersion', WCHAR * 128))
def __init__(self, *args, **kwds):
super(OSVersionInfo, self).__init__(*args, **kwds)
self.dwOSVersionInfoSize = ctypes.sizeof(self)
kernel32.GetVersionExW(ctypes.byref(self))
class OSVersionInfoEx(OSVersionInfo):
_fields_ = (('wServicePackMajor', WORD),
('wServicePackMinor', WORD),
('wSuiteMask', WORD),
('wProductType', BYTE),
('wReserved', BYTE))
return OSVersionInfoEx() |
python | def contains_raw(self, etag):
"""When passed a quoted tag it will check if this tag is part of the
set. If the tag is weak it is checked against weak and strong tags,
otherwise strong only."""
etag, weak = unquote_etag(etag)
if weak:
return self.contains_weak(etag)
return self.contains(etag) |
python | def query(self, domain):
"""The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict]
"""
result = {}
try:
result = self.pdns.query(domain)
except:
self.error('Exception while querying passiveDNS. Check the domain format.')
# Clean the datetime problems in order to correct the json serializability
clean_result = []
for ind, resultset in enumerate(result):
if resultset.get('time_first', None):
resultset['time_first'] = resultset.get('time_first').isoformat(' ')
if resultset.get('time_last', None):
resultset['time_last'] = resultset.get('time_last').isoformat(' ')
clean_result.append(resultset)
return clean_result |
java | public static String stringToString(String src, String srcfmt, String desfmt) {
return dateToString(stringToDate(src, srcfmt), desfmt);
} |
python | def _printStats(self, graph, hrlinetop=False):
""" shotcut to pull out useful info for interactive use
2016-05-11: note this is a local version of graph.printStats()
"""
if hrlinetop:
self._print("----------------", "TIP")
self._print("Ontologies......: %d" % len(graph.all_ontologies), "TIP")
self._print("Classes.........: %d" % len(graph.all_classes), "TIP")
self._print("Properties......: %d" % len(graph.all_properties), "TIP")
self._print("..annotation....: %d" % len(graph.all_properties_annotation), "TIP")
self._print("..datatype......: %d" % len(graph.all_properties_datatype), "TIP")
self._print("..object........: %d" % len(graph.all_properties_object), "TIP")
self._print("Concepts(SKOS)..: %d" % len(graph.all_skos_concepts), "TIP")
self._print("----------------", "TIP") |
java | public synchronized Servlet getServlet()
throws ServletException
{
// Handle previous unavailability
if (_unavailable!=0)
{
if (_unavailable<0 || _unavailable>0 && System.currentTimeMillis()<_unavailable)
throw _unavailableEx;
_unavailable=0;
_unavailableEx=null;
}
try
{
if (_servlets!=null)
{
Servlet servlet=null;
if (_servlets.size()==0)
{
servlet= (Servlet)newInstance();
if (_config==null)
_config=new Config();
initServlet(servlet,_config);
}
else
servlet = (Servlet)_servlets.pop();
return servlet;
}
if (_servlet==null)
{
_servlet=(Servlet)newInstance();
if (_config==null)
_config=new Config();
initServlet(_servlet,_config);
}
return _servlet;
}
catch(UnavailableException e)
{
_servlet=null;
_config=null;
return makeUnavailable(e);
}
catch(ServletException e)
{
_servlet=null;
_config=null;
throw e;
}
catch(Throwable e)
{
_servlet=null;
_config=null;
throw new ServletException("init",e);
}
} |
java | static void linearTimeIncrementHistogramCounters(final DoublesBufferAccessor samples, final long weight,
final double[] splitPoints, final double[] counters) {
int i = 0;
int j = 0;
while (i < samples.numItems() && j < splitPoints.length) {
if (samples.get(i) < splitPoints[j]) {
counters[j] += weight; // this sample goes into this bucket
i++; // move on to next sample and see whether it also goes into this bucket
} else {
j++; // no more samples for this bucket. move on the next bucket.
}
}
// now either i == numSamples(we are out of samples), or
// j == numSplitPoints(out of buckets, but there are more samples remaining)
// we only need to do something in the latter case.
if (j == splitPoints.length) {
counters[j] += (weight * (samples.numItems() - i));
}
} |
python | def plot_data_filter(data, data_f, b, a, cutoff, fs):
'''Plot frequency response and filter overlay for butter filtered data
Args
----
data: ndarray
Signal array
data_f: float
Signal sampling rate
b: array_like
Numerator of a linear filter
a: array_like
Denominator of a linear filter
cutoff: float
Cutoff frequency for the filter
fs: float
Sampling rate of the signal
Notes
-----
http://stackoverflow.com/a/25192640/943773
'''
import matplotlib.pyplot as plt
import numpy
import scipy.signal
n = len(data)
T = n/fs
t = numpy.linspace(0, T, n, endpoint=False)
# Calculate frequency response
w, h = scipy.signal.freqz(b, a, worN=8000)
# Plot the frequency response.
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.title.set_text('Lowpass Filter Frequency Response')
ax1.plot(0.5*fs * w/numpy.pi, numpy.abs(h), 'b')
ax1.plot(cutoff, 0.5*numpy.sqrt(2), 'ko')
ax1.axvline(cutoff, color='k')
ax1.set_xlim(0, 0.5*fs)
ax1.set_xlabel('Frequency [Hz]')
ax2.legend()
# Demonstrate the use of the filter.
ax2.plot(t, data, linewidth=_linewidth, label='data')
ax2.plot(t, data_f, linewidth=_linewidth, label='filtered data')
ax2.set_xlabel('Time [sec]')
ax2.legend()
plt.show()
return None |
python | def get_archive_types():
'''
Return information related to the types of archives available
'''
ret = copy.deepcopy(_bundle_types)
for k, v in ret.items():
v.pop('handler')
return ret |
java | public EntityType getEntityType(Class<?> clazz) {
EntityType type = context.getEntityType(clazz);
if (null == type) {
type = new EntityType(clazz);
}
return type;
} |
python | def _energy_distance_imp(x, y, exponent=1):
"""
Real implementation of :func:`energy_distance`.
This function is used to make parameter ``exponent`` keyword-only in
Python 2.
"""
x = _transform_to_2d(x)
y = _transform_to_2d(y)
_check_valid_energy_exponent(exponent)
distance_xx = distances.pairwise_distances(x, exponent=exponent)
distance_yy = distances.pairwise_distances(y, exponent=exponent)
distance_xy = distances.pairwise_distances(x, y, exponent=exponent)
return _energy_distance_from_distance_matrices(distance_xx=distance_xx,
distance_yy=distance_yy,
distance_xy=distance_xy) |
java | private void resetAnimation(){
mLastUpdateTime = SystemClock.uptimeMillis();
mLastProgressStateTime = mLastUpdateTime;
if(mProgressMode == ProgressView.MODE_INDETERMINATE){
mStartLine = mReverse ? getBounds().width() : 0;
mStrokeColorIndex = 0;
mLineWidth = mReverse ? -mMinLineWidth : mMinLineWidth;
mProgressState = PROGRESS_STATE_STRETCH;
}
else if(mProgressMode == ProgressView.MODE_BUFFER){
mStartLine = 0;
}
else if(mProgressMode == ProgressView.MODE_QUERY){
mStartLine = !mReverse ? getBounds().width() : 0;
mStrokeColorIndex = 0;
mLineWidth = !mReverse ? -mMaxLineWidth : mMaxLineWidth;
}
} |
java | public static Intent openPlayStore(Context context, boolean openInBrowser) {
String appPackageName = context.getPackageName();
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
if (isIntentAvailable(context, marketIntent)) {
return marketIntent;
}
if (openInBrowser) {
return openLink("https://play.google.com/store/apps/details?id=" + appPackageName);
}
return marketIntent;
} |
python | def labeled_accumulate(sequence, keygetter=operator.itemgetter(0), valuegetter=operator.itemgetter(1), accumulator=operator.add):
"""
Accumulates input elements according to accumulate(), but keeping certain data (per element, from the original
sequence/iterable) in the target elements, like behaving as keys or legends.
:param sequence:
:param keygetter:
:param valuegetter:
:return:
"""
return izip((keygetter(item) for item in sequence),
accumulate((valuegetter(item) for item in sequence), accumulator)) |
java | public void close() {
synchronized (this) {
if (this.closed) {
return;
}
this.closed = true;
}
this.numRecordsInBuffer = 0;
this.numRecordsReturned = 0;
// add the full segments to the empty ones
for (int i = this.fullSegments.size() - 1; i >= 0; i--) {
this.emptySegments.add(this.fullSegments.remove(i));
}
// release the memory segment
this.memoryManager.release(this.emptySegments);
this.emptySegments.clear();
if (LOG.isDebugEnabled()) {
LOG.debug("Block Resettable Iterator closed.");
}
} |
python | def _unapply_xheaders(self) -> None:
"""Undo changes from `_apply_xheaders`.
Xheaders are per-request so they should not leak to the next
request on the same connection.
"""
self.remote_ip = self._orig_remote_ip
self.protocol = self._orig_protocol |
java | @Override
public boolean setActive() {
WebLocator inactiveTab = getTitleInactiveEl().setExcludeClasses("x-tab-active");
boolean activated = isActive() || inactiveTab.click();
if (activated) {
log.info("setActive : " + toString());
}
return activated;
} |
python | def solve(self, scenario, solver):
"""
Decompose each cluster into separate units and try to optimize them
separately
:param scenario:
:param solver: Solver that may be used to optimize partial networks
"""
clusters = set(self.clustering.busmap.values)
n = len(clusters)
self.stats = {'clusters': pd.DataFrame(
index=sorted(clusters),
columns=["decompose", "spread", "transfer"])}
profile = cProfile.Profile()
for i, cluster in enumerate(sorted(clusters)):
print('---')
print('Decompose cluster %s (%d/%d)' % (cluster, i+1, n))
profile.enable()
t = time.time()
partial_network, externals = self.construct_partial_network(
cluster,
scenario)
profile.disable()
self.stats['clusters'].loc[cluster, 'decompose'] = time.time() - t
print('Decomposed in ',
self.stats['clusters'].loc[cluster, 'decompose'])
t = time.time()
profile.enable()
self.solve_partial_network(cluster, partial_network, scenario,
solver)
profile.disable()
self.stats['clusters'].loc[cluster, 'spread'] = time.time() - t
print('Result distributed in ',
self.stats['clusters'].loc[cluster, 'spread'])
profile.enable()
t = time.time()
self.transfer_results(partial_network, externals)
profile.disable()
self.stats['clusters'].loc[cluster, 'transfer'] = time.time() - t
print('Results transferred in ',
self.stats['clusters'].loc[cluster, 'transfer'])
profile.enable()
t = time.time()
print('---')
fs = (mc("sum"), mc("sum"))
for bt, ts in (
('generators', {'p': fs, 'q': fs}),
('storage_units', {'p': fs, 'state_of_charge': fs, 'q': fs})):
print("Attribute sums, {}, clustered - disaggregated:" .format(bt))
cnb = getattr(self.clustered_network, bt)
onb = getattr(self.original_network, bt)
print("{:>{}}: {}".format('p_nom_opt', 4 + len('state_of_charge'),
reduce(lambda x, f: f(x), fs[:-1], cnb['p_nom_opt'])
-
reduce(lambda x, f: f(x), fs[:-1], onb['p_nom_opt'])))
print("Series sums, {}, clustered - disaggregated:" .format(bt))
cnb = getattr(self.clustered_network, bt + '_t')
onb = getattr(self.original_network, bt + '_t')
for s in ts:
print("{:>{}}: {}".format(s, 4 + len('state_of_charge'),
reduce(lambda x, f: f(x), ts[s], cnb[s])
-
reduce(lambda x, f: f(x), ts[s], onb[s])))
profile.disable()
self.stats['check'] = time.time() - t
print('Checks computed in ', self.stats['check']) |
python | def _getFromTime(self, atDate=None):
"""
Time that the event starts (in the local time zone).
"""
return getLocalTime(self.date, self.time_from, self.tz) |
java | public PagedList<SecretItem> getSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) {
ServiceResponse<Page<SecretItem>> response = getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults).toBlocking().single();
return new PagedList<SecretItem>(response.body()) {
@Override
public Page<SecretItem> nextPage(String nextPageLink) {
return getSecretVersionsNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
} |
python | def short_codes(self):
"""
Access the short_codes
:returns: twilio.rest.proxy.v1.service.short_code.ShortCodeList
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeList
"""
if self._short_codes is None:
self._short_codes = ShortCodeList(self._version, service_sid=self._solution['sid'], )
return self._short_codes |
java | private void populateRequestHeaders(HttpURLConnection httpUrlConnection, Map<String, String> requestHeaders) {
Set<String> keySet = requestHeaders.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
String value = requestHeaders.get(key);
httpUrlConnection.setRequestProperty(key, value);
}
PropertyHelper propertyHelper = PropertyHelper.getInstance();
String requestSource = propertyHelper.getRequestSource() + propertyHelper.getVersion();
if(propertyHelper.getRequestSourceHeader() != null){
httpUrlConnection.setRequestProperty(propertyHelper.getRequestSourceHeader(), requestSource);
}
} |
java | public Optional<Epic> getOptionalEpic(Object groupIdOrPath, Integer epicIid) {
try {
return (Optional.ofNullable(getEpic(groupIdOrPath, epicIid)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
} |
java | public static void registerReceiver(Context context, BroadcastReceiver receiver) {
context.registerReceiver(receiver, new IntentFilter(ACTION_ACCESSORY_EVENT));
} |
python | def drop_trailing_zeros(num):
"""
Drops the trailing zeros in a float that is printed.
"""
txt = '%f' %(num)
txt = txt.rstrip('0')
if txt.endswith('.'):
txt = txt[:-1]
return txt |
python | def init(cls, name):
"""Return an instance of this class or an appropriate subclass"""
clsdict = {subcls.name: subcls for subcls in cls.__subclasses__()
if hasattr(subcls, 'name')}
return clsdict.get(name, cls)(name) |
java | static public Value getValue( Key key ) {
Value val = DKV.get(key);
return val;
} |
python | def add_feed(url):
"""add to db"""
with Database("feeds") as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name |
java | @Override
public void remove() {
try {
removeThrow();
} catch (SQLException e) {
closeQuietly();
// unfortunately, can't propagate back the SQLException
throw new IllegalStateException("Could not delete " + dataClass + " object " + last, e);
}
} |
python | def forward(self, x, boxes):
"""
Arguments:
x (list[Tensor]): feature maps for each level
boxes (list[BoxList]): boxes to be used to perform the pooling operation.
Returns:
result (Tensor)
"""
num_levels = len(self.poolers)
rois = self.convert_to_roi_format(boxes)
if num_levels == 1:
return self.poolers[0](x[0], rois)
levels = self.map_levels(boxes)
num_rois = len(rois)
num_channels = x[0].shape[1]
output_size = self.output_size[0]
dtype, device = x[0].dtype, x[0].device
result = torch.zeros(
(num_rois, num_channels, output_size, output_size),
dtype=dtype,
device=device,
)
for level, (per_level_feature, pooler) in enumerate(zip(x, self.poolers)):
idx_in_level = torch.nonzero(levels == level).squeeze(1)
rois_per_level = rois[idx_in_level]
result[idx_in_level] = pooler(per_level_feature, rois_per_level)
return result |
java | public static String[] translatePathName(String path) {
path = prettifyPath(path);
if (path.indexOf('/') != 0) path = '/' + path;
int index = path.lastIndexOf('/');
// remove slash at the end
if (index == path.length() - 1) path = path.substring(0, path.length() - 1);
index = path.lastIndexOf('/');
String name;
if (index == -1) {
name = path;
path = "/";
}
else {
name = path.substring(index + 1);
path = path.substring(0, index + 1);
}
return new String[] { path, name };
} |
python | def execute(self, command):
"""
Execute (or simulate) a command. Add to our log.
@param command: Either a C{str} command (which will be passed to the
shell) or a C{list} of command arguments (including the executable
name), in which case the shell is not used.
@return: A C{CompletedProcess} instance. This has attributes such as
C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess.
"""
if isinstance(command, six.string_types):
# Can't have newlines in a command given to the shell.
strCommand = command = command.replace('\n', ' ').strip()
shell = True
else:
strCommand = ' '.join(command)
shell = False
if self._dryRun:
self.log.append('$ ' + strCommand)
return
start = time()
self.log.extend([
'# Start command (shell=%s) at %s' % (shell, ctime(start)),
'$ ' + strCommand,
])
if six.PY3:
try:
result = run(command, check=True, stdout=PIPE,
stderr=PIPE, shell=shell, universal_newlines=True)
except CalledProcessError as e:
from sys import stderr
print('CalledProcessError:', e, file=stderr)
print('STDOUT:\n%s' % e.stdout, file=stderr)
print('STDERR:\n%s' % e.stderr, file=stderr)
raise
else:
try:
result = check_call(command, stdout=PIPE, stderr=PIPE,
shell=shell, universal_newlines=True)
except CalledProcessError as e:
from sys import stderr
print('CalledProcessError:', e, file=stderr)
print('Return code: %s' % e.returncode, file=stderr)
print('Output:\n%s' % e.output, file=stderr)
raise
stop = time()
elapsed = (stop - start)
self.log.extend([
'# Stop command at %s' % ctime(stop),
'# Elapsed = %f seconds' % elapsed,
])
return result |
java | private String loadDrlFile(final Reader drl) throws IOException {
final StringBuilder buf = new StringBuilder();
final BufferedReader input = new BufferedReader( drl );
String line;
while ( (line = input.readLine()) != null ) {
buf.append( line );
buf.append( nl );
}
return buf.toString();
} |
java | private void addLine(PdfLine line) {
lines.add(line);
contentHeight += line.height();
lastLine = line;
this.line = null;
} |
python | def _perform_power_op(self, oper):
"""Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO.
"""
power_settings = {"Action": "Reset",
"ResetType": oper}
systems_uri = "/rest/v1/Systems/1"
status, headers, response = self._rest_post(systems_uri, None,
power_settings)
if status >= 300:
msg = self._get_extended_error(response)
raise exception.IloError(msg) |
java | @Override
public synchronized void open() throws IOException {
if (_mode == Mode.OPEN) {
return;
}
try {
_addressArray.open();
_segmentManager.open();
_compactor.start();
init();
_mode = Mode.OPEN;
} catch(Exception e) {
_mode = Mode.CLOSED;
_log.error("Failed to open", e);
_compactor.shutdown();
_compactor.clear();
if (_addressArray.isOpen()) {
_addressArray.close();
}
if (_segmentManager.isOpen()) {
_segmentManager.close();
}
throw (e instanceof IOException) ? (IOException)e : new IOException(e);
} finally {
_log.info("mode=" + _mode);
}
} |
java | public void stop_logging () {
Vector dl = Util.instance().get_device_list("*");
for (Object aDl : dl) {
((DeviceImpl) aDl).stop_logging();
}
} |
python | def memory_read_bytes(self, start_position: int, size: int) -> bytes:
"""
Read and return ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read_bytes(start_position, size) |
python | def flipcheck(content):
"""Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text
"""
# Prevent tampering with flip
punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─"""
tamperdict = str.maketrans('', '', punct)
tamperproof = content.translate(tamperdict)
# Unflip
if "(╯°□°)╯︵" in tamperproof:
# For tables
if "┻┻" in tamperproof:
# Calculate table length
length = 0
for letter in content:
if letter == "━":
length += 1.36
elif letter == "─":
length += 1
elif letter == "-":
length += 0.50
# Construct table
putitback = "┬"
for i in range(int(length)):
putitback += "─"
putitback += "┬ ノ( ゜-゜ノ)"
return putitback
# For text
else:
# Create dictionary for flipping text
flipdict = str.maketrans(
'abcdefghijklmnopqrstuvwxyzɐqɔpǝɟbɥıظʞןɯuodbɹsʇnʌʍxʎz😅🙃😞😟😠😡☹🙁😱😨😰😦😧😢😓😥😭',
'ɐqɔpǝɟbɥıظʞןɯuodbɹsʇnʌʍxʎzabcdefghijklmnopqrstuvwxyz😄🙂🙂🙂🙂🙂🙂😀😀🙂😄🙂🙂😄😄😄😁'
)
# Construct flipped text
flipstart = content.index('︵')
flipped = content[flipstart+1:]
flipped = str.lower(flipped).translate(flipdict)
putitback = ''.join(list(reversed(list(flipped))))
putitback += "ノ( ゜-゜ノ)"
return putitback
else:
return False |
java | public UpdateRulesOfIpGroupRequest withUserRules(IpRuleItem... userRules) {
if (this.userRules == null) {
setUserRules(new com.amazonaws.internal.SdkInternalList<IpRuleItem>(userRules.length));
}
for (IpRuleItem ele : userRules) {
this.userRules.add(ele);
}
return this;
} |
python | def p_binary_operators(self, p):
"""
conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expression
| condition EQ expression
expression : expression ADD term
| expression SUB term
term : term MUL factor
| term DIV factor
| term POW factor
| term MOD factor
"""
p[0] = Instruction("op(left, right)", context={'op': self.binary_operators[p[2]], 'left': p[1], 'right': p[3]}) |
java | public IfcConstructionMaterialResourceTypeEnum createIfcConstructionMaterialResourceTypeEnumFromString(
EDataType eDataType, String initialValue) {
IfcConstructionMaterialResourceTypeEnum result = IfcConstructionMaterialResourceTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
} |
python | def parse_host_args(self, *args):
"""
Splits out the patch subcommand and returns a comma separated list of host_strings
"""
self.subcommand = None
new_args = args
try:
sub = args[0]
if sub in ['project','templates','static','media','wsgi','webconf']:
self.subcommand = args[0]
new_args = args[1:]
except IndexError:
pass
return ','.join(new_args) |
java | @Override
public void removeByCPOptionId(long CPOptionId) {
for (CPOptionValue cpOptionValue : findByCPOptionId(CPOptionId,
QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(cpOptionValue);
}
} |
java | public static float max( float []array , int offset , int length ) {
float max = -Float.MAX_VALUE;
for (int i = 0; i < length; i++) {
float tmp = array[offset+i];
if( tmp > max ) {
max = tmp;
}
}
return max;
} |
java | public boolean remove(SpdData data) {
if (data == null)
return false;
if (data instanceof SpdDouble) {
return super.remove(data);
} else {
return false;
}
} |
python | def _vpn_signal_handler(self, args):
"""Called on NetworkManager PropertiesChanged signal"""
# Args is a dictionary of changed properties
# We only care about changes in ActiveConnections
active = "ActiveConnections"
# Compare current ActiveConnections to last seen ActiveConnections
if active in args.keys() and sorted(self.active) != sorted(args[active]):
self.active = args[active]
self.py3.update() |
java | boolean setParentNodeReference(N newParent, boolean fireEvent) {
final N oldParent = getParentNode();
if (newParent == oldParent) {
return false;
}
this.parent = (newParent == null) ? null : new WeakReference<>(newParent);
if (!fireEvent) {
return true;
}
firePropertyParentChanged(oldParent, newParent);
if (oldParent != null) {
oldParent.firePropertyParentChanged(toN(), oldParent, newParent);
}
return false;
} |
python | def ssh(self, *args, **kwargs):
'''
Run salt-ssh commands synchronously
Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`.
:return: Returns the result from the salt-ssh command
'''
ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts,
disable_custom_roster=True)
return ssh_client.cmd_sync(kwargs) |
python | def fix_attr_encoding(ds):
""" This is a temporary hot-fix to handle the way metadata is encoded
when we read data directly from bpch files. It removes the 'scale_factor'
and 'units' attributes we encode with the data we ingest, converts the
'hydrocarbon' and 'chemical' attribute to a binary integer instead of a
boolean, and removes the 'units' attribute from the "time" dimension since
that too is implicitly encoded.
In future versions of this library, when upstream issues in decoding
data wrapped in dask arrays is fixed, this won't be necessary and will be
removed.
"""
def _maybe_del_attr(da, attr):
""" Possibly delete an attribute on a DataArray if it's present """
if attr in da.attrs:
del da.attrs[attr]
return da
def _maybe_decode_attr(da, attr):
# TODO: Fix this so that bools get written as attributes just fine
""" Possibly coerce an attribute on a DataArray to an easier type
to write to disk. """
# bool -> int
if (attr in da.attrs) and (type(da.attrs[attr] == bool)):
da.attrs[attr] = int(da.attrs[attr])
return da
for v in ds.data_vars:
da = ds[v]
da = _maybe_del_attr(da, 'scale_factor')
da = _maybe_del_attr(da, 'units')
da = _maybe_decode_attr(da, 'hydrocarbon')
da = _maybe_decode_attr(da, 'chemical')
# Also delete attributes on time.
if hasattr(ds, 'time'):
times = ds.time
times = _maybe_del_attr(times, 'units')
return ds |
java | @Override
public InputHandler getInputHandler(ProtocolType type, SIBUuid8 sourceMEUuid, JsMessage msg)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getInputHandler",
new Object[] { type, sourceMEUuid, msg });
InputHandler msgHandler = null;
if (type == ProtocolType.UNICASTINPUT)
{
msgHandler = getInputHandler();
}
else if (type == ProtocolType.PUBSUBINPUT)
{
msgHandler = getInputHandler();
}
else if (type == ProtocolType.ANYCASTINPUT)
{
// For durable, AIHs are referenced by pseudo destination ID so check for that first
SIBUuid12 destID = msg.getGuaranteedTargetDestinationDefinitionUUID();
SIBUuid12 gatheringTargetDestUuid = msg.getGuaranteedGatheringTargetUUID();
msgHandler = _protoRealization.
getRemoteSupport().
getAnycastInputHandlerByPseudoDestId(destID);
// Otherwise, use the uuid of the sourceCellule ME to find the RCD to deliver the message. We assume that this
// uuid corresponds to that used to choose the RCD initially, and that was used by the associated
// AIH as the uuid of the DME to which it sent the request for the message.
if (msgHandler == null)
msgHandler = getAnycastInputHandler(sourceMEUuid, gatheringTargetDestUuid, true);
}
//else
//{
//unsupported protocol type
//return null
//}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getInputHandler", msgHandler);
return msgHandler;
} |
python | def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts.get('inline_view'))
return inline_views |
python | def build_clonespec(config_spec, object_ref, reloc_spec, template):
'''
Returns the clone spec
'''
if reloc_spec.diskMoveType == QUICK_LINKED_CLONE:
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec,
snapshot=object_ref.snapshot.currentSnapshot
)
return vim.vm.CloneSpec(
template=template,
location=reloc_spec,
config=config_spec
) |
python | def handle_noargs(self, **options):
"""
By default this function runs on all objects.
As we are using a publishing system it should only update draft
objects which can be modified in the tree structure.
Once published the tree preferences should remain the same to
ensure the tree data structure is consistent with what was
published by the user.
"""
is_dry_run = options.get('dry-run', False)
mptt_only = options.get('mptt-only', False)
slugs = {}
overrides = {}
# MODIFIED
# This was modified to filter draft objects only.
# ORIGINAL LINE -> `parents = dict(UrlNode.objects.values_list('id', 'parent_id'))`
parents = dict(
UrlNode.objects.filter(status=UrlNode.DRAFT).values_list('id', 'parent_id')
)
# END MODIFIED
self.stdout.write("Updated MPTT columns")
if is_dry_run and mptt_only:
# Can't really do anything
return
if not is_dry_run:
# Fix MPTT first, that is the basis for walking through all nodes.
# MODIFIED
# Original line -> `UrlNode.objects.rebuild()`
# The `rebuild` function works on the manager. As we need to filter the queryset first
# it does not play nicely. The code for `rebuild` was brought in here and modified to
# work with the current context.
# Get opts from `UrlNode` rather than `self.model`.
opts = UrlNode._mptt_meta
# Add a queryset parameter will draft objects only.
qs = UrlNode.objects._mptt_filter(
qs=UrlNode.objects.filter(status=UrlNode.DRAFT),
parent=None
)
if opts.order_insertion_by:
qs = qs.order_by(*opts.order_insertion_by)
pks = qs.values_list('pk', flat=True)
# Obtain the `rebuild_helper` from `UrlNode.objects` rather than `self`.
rebuild_helper = UrlNode.objects._rebuild_helper
idx = 0
for pk in pks:
idx += 1
rebuild_helper(pk, 1, idx)
# END MODIFIED
self.stdout.write("Updated MPTT columns")
if mptt_only:
return
self.stdout.write("Updating cached URLs")
self.stdout.write("Page tree nodes:\n\n")
col_style = u"| {0:6} | {1:6} | {2:6} | {3}"
header = col_style.format("Site", "Page", "Locale", "URL")
sep = '-' * (len(header) + 40)
self.stdout.write(sep)
self.stdout.write(header)
self.stdout.write(sep)
# MODIFIED
# Modified to add the filter for draft objects only.
for translation in UrlNode_Translation.objects.filter(
master__status=UrlNode.DRAFT
).select_related('master').order_by(
'master__parent_site__id', 'master__tree_id', 'master__lft', 'language_code'
):
# END MODIFIED
slugs.setdefault(translation.language_code, {})[translation.master_id] = translation.slug
overrides.setdefault(translation.language_code, {})[translation.master_id] = translation.override_url
old_url = translation._cached_url
try:
new_url = self._construct_url(translation.language_code, translation.master_id, parents, slugs, overrides)
except KeyError:
if is_dry_run:
# When the mptt tree is broken, some URLs can't be correctly generated yet.
self.stderr.write("Failed to determine new URL for {0}, please run with --mptt-only first.".format(old_url))
return
raise
if old_url != new_url:
translation._cached_url = new_url
if not is_dry_run:
translation.save()
if old_url != new_url:
self.stdout.write(smart_text(u"{0} {1} {2}\n".format(
col_style.format(translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url),
"WILL CHANGE from" if is_dry_run else "UPDATED from",
old_url
)))
else:
self.stdout.write(smart_text(col_style.format(
translation.master.parent_site_id, translation.master_id, translation.language_code, translation._cached_url
))) |
python | def get_tensor_size(self, tensor_name, partial_layout=None,
mesh_dimension_to_size=None):
"""The size of a tensor in bytes.
If partial_layout is specified, then mesh_dimension_to_size must also be. In
this case, the size on a single device is returned.
Args:
tensor_name: a string, name of a tensor in the graph.
partial_layout: an optional {string: string}, from MTF dimension name to
mesh dimension name.
mesh_dimension_to_size: an optional {string: int}, from mesh dimension
name to size.
Returns:
an integer
"""
return (self.get_tensor_dtype(tensor_name).size *
self.get_tensor_num_entries(tensor_name, partial_layout,
mesh_dimension_to_size)) |
java | public void walkSourceContents(SourceWalker walker) {
for (int i = 0, len = this.children.size(); i < len; i++) {
if (this.children.get(i) instanceof SourceNode) {
((SourceNode) this.children.get(i)).walkSourceContents(walker);
}
}
for (Entry<String, String> entry : this.sourceContents.entrySet()) {
walker.walk(entry.getKey(), entry.getValue());
}
} |
java | @Override
public RegisterPatchBaselineForPatchGroupResult registerPatchBaselineForPatchGroup(RegisterPatchBaselineForPatchGroupRequest request) {
request = beforeClientExecution(request);
return executeRegisterPatchBaselineForPatchGroup(request);
} |
python | def items( self ):
"""
Returns all the rollout items for this widget.
:return [<XRolloutItem>, ..]
"""
layout = self.widget().layout()
return [layout.itemAt(i).widget() for i in range(layout.count()-1)] |
java | public ArrayList<String> serviceName_networkInterfaceController_GET(String serviceName, OvhNetworkInterfaceControllerLinkTypeEnum linkType) throws IOException {
String qPath = "/dedicated/server/{serviceName}/networkInterfaceController";
StringBuilder sb = path(qPath, serviceName);
query(sb, "linkType", linkType);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} |
java | public Observable<RestorePointInner> createAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
return createWithServiceResponseAsync(resourceGroupName, serverName, databaseName, restorePointLabel).map(new Func1<ServiceResponse<RestorePointInner>, RestorePointInner>() {
@Override
public RestorePointInner call(ServiceResponse<RestorePointInner> response) {
return response.body();
}
});
} |
python | def lower(string):
"""Lower."""
new_string = []
for c in string:
o = ord(c)
new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c)
return ''.join(new_string) |
python | def nested(*contexts):
"""
Reimplementation of nested in python 3.
"""
with ExitStack() as stack:
results = [
stack.enter_context(context)
for context in contexts
]
yield results |
java | public java.util.List<NodeGroup> getNodeGroups() {
if (nodeGroups == null) {
nodeGroups = new com.amazonaws.internal.SdkInternalList<NodeGroup>();
}
return nodeGroups;
} |
python | def on_train_begin(self, **kwargs):
"Call watch method to log model topology, gradients & weights"
# Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback"
super().on_train_begin()
# Ensure we don't call "watch" multiple times
if not WandbCallback.watch_called:
WandbCallback.watch_called = True
# Logs model topology and optionally gradients and weights
wandb.watch(self.learn.model, log=self.log) |
java | private void checkForFailure(Dependency[] dependencies) throws ScanAgentException {
final StringBuilder ids = new StringBuilder();
for (Dependency d : dependencies) {
boolean addName = true;
for (Vulnerability v : d.getVulnerabilities()) {
if (v.getCvssV2().getScore() >= failBuildOnCVSS) {
if (addName) {
addName = false;
ids.append(NEW_LINE).append(d.getFileName()).append(": ");
ids.append(v.getName());
} else {
ids.append(", ").append(v.getName());
}
}
}
}
if (ids.length() > 0) {
final String msg;
if (showSummary) {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities that have a CVSS score greater than or equal to '%.1f': %s%n"
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
} else {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities.%n%n"
+ "See the dependency-check report for more details.%n%n");
}
throw new ScanAgentException(msg);
}
} |
java | public BigMoney minus(Iterable<? extends BigMoneyProvider> moniesToSubtract) {
BigDecimal total = amount;
for (BigMoneyProvider moneyProvider : moniesToSubtract) {
BigMoney money = checkCurrencyEqual(moneyProvider);
total = total.subtract(money.amount);
}
return with(total);
} |
python | def run_psexec_command(cmd, args, host, username, password, port=445):
'''
Run a command remotly using the psexec protocol
'''
if has_winexe() and not HAS_PSEXEC:
ret_code = run_winexe_command(cmd, args, host, username, password, port)
return None, None, ret_code
service_name = 'PS-Exec-{0}'.format(uuid.uuid4())
stdout, stderr, ret_code = '', '', None
client = Client(host, username, password, port=port, encrypt=False, service_name=service_name)
client.connect()
try:
client.create_service()
stdout, stderr, ret_code = client.run_executable(cmd, args)
finally:
client.remove_service()
client.disconnect()
return stdout, stderr, ret_code |
java | public static Packet decompress(final Packet packet) throws IOException
{
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(packet.getData());
final GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Read from input until everything is inflated
final byte buffer[] = new byte[INFLATE_BUFFER_SIZE];
int bytesInflated;
while ((bytesInflated = gzipInputStream.read(buffer)) >= 0)
{
byteArrayOutputStream.write(buffer, 0, bytesInflated);
}
return new Packet(
packet.getPacketType(),
packet.getPacketID(),
byteArrayOutputStream.toByteArray()
);
} |
python | def sample(self, size=None):
"""
Sample from the prior distribution over datasets
Args:
size (Optional[int]): The number of samples to draw.
Returns:
array[n] or array[size, n]: The samples from the prior
distribution over datasets.
"""
self._recompute()
if size is None:
n = np.random.randn(len(self._t))
else:
n = np.random.randn(len(self._t), size)
n = self.solver.dot_L(n)
if size is None:
return self.mean.get_value(self._t) + n[:, 0]
return self.mean.get_value(self._t)[None, :] + n.T |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.