language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _start_map(cls,
name,
mapper_spec,
mapreduce_params,
queue_name,
eta=None,
countdown=None,
hooks_class_name=None,
_app=None,
in_xg_transaction=False):
# pylint... |
java | @Override
public DDF sql2ddf(String command, Schema schema, DataSourceDescriptor dataSource, DataFormat dataFormat) throws DDFException {
// TableRDD tableRdd = null;
// RDD<Row> rddRow = null;
DataFrame rdd = this.getHiveContext().sql(command);
if (schema == null) schema = SchemaHandler.getSch... |
python | def is_period_alias(period):
"""
Check if a given period is possibly an alias.
Parameters
----------
period : float
A period to test if it is a possible alias or not.
Returns
-------
is_alias : boolean
True if the given period is in a range of period alias.
"""
... |
python | def read_message(self, id_):
"""Login required. Send POST to mark a message as read. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: ``http://www.reddit.com/api/read_message/``
:param id\_: full id of message to mark
... |
python | def is_valid(url, fix=True):
""" Returns True if this is what we consider to be a valid URL.
A valid URL has:
* http OR https scheme
* a valid TLD
If there is no scheme, it will check the URL assuming the scheme is http.
Returns False if the URL is not valid.
"... |
java | public void setRelativeTo(String relativeTo) {
m_relativeTo = relativeTo;
if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_relativeTo)) {
m_relativeTo = null;
} else {
if (!m_relativeTo.startsWith("/")) {
m_relativeTo = "/" + m_relativeTo;
}
... |
java | protected String mergeDefinition(BeanDefinition target, ReconfigBeanDefinitionHolder source) {
if (null == target.getBeanClassName()) {
logger.warn("ingore bean definition {} for without class", source.getBeanName());
return null;
}
// 当类型变化后,删除原有配置
if (null != source.getBeanDefinition().get... |
java | @Override
public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException {
if (inputType.length > 1)
throw new InvalidKerasConfigurationException(
"Keras Convolution layer accepts only one input (received " + inputType.length + ")");
... |
python | def train():
"""Training process"""
start_pipeline_time = time.time()
# Training/Testing
best_valid_acc = 0
stop_early = 0
for epoch in range(args.epochs):
# Epoch training stats
start_epoch_time = time.time()
epoch_L = 0.0
epoch_sent_num = 0
epoch_wc = 0... |
java | public int correlationDistance(PCAFilteredResult pca1, PCAFilteredResult pca2, int dimensionality) {
// TODO: Can we delay copying the matrixes?
// pca of rv1
double[][] v1t = copy(pca1.getEigenvectors());
double[][] v1t_strong = pca1.getStrongEigenvectors();
int lambda1 = pca1.getCorrelationDimensi... |
python | def _get_existing_report(self, mask, report):
"""Returns the aggregated report that matches report"""
for existing_report in self._reports:
if existing_report['namespace'] == report['namespace']:
if mask == existing_report['queryMask']:
return existing_rep... |
python | def plug(update_kwargs=True, **plugs_map):
"""Creates a decorator that passes in plugs when invoked.
This function returns a decorator for a function that will replace positional
arguments to that function with the plugs specified. See the module
docstring for details and examples.
Note this decorator does... |
java | public static String getLocationByIp(String ip) throws IOException, XPathExpressionException,
ParserConfigurationException {
return evaluate(ValueConsts.IP_REGION_XPATH, getHtmlFromUrl("http://ip.chinaz.com/" + ip));
} |
python | def lwd(self, astr_startPath, **kwargs):
"""
Return the cwd in treeRecurse compatible format.
:return: Return the cwd in treeRecurse compatible format.
"""
if self.cd(astr_startPath)['status']:
self.l_lwd.append(self.cwd())
return ... |
java | public static int cs_fkeep(DZcs A, DZcs_ifkeep fkeep, Object other)
{
int j, p, nz = 0, n, Ap[], Ai[] ;
DZcsa Ax = new DZcsa() ;
if (!CS_CSC (A)) return (-1) ; /* check inputs */
n = A.n ; Ap = A.p ; Ai = A.i ; Ax.x = A.x ;
for (j = 0 ; j < n ; j++)
{
p = Ap [j] ; /* get current location of c... |
python | def getHashForFile(f):
"""Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str
"""
hashVal = hashlib.sha1()
while True:
r = f.read(1024)
if not r:
break
hashVal.update(r)
f.seek(0)
return hashVal.hexdigest() |
python | def _ParseMRUListExEntryValue(
self, parser_mediator, registry_key, entry_index, entry_number,
codepage='cp1252', **kwargs):
"""Parses the MRUListEx entry value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and d... |
python | def control(self, control_func, args=None, kwargs=None, name='Control', context=None):
'''
Set the experiment's control function. Must be set before ``conduct()`` is called.
:param callable control_func: your control function
:param iterable args: positional arguments to pass to your fu... |
java | @SuppressWarnings("unchecked")
private void parseOptionsFromFile(String optionFileName)
throws ParseException {
List<String> options = OptionsFileLoader.loadOptions(optionFileName);
options.addAll(commandLine.getArgList());
commandLine = cliParser.parse(cliOptions, options.toArray(new String[0]));
... |
python | def horizontals(self):
""" All horizontal squares from the piece's point of view.
Returns a list of relative movements up to the board's bound.
"""
horizontal_shifts = set(izip_longest(map(
lambda i: i - self.x, range(self.board.length)), [], fillvalue=0))
horizontal... |
java | @GetMapping(value = "/csv/{entityTypeId}", produces = "text/csv")
@ResponseBody
public EntityCollection retrieveEntityCollection(
@PathVariable("entityTypeId") String entityTypeId,
@RequestParam(value = "attributes", required = false) String[] attributes,
HttpServletRequest req,
HttpServletR... |
java | public final Ix<Boolean> sequenceEqual(Iterable<? extends T> other, IxPredicate2<? super T, ? super T> comparer) {
return new IxSequenceEqual<T>(this, nullCheck(other, "other is null"), nullCheck(comparer, "comparer is null"));
} |
java | public URIBuilder addNullParameter( String key )
{
if ( key != null ) {
queryParams.put( key, null );
}
return this;
} |
python | def read_ring_images_index():
"""Filter cumulative index for ring images.
This is done by matching the column TARGET_DESC to contain the string 'ring'
Returns
-------
pandas.DataFrame
data table containing only meta-data for ring images
"""
meta = read_cumulative_iss_index()
ri... |
python | def _machine_actions(self, action):
"""
Actions for the machine (e.g. stop, start etc)
:param action: Can be "reboot", "start", "stop", "destroy"
:returns: An updated list of the added machines
"""
payload = {
'action': action
}
data = json.du... |
java | private boolean isStoppingStoppedOrFailed() {
BatchStatus jobBatchStatus = runtimeWorkUnitExecution.getBatchStatus();
if (jobBatchStatus.equals(BatchStatus.STOPPING) || jobBatchStatus.equals(BatchStatus.STOPPED) || jobBatchStatus.equals(BatchStatus.FAILED)) {
return true;
}
... |
python | def operator_names():
"""Get all operator names.
Returns: A sequence of operator names.
"""
return tuple('{}/{}'.format(provider_name, operator_name)
for provider_name, provider in OPERATOR_PROVIDERS.items()
for operator_name in provider) |
java | public <T> List<T> executeGroup(final Collection<ShardingExecuteGroup<? extends StatementExecuteUnit>> sqlExecuteGroups, final SQLExecuteCallback<T> callback) throws SQLException {
return executeGroup(sqlExecuteGroups, null, callback);
} |
java | public void setThreadContextLoader() {
if (isContextLoaderSaved) {
throw new BuildException("Context loader has not been reset");
}
if (LoaderUtils.isContextLoaderAvailable()) {
savedContextLoader = LoaderUtils.getContextClassLoader();
ClassLoader loader = thi... |
python | def omega_ratio(returns, risk_free=0.0, required_return=0.0,
annualization=APPROX_BDAYS_PER_YEAR):
"""Determines the Omega ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in... |
python | def associate_health_monitor(self, pool, body):
"""Associate specified load balancer health monitor and pool."""
return self.post(self.associate_pool_health_monitors_path % (pool),
body=body) |
python | def _find_highest_supported_command(self, *segment_classes, **kwargs):
"""Search the BPD for the highest supported version of a segment."""
return_parameter_segment = kwargs.get("return_parameter_segment", False)
parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_class... |
java | public static Object toPrimitiveBoolArray(List<?> values)
{
boolean[] array = new boolean[values.size()];
int cursor = 0;
for(Object o : values)
{
array[cursor] = (Boolean) o;
cursor ++;
}
return array;
} |
python | def equal(value_a, value_b):
"""Determine if two **HasProperties** instances are equivalent
Equivalence is determined by checking if (1) the two instances are
the same class and (2) all Property values on two instances are
equal, using :code:`Property.equal`. If the two values are the same
HasPrope... |
python | def imap(self, func, iterable, chunksize=1):
"""
An equivalent of itertools.imap().
The chunksize argument is the same as the one used by the
map() method. For very long iterables using a large value for
chunksize can make make the job complete much faster than
using the... |
java | public void marshall(DetachPolicyRequest detachPolicyRequest, ProtocolMarshaller protocolMarshaller) {
if (detachPolicyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(detachPolicyRequest.ge... |
java | public boolean subtract(ModuleDepInfo toSub) {
boolean modified = false;
if (toSub.formula.isTrue()) {
// Subtracting true makes this formula false
modified = !formula.isFalse();
formula = new BooleanFormula(false);
} else if (formula.isTrue()) {
// Subtracting anything from true (other than tr... |
java | private boolean isANeighboorsInAnAtomContainer(List<IAtom> neighs, IAtomContainer ac) {
boolean isIn = false;
int count = 0;
for (IAtom neigh : neighs) {
if (ac.contains(neigh)) {
count += 1;
}
}
if (count > 0) {
isIn = true;
... |
python | def download_file(self, url, local_path):
"""
Download a file from a remote host.
"""
response = requests.get(url, stream=True)
with open(local_path, 'wb') as f:
for chunk in tqdm(response.iter_content(chunk_size=1024), unit='KB'):
if chunk: # filter ... |
python | def move_identity(db, from_id, to_uuid):
"""Move an identity to a unique identity.
This function shifts the identity identified by 'from_id' to
the unique identity 'to_uuid'.
When 'to_uuid' is the unique identity that is currently related
to 'from_id', the action does not have any effect.
In ... |
python | def _write_history(self):
"""Write previously-calculated history lines back to the file"""
if self.data['history_file'] is None:
return
contents = '\n'.join(self.data['history_lines'])
history = self.data['history_file']
open(history, 'w').write(contents)
logg... |
java | public void makeNothingCurrent() {
if (!EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE,
EGL14.EGL_NO_CONTEXT)) {
throw new RuntimeException("eglMakeCurrent failed");
}
} |
java | public static <T> void closeQuietly(@Nullable final Iterable<T> iterable) {
if (iterable != null) {
iterable.forEach(AutoCloseables::closeQuietly);
}
} |
python | def set_bytes_at_offset(self, offset, data):
"""Overwrite the bytes at the given file offset with the given string.
Return True if successful, False otherwise. It can fail if the
offset is outside the file's boundaries.
"""
if not isinstance(data, bytes):
raise Type... |
python | def write(self):
"""Write csv file of resolved names and txt file of unresolved names.
"""
csv_file = os.path.join(self.outdir, 'search_results.csv')
txt_file = os.path.join(self.outdir, 'unresolved.txt')
headers = self.key_terms
unresolved = []
with open(csv_file... |
java | public static long readUnsignedIntLittleEndian(byte[] data, int index) {
long result = (long) (data[index] & 0xFF) | (long) ((data[index + 1] & 0xFF) << 8)
| (long) ((data[index + 2] & 0xFF) << 16) | (long) ((data[index + 3] & 0xFF) << 24);
return result;
} |
java | public Criteria between(@Nullable Object lowerBound, @Nullable Object upperBound, boolean includeLowerBound, boolean includeUppderBound) {
predicates.add(new Predicate(OperationKey.BETWEEN,
new Object[] { lowerBound, upperBound, includeLowerBound, includeUppderBound }));
return this;
} |
python | def multiply(self, multiplicator):
"""Return a new Matrix with a multiple.
:param Number multiplicator: The number to calculate the multiple
:return: The Matrix with the the multiple.
:rtype: Matrix
"""
result = Matrix(self.get_width(), self.get_height())
... |
java | public VertexElement buildVertexElement(Vertex vertex) {
if (!tx.isValidElement(vertex)) {
Objects.requireNonNull(vertex);
throw TransactionException.invalidElement(vertex);
}
return new VertexElement(tx, vertex);
} |
python | def commits_with_message(message):
"""All commits with that message (in current branch)"""
output = log("--grep '%s'" % message, oneline=True, quiet=True)
lines = output.splitlines()
return [l.split(' ', 1)[0] for l in lines] |
python | def xlsx_to_csv(self, infile, worksheet=0, delimiter=","):
""" Convert xlsx to easier format first, since we want to use the
convenience of the CSV library
"""
wb = load_workbook(self.getInputFile())
sheet = wb.worksheets[worksheet]
buffer = StringIO()
# extract ... |
python | def get_voltage_at_bus_bar(grid, tree):
"""
Determine voltage level at bus bar of MV-LV substation
Parameters
----------
grid : LVGridDing0
Ding0 grid object
tree : :networkx:`NetworkX Graph Obj< >`
Tree of grid topology:
Returns
-------
:any:`list`
Voltage ... |
python | async def on_shutdown(app):
"""app SHUTDOWN event handler
"""
for method in app.get("close_methods", []):
logger.debug("Calling < %s >", method)
if asyncio.iscoroutinefunction(method):
await method()
else:
method() |
python | def _load_aux_image(self, image, auxfile):
"""
Load a fits file (bkg/rms/curve) and make sure that
it is the same shape as the main image.
Parameters
----------
image : :class:`AegeanTools.fits_image.FitsImage`
The main image that has already been loaded.
... |
java | public static int max(IntTuple t)
{
return IntTupleFunctions.reduce(
t, Integer.MIN_VALUE, Math::max);
} |
java | @Override
public Object getObjectInstance(JavaColonNamespace namespace, String name) throws NamingException {
Object instance;
// This helper only provides support for java:global, java:app, and java:module
if (namespace == JavaColonNamespace.GLOBAL) {
instance = processJavaCol... |
java | public SourceReportModel getSourceReportForFileModel(FileModel fileModel)
{
GraphTraversal<Vertex, Vertex> pipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(fileModel.getElement());
pipeline.in(SourceReportModel.SOURCE_REPORT_TO_SOURCE_FILE_MODEL);
SourceReportModel result... |
java | public final DeviceRegistry updateDeviceRegistry(
DeviceRegistry deviceRegistry, FieldMask updateMask) {
UpdateDeviceRegistryRequest request =
UpdateDeviceRegistryRequest.newBuilder()
.setDeviceRegistry(deviceRegistry)
.setUpdateMask(updateMask)
.build();
retur... |
java | static public char normalize(char input, int format) {
if (NORMALIZE_LOWER == format) {
return toLower(input);
}
if (NORMALIZE_UPPER == format) {
return toUpper(input);
}
return input;
} |
java | static double hsla( HSL hsl ) {
return hsla(hsl.h, hsl.s, hsl.l, hsl.a);
} |
python | def call_rpc(self, rpc_id, payload=bytes()):
"""Call an RPC by its ID.
Args:
rpc_id (int): The number of the RPC
payload (bytes): A byte string of payload parameters up to 20 bytes
Returns:
bytes: The response payload from the RPC
"""
if rpc_... |
java | public void deleteShippingAddress(final String accountCode, final long shippingAddressId) {
doDELETE(Accounts.ACCOUNTS_RESOURCE + "/" + accountCode + ShippingAddresses.SHIPPING_ADDRESSES_RESOURCE + "/" + shippingAddressId);
} |
java | @Deprecated
public String unsetDefault() {
return call(
new PostRequest(path("unset_default"))
.setMediaType(MediaTypes.JSON)
).content();
} |
java | private String getRealFilePath(String fileName, BundleHashcodeType bundleHashcodeType) {
String realFilePath = fileName;
if (bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) {
int idx = realFilePath.indexOf(JawrConstant.URL_SEPARATOR, 1);
if (idx != -1) {
realFilePath = realFilePath.substr... |
java | public boolean restricted(Order<?, ?> order) {
if (!order.property().metamodel().isRoot()) {
restricted = true;
return true;
}
if (restricted) {
return true;
}
if (this.order == null) {
if (filter != null && filter.property() != order.property()) {
restricted = true;
return true;
... |
java | public EEnum getIfcStructuralSurfaceTypeEnum() {
if (ifcStructuralSurfaceTypeEnumEEnum == null) {
ifcStructuralSurfaceTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(907);
}
return ifcStructuralSurfaceTypeEnumEEnum;
} |
python | def register(self, user_data, base_confirm_url='', send_welcome=True):
"""
Register user
Accepts user data, validates it and performs registration. Will send
a welcome message with a confirmation link on success.
:param user_data: dic, populate user with data
:param send... |
python | def update_state_success(self, model_output):
"""Update the state of the model run to 'SUCCESS'. Expects a model
output result file. Will upload the file before changing the model
run state.
Raises an exception if update fails or resource is unknown.
Parameters
--------... |
python | def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, value... |
java | public Iterator iterateObjects(org.kie.api.runtime.ObjectFilter filter) {
return getObjectStore().iterateObjects(filter);
} |
python | def generate(self, number=None):
"""Generates vectors from the Gaussian.
@param number: optional, if given, generates more than one vector.
@returns: generated vector(s), either as a one dimensional array
(shape (d,)) if number is not set, or as a two dimensional array
... |
java | public static String doDelete(String host, String path,
Map<String, String> headers,
Map<String, String> queries,
Map<String, String> body) throws Exception {
return EntityUtils.toString(doDeleteResponse(host, ... |
python | def running_windows(iterable, size):
"""Generate n-size running windows.
Usage::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
"""
fifo = collections.deque(maxlen=size)
for i in iterable:
fifo.a... |
python | def callback(self):
"""Run callback."""
if self._callback_func and callable(self._callback_func):
self._callback_func(self) |
java | public NotificationChain basicSetExpression(XExpression newExpression, NotificationChain msgs)
{
XExpression oldExpression = expression;
expression = newExpression;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SarlPackage.SARL_BEHAVIOR_UNIT__E... |
java | public Map<Integer, String> listProjects() throws MPXJException
{
try
{
Map<Integer, String> result = new HashMap<Integer, String>();
List<Row> rows = getRows("select proj_id, proj_short_name from " + m_schema + "project where delete_date is null");
for (Row row : rows)
... |
python | def update_all(engine, table, data, upsert=False):
"""
Update data by its primary_key column.
"""
data = ensure_list(data)
ins = table.insert()
upd = table.update()
# Find all primary key columns
pk_cols = OrderedDict()
for column in table._columns:
if column.primary_key:
... |
java | public static MutableDoubleTuple insertElementAt(
DoubleTuple t, int index, double value,
MutableDoubleTuple result)
{
if (index < 0)
{
throw new IndexOutOfBoundsException(
"Index "+index+" is negative");
}
if (index > t.getSize()... |
python | def get_logs(self, id, **kwargs):
"""
Gets logs for specific Build Record
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callbac... |
python | def translate(self, node):
"""
Translate a node into some output format.
:param node: a treebrd node
:return: a node's translation to some format
"""
_translate = self._translate_functions.get(node.operator)
return _translate(node) |
java | public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException
{
out.writeObject(getContextPath());
out.writeObject(getVirtualHosts());
HttpHandler[] handlers= getHandlers();
for (int i= 0; i < handlers.length; i++)
{
if (handlers[i] instanceof Web... |
java | public Include withType(String theResourceType) {
StringBuilder b = new StringBuilder();
String paramType = getParamType();
String paramName = getParamName();
if (isBlank(paramType) || isBlank(paramName)) {
throw new IllegalStateException("This include does not contain a value in the format [ResourceType]... |
java | List<Shape> getOutlines() {
List<Shape> shapes = new ArrayList<Shape>();
shapes.add(element.getOutline());
for (TextOutline adjunct : adjuncts)
shapes.add(adjunct.getOutline());
return shapes;
} |
java | public CollisionGroup getGroup(String name)
{
Check.notNull(name);
final CollisionGroup group = groups.get(name);
Check.notNull(group);
return group;
} |
java | public String disAssembleId(String id, String... suffixes) {
int count = 0;
for (String s : suffixes) {
count += s.length() + Dom.ID_SEPARATOR.length();
}
return id.substring(0, id.length() - count);
} |
python | def debug(level=logging.DEBUG):
"""
Turn on the debugging
"""
from jcvi.apps.console import magenta, yellow
format = yellow("%(asctime)s [%(module)s]")
format += magenta(" %(message)s")
logging.basicConfig(level=level,
format=format,
datefmt="%H:%M:%S") |
java | public static String hash(Serializable obj) {
if (obj == null) {
return "";
}
StringBuilder hexString = new StringBuilder();
try {
MessageDigest m = MessageDigest.getInstance("SHA1");
m.update(SerializationUtils.serialize(obj));
byte[] mdbytes = m.digest();
for (byte mdbyte : mdbytes... |
python | def add_volumes(self,
pathmapper, # type: PathMapper
runtime, # type: List[Text]
tmpdir_prefix, # type: Text
secret_store=None, # type: Optional[SecretStore]
any_path_okay=False # type: bool... |
python | def draw(self, surface):
"""Blit the menu to a surface."""
offset = 0
i = 0
ol, ot = self.screen_topleft_offset
first = self.options and self.options[0]
last = self.options and self.options[-1]
for o in self.options:
indent = o.get('padding_col', 0)
... |
java | @Override
public File inputrc() {
if(inputrc == null) {
inputrc = new File(System.getProperty("user.home")+Config.getPathSeparator()+".inputrc");
}
return inputrc;
} |
python | def draw(self, gdefs, theme):
"""
Draw out each guide definition
Parameters
----------
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
out : list of matplotlib.offsetb... |
java | private static CharSequence reverse(CharSequence s) {
int length = s.length();
if (length <= 1) {
return s;
}
char[] buffer = new char[length];
buffer[0] = s.charAt(length - 1);
for (int i = 1; i < length; i++) {
buffer[i] = s.charAt(length - 1 - i);
if (Character.isSurrogate... |
java | public void addExtraCapabilities(DesiredCapabilities extraCapabilities) {
if (extraCapabilities != null && browser.getName() != BrowserName.NONE) {
desiredCapabilities = desiredCapabilities.merge(extraCapabilities);
}
} |
python | def _get_envs_from_ref_paths(self, refs):
'''
Return the names of remote refs (stripped of the remote name) and tags
which are map to the branches and tags.
'''
def _check_ref(env_set, rname):
'''
Add the appropriate saltenv(s) to the set
'''
... |
python | def to_css(self):
''' Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"``
'''
if self.a == 1.0:
return "hsl(%d, %s%%, %s%%)" % (self.h, self.s*100, self.l*100)
else:
return "hsla(%d, %s%%, %s%%, ... |
java | @SuppressFBWarnings(value = "PZLA", justification = "Null is checked, not empty array. API is clear as well.")
public String[] match(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.m... |
java | private void adjustOriginalPositionIndicator(
CmsSitemapTreeItem draggable,
I_CmsDropTarget target,
CmsDNDHandler handler) {
if (!isChangedPosition(draggable, target, true)) {
draggable.getElement().addClassName(I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().markUnchange... |
python | def _backward_sampling_ON2(self, M, idx):
"""O(N^2) version of backward sampling.
not meant to be called directly, see backward_sampling
"""
for m in range(M):
for t in reversed(range(self.T - 1)):
lwm = (self.wgt[t].lw + self.model.logpt(t + 1, self.X[t],
... |
python | def _correctNoise(self, image):
'''
denoise using non-local-means
with guessing best parameters
'''
from skimage.restoration import denoise_nl_means # save startup time
image[np.isnan(image)] = 0 # otherwise result =nan
out = denoise_nl_means(image,
... |
java | public void marshall(AggregatedSourceStatus aggregatedSourceStatus, ProtocolMarshaller protocolMarshaller) {
if (aggregatedSourceStatus == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(aggregatedSou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.