language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | protected Pair<String, Map<String, List<Object>>> convertPersonAttributesToPrincipal(final String extractedPrincipalId,
final Map<String, List<Object>> attributes) {
val convertedAttributes = new LinkedHashMap<String, List<Object>>();
attributes.forEach((key, attrValue) -> {
val values = CollectionUtils.toCollection(attrValue, ArrayList.class);
LOGGER.debug("Found attribute [{}] with value(s) [{}]", key, values);
if (values.size() == 1) {
val value = CollectionUtils.firstElement(values).get();
convertedAttributes.put(key, CollectionUtils.wrapList(value));
} else {
convertedAttributes.put(key, values);
}
});
var principalId = extractedPrincipalId;
if (StringUtils.isNotBlank(this.principalAttributeNames)) {
val attrNames = org.springframework.util.StringUtils.commaDelimitedListToSet(this.principalAttributeNames);
val result = attrNames.stream()
.map(String::trim)
.filter(attributes::containsKey)
.map(attributes::get)
.findFirst();
if (result.isPresent()) {
val values = result.get();
if (!values.isEmpty()) {
principalId = CollectionUtils.firstElement(values).get().toString();
LOGGER.debug("Found principal id attribute value [{}] and removed it from the collection of attributes", principalId);
}
} else {
LOGGER.warn("Principal resolution is set to resolve the authenticated principal via attribute(s) [{}], and yet "
+ "the collection of attributes retrieved [{}] do not contain any of those attributes. This is likely due to misconfiguration "
+ "and CAS will switch to use [{}] as the final principal id", this.principalAttributeNames, attributes.keySet(), principalId);
}
}
return Pair.of(principalId, convertedAttributes);
} |
python | def register(self, event, callback, selector=None):
"""
Resister an event that you want to monitor.
:param event: Name of the event to monitor
:param callback: Callback function for when the event is received (Params: event, interface).
:param selector: `(Optional)` CSS selector for the element(s) you want to monitor.
"""
self.processor.register(event, callback, selector) |
python | def _sanity_check_no_nested_folds(ir_blocks):
"""Assert that there are no nested Fold contexts, and that every Fold has a matching Unfold."""
fold_seen = False
for block in ir_blocks:
if isinstance(block, Fold):
if fold_seen:
raise AssertionError(u'Found a nested Fold contexts: {}'.format(ir_blocks))
else:
fold_seen = True
elif isinstance(block, Unfold):
if not fold_seen:
raise AssertionError(u'Found an Unfold block without a matching Fold: '
u'{}'.format(ir_blocks))
else:
fold_seen = False |
python | def _open_browser(self, single_doc_html):
"""
Open a browser tab showing single
"""
url = os.path.join('file://', DOC_PATH, 'build', 'html',
single_doc_html)
webbrowser.open(url, new=2) |
java | protected void adjustHomographSign( AssociatedPair p , DMatrixRMaj H ) {
double val = GeometryMath_F64.innerProd(p.p2, H, p.p1);
if( val < 0 )
CommonOps_DDRM.scale(-1, H);
} |
java | public void setEditable(final int row, final int col, final boolean enable) {
final int actualIndex = getTableColumn(col).getIndex();
getRecord(row).setColumnEnabled(actualIndex, enable);
} |
java | @Override
protected void init() {
dataJoinNo = StringUtil.getMatchNo(labels, conf.get(SimpleJob.JOIN_DATA_COLUMN));
} |
java | public void report(long arrivalTime) {
checkArgument(arrivalTime >= 0, "arrivalTime must not be negative");
long latestHeartbeat = history.latestHeartbeatTime();
history.samples().addValue(arrivalTime - latestHeartbeat);
history.setLatestHeartbeatTime(arrivalTime);
} |
java | public final EObject entryRuleJvmUpperBound() throws RecognitionException {
EObject current = null;
EObject iv_ruleJvmUpperBound = null;
try {
// InternalSARL.g:16394:54: (iv_ruleJvmUpperBound= ruleJvmUpperBound EOF )
// InternalSARL.g:16395:2: iv_ruleJvmUpperBound= ruleJvmUpperBound EOF
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getJvmUpperBoundRule());
}
pushFollow(FOLLOW_1);
iv_ruleJvmUpperBound=ruleJvmUpperBound();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
current =iv_ruleJvmUpperBound;
}
match(input,EOF,FOLLOW_2); if (state.failed) return current;
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} |
java | private Properties loadConfig() throws IOException {
String configUrl = String.format("%s/%s/%s", defaultRepositoryUrl, DIST_DIR, RESOLVE_CONFIG_FILE);
log.info("Looking for repository-config at {}", configUrl);
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpget = new HttpGet(configUrl);
CloseableHttpResponse contentResponse;
try {
contentResponse = client.execute(httpget);
} catch (ConnectTimeoutException e) {
throw new ConnectException(e.getMessage());
}
int statusCode = contentResponse.getStatusLine().getStatusCode();
log.debug("HttpGet at {}, Status is {}", configUrl, statusCode);
if (statusCode == HttpStatus.SC_NOT_FOUND) {
log.info("No repository-config found at {}", configUrl);
return null;
} else if (statusCode != HttpStatus.SC_OK) {
String msg = "Error loading " + configUrl + ":\n";
msg += contentResponse.getStatusLine().toString();
throw new RuntimeException(msg);
}
HttpEntity entity = contentResponse.getEntity();
BufferedInputStream inputStream = new BufferedInputStream(entity.getContent());
Properties properties = new Properties();
properties.load(inputStream);
contentResponse.close();
client.close();
return properties;
} |
python | def set_windows_permissions(filename):
'''
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change the permissions for Allusers of the application
The Everyone Group
Full access
http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html
'''
#Todo rename this to allow_all, also make international not just for english..
if os.name == 'nt':
try:
everyone, domain, type = win32security.LookupAccountName(
"", "Everyone")
except Exception:
# Todo fails on non english langauge systesm ... FU WINDOWS
# Just allow permission for the current user then...
everyone, domain, type = win32security.LookupAccountName ("", win32api.GetUserName())
# ~ user, domain, type = win32security.LookupAccountName ("", win32api.GetUserName())
#~ userx, domain, type = win32security.LookupAccountName ("", "User")
#~ usery, domain, type = win32security.LookupAccountName ("", "User Y")
sd = win32security.GetFileSecurity(
filename,
win32security.DACL_SECURITY_INFORMATION)
# instead of dacl = win32security.ACL()
dacl = sd.GetSecurityDescriptorDacl()
#~ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, everyone)
#~ dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_ALL_ACCESS, user)
dacl.AddAccessAllowedAce(
win32security.ACL_REVISION,
con.FILE_ALL_ACCESS,
everyone)
sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary
win32security.SetFileSecurity(
filename,
win32security.DACL_SECURITY_INFORMATION,
sd) |
python | def input(msg="", default="", title="Lackey Input", hidden=False):
""" Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInput(root, msg, title, hidden, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get()) |
python | def update_field(self, name, value):
"""Changes the definition of a KV Store field.
:param name: name of field to change
:type name: ``string``
:param value: new field definition
:type value: ``string``
:return: Result of POST request
"""
kwargs = {}
kwargs['field.' + name] = value
return self.post(**kwargs) |
java | public DescribeTagsRequest withFilters(TagFilter... filters) {
if (this.filters == null) {
setFilters(new java.util.ArrayList<TagFilter>(filters.length));
}
for (TagFilter ele : filters) {
this.filters.add(ele);
}
return this;
} |
python | def lemma(self, verb, parse=True):
""" Returns the infinitive form of the given verb, or None.
"""
if dict.__len__(self) == 0:
self.load()
if verb.lower() in self._inverse:
return self._inverse[verb.lower()]
if verb in self._inverse:
return self._inverse[verb]
if parse is True: # rule-based
return self.find_lemma(verb) |
python | def valid_options(kwargs, allowed_options):
""" Checks that kwargs are valid API options"""
diff = set(kwargs) - set(allowed_options)
if diff:
print("Invalid option(s): ", ', '.join(diff))
return False
return True |
python | def _check_values(self, values):
"""Check values whenever they come through the values setter."""
assert isinstance(values, Iterable) and not \
isinstance(values, (str, dict, bytes, bytearray)), \
'values should be a list or tuple. Got {}'.format(type(values))
assert len(values) == len(self.datetimes), \
'Length of values list must match length of datetimes list. {} != {}'.format(
len(values), len(self.datetimes))
assert len(values) > 0, 'Data Collection must include at least one value' |
python | def global_avgpooling(attrs, inputs, proto_obj):
"""Performs avg pooling on the input."""
new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True,
'kernel': (1, 1),
'pool_type': 'avg'})
return 'Pooling', new_attrs, inputs |
python | def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
CPIOPathSpec: path specification.
"""
location = getattr(self.path_spec, 'location', None)
if location and location.startswith(self._file_system.PATH_SEPARATOR):
cpio_archive_file = self._file_system.GetCPIOArchiveFile()
for cpio_archive_file_entry in cpio_archive_file.GetFileEntries(
path_prefix=location[1:]):
path = cpio_archive_file_entry.path
if not path:
continue
_, suffix = self._file_system.GetPathSegmentAndSuffix(
location[1:], path)
# Ignore anything that is part of a sub directory or the directory
# itself.
if suffix or path == location:
continue
path_spec_location = self._file_system.JoinPath([path])
yield cpio_path_spec.CPIOPathSpec(
location=path_spec_location, parent=self.path_spec.parent) |
java | public final Observable<Integer> averageInteger(Func1<? super T, Integer> valueExtractor) {
return o.lift(new OperatorAverageInteger<T>(valueExtractor));
} |
java | public static int lastWhitespaceIn(String source) {
if (CmsStringUtil.isEmpty(source)) {
return -1;
}
int pos = -1;
for (int i = source.length() - 1; i >= 0; i--) {
if (Character.isWhitespace(source.charAt(i))) {
pos = i;
break;
}
}
return pos;
} |
java | @Given("^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$")
public void executeLocalCommand(String command, String foo, Integer exitStatus, String bar, String envVar) throws Exception {
if (exitStatus == null) {
exitStatus = 0;
}
commonspec.runLocalCommand(command);
commonspec.runCommandLoggerAndEnvVar(exitStatus, envVar, Boolean.TRUE);
Assertions.assertThat(commonspec.getCommandExitStatus()).isEqualTo(exitStatus);
} |
java | public void applyAndJournal(Supplier<JournalContext> context, MutableInode<?> inode) {
try {
applyCreateInode(inode);
context.get().append(inode.toJournalEntry());
} catch (Throwable t) {
ProcessUtils.fatalError(LOG, t, "Failed to apply %s", inode);
throw t; // fatalError will usually system.exit
}
} |
python | def plotBasis(self, filename=None):
"""
Plots the basis functions, reshaped in 2-dimensional arrays.
This representation makes the most sense for visual input.
:param: filename (string) Can be provided to save the figure
"""
if np.floor(np.sqrt(self.filterDim)) ** 2 != self.filterDim:
print "Basis visualization is not available if filterDim is not a square."
return
dim = int(np.sqrt(self.filterDim))
if np.floor(np.sqrt(self.outputDim)) ** 2 != self.outputDim:
outDimJ = np.sqrt(np.floor(self.outputDim / 2))
outDimI = np.floor(self.outputDim / outDimJ)
if outDimI > outDimJ:
outDimI, outDimJ = outDimJ, outDimI
else:
outDimI = np.floor(np.sqrt(self.outputDim))
outDimJ = outDimI
outDimI, outDimJ = int(outDimI), int(outDimJ)
basis = - np.ones((1 + outDimI * (dim + 1), 1 + outDimJ * (dim + 1)))
# populate array with basis values
k = 0
for i in xrange(outDimI):
for j in xrange(outDimJ):
colorLimit = np.max(np.abs(self.basis[:, k]))
mat = np.reshape(self.basis[:, k], (dim, dim)) / colorLimit
basis[1 + i * (dim + 1) : 1 + i * (dim + 1) + dim, \
1 + j * (dim + 1) : 1 + j * (dim + 1) + dim] = mat
k += 1
plt.figure()
plt.subplot(aspect="equal")
plt.pcolormesh(basis)
plt.axis([0, 1 + outDimJ * (dim + 1), 0, 1 + outDimI * (dim + 1)])
# remove ticks
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.title("Basis functions for {0}".format(self))
if filename is not None:
plt.savefig(filename) |
python | def reset_can(self, channel=Channel.CHANNEL_CH0, flags=ResetFlags.RESET_ALL):
"""
Resets a CAN channel of a device (hardware reset, empty buffer, and so on).
:param int channel: CAN channel, to be reset (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`).
:param int flags: Flags defines what should be reset (see enum :class:`ResetFlags`).
"""
UcanResetCanEx(self._handle, channel, flags) |
java | public static Directory getDirectory()
throws EFapsException
{
IDirectoryProvider provider = null;
if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXDIRECTORYPROVCLASS)) {
final String clazzname = EFapsSystemConfiguration.get().getAttributeValue(
KernelSettings.INDEXDIRECTORYPROVCLASS);
try {
final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance());
provider = (IDirectoryProvider) clazz.newInstance();
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new EFapsException(Index.class, "Could not instanciate IDirectoryProvider", e);
}
} else {
provider = new IDirectoryProvider()
{
@Override
public Directory getDirectory()
throws EFapsException
{
return new RAMDirectory();
}
@Override
public Directory getTaxonomyDirectory()
throws EFapsException
{
return null;
}
};
}
return provider.getDirectory();
} |
java | public static HijriCalendar ofUmalqura(
int hyear,
int hmonth,
int hdom
) {
return HijriCalendar.of(VARIANT_UMALQURA, hyear, hmonth, hdom);
} |
python | def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833]
"""
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p |
java | public byte[] getBytes()
{
byte b[] = new byte[getLength()];
int bytesCopied = 0;
Iterator<V> it = this.values().iterator();
while (it.hasNext())
{
ID3v2Frame frame = (ID3v2Frame) it.next();
System.arraycopy(frame.getFrameBytes(), 0, b, bytesCopied, frame.getFrameLength());
bytesCopied += frame.getFrameLength();
}
return b;
} |
python | def _rotate_vector(x, y, x2, y2, x1, y1):
"""
rotate x,y vector over x2-x1, y2-y1 angle
"""
angle = atan2(y2 - y1, x2 - x1)
cos_rad = cos(angle)
sin_rad = sin(angle)
return cos_rad * x + sin_rad * y, -sin_rad * x + cos_rad * y |
java | @SuppressWarnings("WeakerAccess")
public static void setStatementResolver(StatementResolver statementResolver) {
if (statementResolver == null) {
throw new NullPointerException("The statement resolver must not be null.");
}
StatementResolverHolder.STATEMENT_RESOLVER.set(statementResolver);
} |
java | @Trivial
protected void activate(ComponentContext context) throws Exception {
Dictionary<String, ?> props = context.getProperties();
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(this, tc, "activate", props);
String sourcePID = (String) props.get("ibm.extends.source.pid"); // com.ibm.ws.jca.jmsQueueConnectionFactory_gen_3f3cb305-4146-41f9-8a57-b231d09013e6
configElementName = sourcePID == null ? "connectionFactory" : sourcePID.substring(15, sourcePID.indexOf('_', 15));
cfInterfaceNames = props.get("creates.objectClass");
mcfImplClassName = (String) props.get(CONFIG_PROPS_PREFIX + "managedconnectionfactory-class");
jndiName = (String) props.get(JNDI_NAME);
id = (String) props.get("config.displayId");
componentContext = context;
isServerDefined = true; // We don't support app-defined connection factories yet
//Integer trlevel = props.get("transactionSupport");
if (props.get("transactionSupport") != null)
connectionFactoryTransactionSupport = TransactionSupportLevel.valueOf((String) props.get("transactionSupport"));
// filter out actual config properties for the connection factory
for (Enumeration<String> keys = props.keys(); keys.hasMoreElements();) {
String key = keys.nextElement();
if (key.length() > CONFIG_PROPS_PREFIX_LENGTH && key.charAt(CONFIG_PROPS_PREFIX_LENGTH - 1) == '.' && key.startsWith(CONFIG_PROPS_PREFIX)) {
String propName = key.substring(CONFIG_PROPS_PREFIX_LENGTH);
if (propName.indexOf('.') < 0 && propName.indexOf('-') < 0)
properties.put(propName, props.get(key));
}
}
bootstrapContextRef.activate(context);
if (trace && tc.isEntryEnabled())
Tr.exit(this, tc, "activate");
} |
java | @Override
protected void addSummaryType(Element member, Content tdSummaryType) {
ExecutableElement meth = (ExecutableElement)member;
addModifierAndType(meth, utils.getReturnType(meth), tdSummaryType);
} |
java | public List<Boolean> exists(List<Value> keyValues) throws AerospikeException {
List<Boolean> target = new ArrayList<Boolean>();
for (Object value : keyValues) {
target.add(exists(Value.get(value)));
}
return target;
} |
python | def get_local_gb(iLOIP, snmp_credentials):
"""Gets the maximum disk size among all disks.
:param iLOIP: IP address of the server on which SNMP discovery
has to be executed.
:param snmp_credentials in a dictionary having following mandatory
keys.
auth_user: SNMP user
auth_protocol: Auth Protocol
auth_prot_pp: Pass phrase value for AuthProtocol.
priv_protocol:Privacy Protocol.
auth_priv_pp: Pass phrase value for Privacy Protocol.
"""
disk_sizes = _get_disksize_MiB(iLOIP, snmp_credentials)
max_size = 0
for uuid in disk_sizes:
for key in disk_sizes[uuid]:
if int(disk_sizes[uuid][key]) > max_size:
max_size = int(disk_sizes[uuid][key])
max_size_gb = max_size/1024
return max_size_gb |
python | def on_drag_data_get(self, widget, context, data, info, time):
'''拖放开始'''
tree_paths = self.iconview.get_selected_items()
if not tree_paths:
return
filelist = []
for tree_path in tree_paths:
filelist.append({
'path': self.liststore[tree_path][PATH_COL],
'newname': self.liststore[tree_path][NAME_COL],
})
filelist_str = json.dumps(filelist)
if info == TargetInfo.PLAIN_TEXT:
data.set_text(filelist_str, -1)
# 拖拽时无法获取目标路径, 所以不能实现拖拽下载功能
elif info == TargetInfo.URI_LIST:
data.set_uris([]) |
python | def _set_up_figure(self, x_mins, x_maxs, y_mins, y_maxs):
"""
Prepare the matplotlib figure: make all the subplots; adjust their
x and y range; plot the data; and plot an putative function.
"""
self.fig = plt.figure()
# Make room for the sliders:
bot = 0.1 + 0.05*len(self.model.params)
self.fig.subplots_adjust(bottom=bot)
# If these are not ints, matplotlib will crash and burn with an utterly
# vague error.
nrows = int(np.ceil(len(self._projections)**0.5))
ncols = int(np.ceil(len(self._projections)/nrows))
# Make all the subplots: set the x and y limits, scatter the data, and
# plot the putative function.
self._plots = {}
for plotnr, proj in enumerate(self._projections, 1):
x, y = proj
if Derivative(y, x) in self.model:
title_format = '$\\frac{{\\partial {dependant}}}{{\\partial {independant}}} = {expression}$'
else:
title_format = '${dependant}({independant}) = {expression}$'
plotlabel = title_format.format(
dependant=latex(y, mode='plain'),
independant=latex(x, mode='plain'),
expression=latex(self.model[y], mode='plain'))
ax = self.fig.add_subplot(ncols, nrows, plotnr,
label=plotlabel)
ax.set_title(ax.get_label())
ax.set_ylim(y_mins[y], y_maxs[y])
ax.set_xlim(x_mins[x], x_maxs[x])
ax.set_xlabel('${}$'.format(x))
ax.set_ylabel('${}$'.format(y))
self._plot_data(proj, ax)
plot = self._plot_model(proj, ax)
self._plots[proj] = plot |
python | def viewer_has_liked(self) -> Optional[bool]:
"""Whether the viewer has liked the post, or None if not logged in."""
if not self._context.is_logged_in:
return None
if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']:
return self._node['likes']['viewer_has_liked']
return self._field('viewer_has_liked') |
python | def compound_statements(logical_line):
r"""Compound statements (on the same line) are generally discouraged.
While sometimes it's okay to put an if/for/while with a small body
on the same line, never do this for multi-clause statements.
Also avoid folding such long lines!
Always use a def statement instead of an assignment statement that
binds a lambda expression directly to a name.
Okay: if foo == 'blah':\n do_blah_thing()
Okay: do_one()
Okay: do_two()
Okay: do_three()
E701: if foo == 'blah': do_blah_thing()
E701: for x in lst: total += x
E701: while t < 10: t = delay()
E701: if foo == 'blah': do_blah_thing()
E701: else: do_non_blah_thing()
E701: try: something()
E701: finally: cleanup()
E701: if foo == 'blah': one(); two(); three()
E702: do_one(); do_two(); do_three()
E703: do_four(); # useless semicolon
E704: def f(x): return 2*x
E731: f = lambda x: 2*x
"""
line = logical_line
last_char = len(line) - 1
found = line.find(':')
prev_found = 0
counts = dict((char, 0) for char in '{}[]()')
while -1 < found < last_char:
update_counts(line[prev_found:found], counts)
if ((counts['{'] <= counts['}'] and # {'a': 1} (dict)
counts['['] <= counts[']'] and # [1:2] (slice)
counts['('] <= counts[')'])): # (annotation)
lambda_kw = LAMBDA_REGEX.search(line, 0, found)
if lambda_kw:
before = line[:lambda_kw.start()].rstrip()
if before[-1:] == '=' and isidentifier(before[:-1].strip()):
yield 0, ("E731 do not assign a lambda expression, use a "
"def")
break
if STARTSWITH_DEF_REGEX.match(line):
yield 0, "E704 multiple statements on one line (def)"
elif STARTSWITH_INDENT_STATEMENT_REGEX.match(line):
yield found, "E701 multiple statements on one line (colon)"
prev_found = found
found = line.find(':', found + 1)
found = line.find(';')
while -1 < found:
if found < last_char:
yield found, "E702 multiple statements on one line (semicolon)"
else:
yield found, "E703 statement ends with a semicolon"
found = line.find(';', found + 1) |
java | public void encodeAMO(final MiniSatStyleSolver s, final LNGIntVector lits) {
switch (this.amoEncoding) {
case LADDER:
this.ladder.encode(s, lits);
break;
default:
throw new IllegalStateException("Unknown AMO encoding: " + this.amoEncoding);
}
} |
java | public static WindowOver<Double> regrSxx(Expression<? extends Number> arg1, Expression<? extends Number> arg2) {
return new WindowOver<Double>(Double.class, SQLOps.REGR_SXX, arg1, arg2);
} |
python | def parser(scope, usage=''):
"""
Generates a default parser for the inputted scope.
:param scope | <dict> || <module>
usage | <str>
callable | <str>
:return <OptionParser>
"""
subcmds = []
for cmd in commands(scope):
subcmds.append(cmd.usage())
if subcmds:
subcmds.sort()
usage += '\n\nSub-Commands:\n '
usage += '\n '.join(subcmds)
parse = PARSER_CLASS(usage=usage)
parse.prog = PROGRAM_NAME
return parse |
python | def diff(self):
""" shortcut to netdiff.diff """
latest = self.latest
current = NetJsonParser(self.json())
return diff(current, latest) |
java | public Map<String, FieldType> flatten() {
if (fields == null || fields.length == 0) {
return Collections.<String, FieldType> emptyMap();
}
Map<String, FieldType> map = new LinkedHashMap<String, FieldType>();
for (Field nestedField : fields) {
addSubFieldToMap(map, nestedField, null);
}
return map;
} |
java | public static String removeSessionId(String sessionId, String page) {
String regexp = ";?jsessionid=" + Pattern.quote(sessionId);
return page.replaceAll(regexp, "");
} |
python | def _sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
# Handle logging - this has to be done first
if self.logCalls:
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
values.pop('frame')
values.pop('self')
(_, filename,
_, _, _, _) = inspect.getouterframes(inspect.currentframe())[1]
if os.path.splitext(os.path.basename(__file__))[0] != \
os.path.splitext(os.path.basename(filename))[0]:
self.callLog.append([inspect.getframeinfo(frame)[2], values])
for col in xrange(self.numColumns):
self.locationInputs[col].addResetToQueue(sequenceId)
self.coarseSensors[col].addResetToQueue(sequenceId)
self.sensors[col].addResetToQueue(sequenceId)
self.network.run(1) |
python | def garud_h(h):
"""Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures
of soft sweeps, as defined in Garud et al. (2015).
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
h1 : float
H1 statistic (sum of squares of haplotype frequencies).
h12 : float
H12 statistic (sum of squares of haplotype frequencies, combining
the two most common haplotypes into a single frequency).
h123 : float
H123 statistic (sum of squares of haplotype frequencies, combining
the three most common haplotypes into a single frequency).
h2_h1 : float
H2/H1 statistic, indicating the "softness" of a sweep.
"""
# check inputs
h = HaplotypeArray(h, copy=False)
# compute haplotype frequencies
f = h.distinct_frequencies()
# compute H1
h1 = np.sum(f**2)
# compute H12
h12 = np.sum(f[:2])**2 + np.sum(f[2:]**2)
# compute H123
h123 = np.sum(f[:3])**2 + np.sum(f[3:]**2)
# compute H2/H1
h2 = h1 - f[0]**2
h2_h1 = h2 / h1
return h1, h12, h123, h2_h1 |
java | @Nonnull
public Word<I> longestCommonPrefix(Word<?> other) {
int len = length(), otherLen = other.length();
int maxIdx = (len < otherLen) ? len : otherLen;
int i = 0;
while (i < maxIdx) {
I sym1 = getSymbol(i);
Object sym2 = other.getSymbol(i);
if (!Objects.equals(sym1, sym2)) {
break;
}
i++;
}
return prefix(i);
} |
python | def get_source(self, environment, template):
'''
Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be relative to
the importing file.
'''
# FIXME: somewhere do seprataor replacement: '\\' => '/'
_template = template
if template.split('/', 1)[0] in ('..', '.'):
is_relative = True
else:
is_relative = False
# checks for relative '..' paths that step-out of file_roots
if is_relative:
# Starts with a relative path indicator
if not environment or 'tpldir' not in environment.globals:
log.warning(
'Relative path "%s" cannot be resolved without an environment',
template
)
raise TemplateNotFound
base_path = environment.globals['tpldir']
_template = os.path.normpath('/'.join((base_path, _template)))
if _template.split('/', 1)[0] == '..':
log.warning(
'Discarded template path "%s": attempts to'
' ascend outside of salt://', template
)
raise TemplateNotFound(template)
self.check_cache(_template)
if environment and template:
tpldir = os.path.dirname(_template).replace('\\', '/')
tplfile = _template
if is_relative:
tpldir = environment.globals.get('tpldir', tpldir)
tplfile = template
tpldata = {
'tplfile': tplfile,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
environment.globals.update(tpldata)
# pylint: disable=cell-var-from-loop
for spath in self.searchpath:
filepath = os.path.join(spath, _template)
try:
with salt.utils.files.fopen(filepath, 'rb') as ifile:
contents = ifile.read().decode(self.encoding)
mtime = os.path.getmtime(filepath)
def uptodate():
try:
return os.path.getmtime(filepath) == mtime
except OSError:
return False
return contents, filepath, uptodate
except IOError:
# there is no file under current path
continue
# pylint: enable=cell-var-from-loop
# there is no template file within searchpaths
raise TemplateNotFound(template) |
python | def get_xy_dataset_statistics_pandas(dataframe, x_series, y_series, fcorrect_x_cutoff = 1.0, fcorrect_y_cutoff = 1.0, x_fuzzy_range = 0.1, y_scalar = 1.0, ignore_null_values = False,
bootstrap_data = False,
expect_negative_correlation = False, STDev_cutoff = 1.0,
run_standardized_analysis = True,
check_multiple_analysis_for_consistency = True):
'''
A version of _get_xy_dataset_statistics which accepts a pandas dataframe rather than X- and Y-value lists.
:param dataframe: A pandas dataframe
:param x_series: The column name of the X-axis series
:param y_series: The column name of the Y-axis series
:param fcorrect_x_cutoff: The X-axis cutoff value for the fraction correct metric.
:param fcorrect_y_cutoff: The Y-axis cutoff value for the fraction correct metric.
:param x_fuzzy_range: The X-axis fuzzy range value for the fuzzy fraction correct metric.
:param y_scalar: The Y-axis scalar multiplier for the fuzzy fraction correct metric (used to calculate y_cutoff and y_fuzzy_range in that metric)
:return: A table of statistics.
'''
x_values = dataframe[x_series].tolist()
y_values = dataframe[y_series].tolist()
return _get_xy_dataset_statistics(x_values, y_values,
fcorrect_x_cutoff = fcorrect_x_cutoff, fcorrect_y_cutoff = fcorrect_y_cutoff, x_fuzzy_range = x_fuzzy_range,
y_scalar = y_scalar, ignore_null_values = ignore_null_values,
bootstrap_data = bootstrap_data,
expect_negative_correlation = expect_negative_correlation,
STDev_cutoff = STDev_cutoff,
run_standardized_analysis = run_standardized_analysis,
check_multiple_analysis_for_consistency = check_multiple_analysis_for_consistency) |
java | public NativeQuery withDMLResultsDisplaySize(int DMLResultsDisplaySize) {
if (!getOperationType(boundStatement).isUpsert) {
options.setDMLResultsDisplaySize(Optional.of(Integer.max(0,Integer.min(DMLResultsDisplaySize, CassandraOptions.MAX_RESULTS_DISPLAY_SIZE))));
}
return this;
} |
java | public static Marshaller createMarshaller(Class clazz, String encoding) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw ExceptionUtil.unchecked(e);
}
} |
python | async def playback(dev: Device, cmd, target, value):
"""Get and set playback settings, e.g. repeat and shuffle.."""
if target and value:
dev.set_playback_settings(target, value)
if cmd == "support":
click.echo("Supported playback functions:")
supported = await dev.get_supported_playback_functions("storage:usb1")
for i in supported:
print(i)
elif cmd == "settings":
print_settings(await dev.get_playback_settings())
# click.echo("Playback functions:")
# funcs = await dev.get_available_playback_functions()
# print(funcs)
else:
click.echo("Currently playing: %s" % await dev.get_play_info()) |
python | def locations(self):
"""
Available locations to be used when creating a new machine.
:returns: A list of available locations.
"""
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/locations')
locations = req.get().json()
return locations |
java | public void setModel (PropertySheetModel pm)
{
if (pm instanceof org.apache.ojb.tools.mapping.reversedb.DBMeta)
{
this.aMeta = (org.apache.ojb.tools.mapping.reversedb.DBMeta)pm;
this.readValuesFromMeta();
}
else
throw new IllegalArgumentException();
} |
python | def get_user_by_userid(self, userid):
''' get user by user id '''
response, status_code = self.__pod__.Users.get_v2_user(
sessionToken=self.__session__,
uid=userid
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response |
java | public static base_response enable(nitro_service client, Long clid) throws Exception {
clusterinstance enableresource = new clusterinstance();
enableresource.clid = clid;
return enableresource.perform_operation(client,"enable");
} |
python | def lookup_command(cmdname, mode):
"""
returns commandclass, argparser and forced parameters used to construct
a command for `cmdname` when called in `mode`.
:param cmdname: name of the command to look up
:type cmdname: str
:param mode: mode identifier
:type mode: str
:rtype: (:class:`Command`, :class:`~argparse.ArgumentParser`,
dict(str->dict))
"""
if cmdname in COMMANDS[mode]:
return COMMANDS[mode][cmdname]
elif cmdname in COMMANDS['global']:
return COMMANDS['global'][cmdname]
else:
return None, None, None |
python | def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
val = hexdecode(text)
if self.pyclass is not None:
return self.pyclass(val)
return val |
java | protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) {
final PatchElement patchElement = entry.element;
final PatchElementImpl element = new PatchElementImpl(patchId);
element.setProvider(patchElement.getProvider());
// Add all the rollback actions
element.getModifications().addAll(modifications);
element.setDescription(patchElement.getDescription());
return element;
} |
java | public static CommerceVirtualOrderItem fetchByUuid_C_First(String uuid,
long companyId,
OrderByComparator<CommerceVirtualOrderItem> orderByComparator) {
return getPersistence()
.fetchByUuid_C_First(uuid, companyId, orderByComparator);
} |
python | def title(self) -> str:
"""Get/Set title string of this document."""
title_element = _find_tag(self.head, 'title')
if title_element:
return title_element.textContent
return '' |
java | public synchronized void add(SocketBox sb) {
int status = ((ManagedSocketBox) sb).getStatus();
if (allSockets.containsKey(sb)) {
throw new IllegalArgumentException("This socket already exists in the socket pool.");
}
allSockets.put(sb, sb);
if (status == ManagedSocketBox.FREE) {
if (freeSockets.containsKey(sb)) {
throw new IllegalArgumentException("This socket already exists in the pool of free sockets.");
}
logger.debug("adding a free socket");
freeSockets.put(sb, sb);
} else {
if (busySockets.containsKey(sb)) {
throw new IllegalArgumentException("This socket already exists in the pool of busy sockets.");
}
logger.debug("adding a busy socket");
busySockets.put(sb, sb);
}
} |
java | public ServiceFuture<SignalRKeysInner> beginRegenerateKeyAsync(String resourceGroupName, String resourceName, final ServiceCallback<SignalRKeysInner> serviceCallback) {
return ServiceFuture.fromResponse(beginRegenerateKeyWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback);
} |
java | protected Map<MarshallerType, AbstractType> getDefaultMarshallers(CfDef cfDef) throws IOException
{
Map<MarshallerType, AbstractType> marshallers = new EnumMap<MarshallerType, AbstractType>(MarshallerType.class);
AbstractType comparator;
AbstractType subcomparator;
AbstractType default_validator;
AbstractType key_validator;
comparator = parseType(cfDef.getComparator_type());
subcomparator = parseType(cfDef.getSubcomparator_type());
default_validator = parseType(cfDef.getDefault_validation_class());
key_validator = parseType(cfDef.getKey_validation_class());
marshallers.put(MarshallerType.COMPARATOR, comparator);
marshallers.put(MarshallerType.DEFAULT_VALIDATOR, default_validator);
marshallers.put(MarshallerType.KEY_VALIDATOR, key_validator);
marshallers.put(MarshallerType.SUBCOMPARATOR, subcomparator);
return marshallers;
} |
java | public static void expandAll(JTree tree, TreePath path, boolean expand)
{
TreeNode node = (TreeNode)path.getLastPathComponent();
if (node.getChildCount() >= 0)
{
Enumeration<?> enumeration = node.children();
while (enumeration.hasMoreElements())
{
TreeNode n = (TreeNode)enumeration.nextElement();
TreePath p = path.pathByAddingChild(n);
expandAll(tree, p, expand);
}
}
if (expand)
{
tree.expandPath(path);
}
else
{
tree.collapsePath(path);
}
} |
java | public void setScript(String newScript) {
String oldScript = script;
script = newScript;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT, oldScript, script));
} |
python | def list_delete(self, id):
"""
Delete a list.
"""
id = self.__unpack_id(id)
self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id)) |
java | @POST
@Path("delete/{repository}/{workspace}/{path:.*}")
public Response deleteScript(@PathParam("repository") String repository, @PathParam("workspace") String workspace,
@PathParam("path") String path)
{
Session ses = null;
try
{
ses =
sessionProviderService.getSessionProvider(null).getSession(workspace,
repositoryService.getRepository(repository));
ses.getItem("/" + path).remove();
ses.save();
return Response.status(Response.Status.NO_CONTENT).build();
}
catch (PathNotFoundException e)
{
String msg = "Path " + path + " does not exists";
LOG.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
{
if (ses != null)
{
ses.logout();
}
}
} |
java | synchronized void setDefaultParent(final Actor defaultParent) {
if (defaultParent != null && this.defaultParent != null) {
throw new IllegalStateException("Default parent already exists.");
}
this.defaultParent = defaultParent;
} |
python | def inverse_qft(qubits: List[int]) -> Program:
"""
Generate a program to compute the inverse quantum Fourier transform on a set of qubits.
:param qubits: A list of qubit indexes.
:return: A Quil program to compute the inverse Fourier transform of the qubits.
"""
qft_result = Program().inst(_core_qft(qubits, -1))
qft_result += bit_reversal(qubits)
inverse_qft = Program()
while len(qft_result) > 0:
new_inst = qft_result.pop()
inverse_qft.inst(new_inst)
return inverse_qft |
java | public List<Method> listMethods( final Class<?> classObj,
final String methodName )
{
//
// Get the array of methods for my classname.
//
Method[] methods = classObj.getMethods();
List<Method> methodSignatures = new ArrayList<Method>();
//
// Loop round all the methods and print them out.
//
for ( int ii = 0; ii < methods.length; ++ii )
{
if ( methods[ii].getName().equals( methodName ) )
{
methodSignatures.add( methods[ii] );
}
}
return methodSignatures;
} |
java | private static String getResourceIconClasses(String resourceTypeName, String fileName, boolean small) {
StringBuffer sb = new StringBuffer(CmsGwtConstants.TYPE_ICON_CLASS);
sb.append(" ").append(getResourceTypeIconClass(resourceTypeName, small)).append(" ").append(
getFileTypeIconClass(resourceTypeName, fileName, small));
return sb.toString();
} |
python | def interp_S_t(S, t, z, z_new, p=None):
''' Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`.
Args
----
S: ndarray
CTD salinities
t: ndarray
CTD temperatures
z: ndarray
CTD Depths, must be a strictly increasing or decreasing 1-D array, and
its length must match the last dimension of `S` and `t`.
z_new: ndarray
Depth to interpolate `S`, `t`, and `p` to. May be a scalar or a sequence.
p: ndarray (optional)
CTD pressures
Returns
-------
S_i: ndarray
Interpolated salinities
t_i: ndarray
Interpolated temperatures
p_i: ndarray
Interpolated pressures. `None` returned if `p` not passed.
Note
----
It is assumed, but not checked, that `S`, `t`, and `z` are all plain
ndarrays, not masked arrays or other sequences.
Out-of-range values of `z_new`, and `nan` in `S` and `t`, yield
corresponding `numpy.nan` in the output.
This method is adapted from the the legacy `python-gsw` package, where
their basic algorithm is from scipy.interpolate.
'''
import numpy
# Create array-like query depth if single value passed
isscalar = False
if not numpy.iterable(z_new):
isscalar = True
z_new = [z_new]
# Type cast to numpy array
z_new = numpy.asarray(z_new)
# Determine if depth direction is inverted
inverted = False
if z[1] - z[0] < 0:
inverted = True
z = z[::-1]
S = S[..., ::-1]
t = t[..., ::-1]
if p is not None:
p = p[..., ::-1]
# Ensure query depths are ordered
if (numpy.diff(z) <= 0).any():
raise ValueError("z must be strictly increasing or decreasing")
# Find z indices where z_new elements can insert with maintained order
hi = numpy.searchsorted(z, z_new)
# Replaces indices below/above with 1 or len(z)-1
hi = hi.clip(1, len(z) - 1).astype(int)
lo = hi - 1
# Get CTD depths above and below query depths
z_lo = z[lo]
z_hi = z[hi]
S_lo = S[lo]
S_hi = S[hi]
t_lo = t[lo]
t_hi = t[hi]
# Calculate distance ratio between CTD depths
z_ratio = (z_new - z_lo) / (z_hi - z_lo)
# Interpolate salinity and temperature with delta and ratio
S_i = S_lo + (S_hi - S_lo) * z_ratio
t_i = t_lo + (t_hi - t_lo) * z_ratio
if p is None:
p_i = None
else:
p_i = p[lo] + (p[hi] - p[lo]) * z_ratio
# Invert interp values if passed depths inverted
if inverted:
S_i = S_i[..., ::-1]
t_i = t_i[..., ::-1]
if p is not None:
p_i = p_i[..., ::-1]
# Replace values not within CTD sample range with `nan`s
outside = (z_new < z.min()) | (z_new > z.max())
if numpy.any(outside):
S_i[..., outside] = numpy.nan
t_i[..., outside] = numpy.nan
if p is not None:
p_i[..., outside] = numpy.nan
# Return single interp values if single query depth passed
if isscalar:
S_i = S_i[0]
t_i = t_i[0]
if p is not None:
p_i = p_i[0]
return S_i, t_i, p_i |
java | public static String getConfigParam(String key, String defaultValue) {
if (config == null) {
init(null);
}
if (StringUtils.isBlank(key)) {
return defaultValue;
}
String keyVar = key.replaceAll("\\.", "_");
String env = System.getenv(keyVar) == null ? System.getenv(PARA + "_" + keyVar) : System.getenv(keyVar);
String sys = System.getProperty(key, System.getProperty(PARA + "." + key));
if (!StringUtils.isBlank(sys)) {
return sys;
} else if (!StringUtils.isBlank(env)) {
return env;
} else {
return (!StringUtils.isBlank(key) && config.hasPath(key)) ? config.getString(key) : defaultValue;
}
} |
java | public Observable<Boolean> beginTransaction(Observable<?> dependency) {
return update("begin").dependsOn(dependency).count().map(Functions.constant(true));
} |
java | public XAttributeNameMap getMapping(String name) {
XAttributeNameMapImpl mapping = mappings.get(name);
if(mapping == null) {
mapping = new XAttributeNameMapImpl(name);
mappings.put(name, mapping);
}
return mapping;
} |
java | public String getTimeString()
{
Calendar cal = getCalendar();
return
toClockString(cal.get(Calendar.HOUR)) +
(((cal.get(Calendar.SECOND) % 2) == 0) ? ":" : " ") +
toClockString(cal.get(Calendar.MINUTE));
} |
python | def get_users(self, capacity=None):
# type: (Optional[str]) -> List[User]
"""Returns the organization's users.
Args:
capacity (Optional[str]): Filter by capacity eg. member, admin. Defaults to None.
Returns:
List[User]: Organization's users.
"""
users = list()
usersdicts = self.data.get('users')
if usersdicts is not None:
for userdata in usersdicts:
if capacity is not None and userdata['capacity'] != capacity:
continue
id = userdata.get('id')
if id is None:
id = userdata['name']
user = hdx.data.user.User.read_from_hdx(id, configuration=self.configuration)
user['capacity'] = userdata['capacity']
users.append(user)
return users |
java | @CheckResult public static boolean onNewIntent(@NonNull Intent intent,
@NonNull Activity activity) {
//noinspection ConstantConditions
checkArgument(intent != null, "intent may not be null");
if (intent.hasExtra(InternalLifecycleIntegration.INTENT_KEY)) {
InternalLifecycleIntegration.require(activity).onNewIntent(intent);
return true;
}
return false;
} |
python | def terminate_all(self):
"""Terminate all worker processes."""
for worker in self._workers:
worker.terminate()
# for thread in self._threads:
# try:
# thread.terminate()
# thread.wait()
# except Exception:
# pass
self._queue_workers = deque() |
python | def set_peripheral(self, power=None, pullup=None, aux=None, chip_select=None):
""" Set the peripheral config at runtime.
If a parameter is None then the config will not be changed.
:param power: Set to True to enable the power supply or False to disable
:param pullup: Set to True to enable the internal pull-up resistors. False to disable
:param aux: Set the AUX pin output state
:param chip_select: Set the CS pin output state
"""
if power is not None:
self.power = power
if pullup is not None:
self.pullup = pullup
if aux is not None:
self.aux = aux
if chip_select is not None:
self.chip_select = chip_select
# Set peripheral status
peripheral_byte = 64
if self.chip_select:
peripheral_byte |= 0x01
if self.aux:
peripheral_byte |= 0x02
if self.pullup:
peripheral_byte |= 0x04
if self.power:
peripheral_byte |= 0x08
self.device.write(bytearray([peripheral_byte]))
response = self.device.read(1)
if response != b"\x01":
raise Exception("Setting peripheral failed. Received: {}".format(repr(response))) |
python | def add_output(self, output):
"""Adds an output to a Transaction's list of outputs.
Args:
output (:class:`~bigchaindb.common.transaction.
Output`): An Output to be added to the
Transaction.
"""
if not isinstance(output, Output):
raise TypeError('`output` must be an Output instance or None')
self.outputs.append(output) |
python | def get_shard_by_key_id(self, key_id):
"""
get_shard_by_key_id returns the Redis shard given a key id.
Keyword arguments:
key_id -- the key id (e.g. '12345')
This is similar to get_shard_by_key(key) except that it will not search
for a key id within the curly braces.
returns a redis.StrictRedis connection
"""
shard_num = self.get_shard_num_by_key_id(key_id)
return self.get_shard_by_num(shard_num) |
python | def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
# Publish ON_RECEIVE message
self.factory.mease.publisher.publish(
message_type=ON_RECEIVE,
client_id=self._client_id,
client_storage=self.storage,
message=payload) |
python | def verify(self):
'''
Verify the correctness of the region arcs. Throws an VennRegionException if verification fails
(or any other exception if it happens during verification).
'''
# Verify size of arcs list
if (len(self.arcs) < 2):
raise VennRegionException("At least two arcs needed in a poly-arc region")
if (len(self.arcs) > 4):
raise VennRegionException("At most 4 arcs are supported currently for poly-arc regions")
TRIG_TOL = 100*tol # We need to use looser tolerance level here because conversion to angles and back is prone to large errors.
# Verify connectedness of arcs
for i in range(len(self.arcs)):
if not np.all(self.arcs[i-1].end_point() - self.arcs[i].start_point() < TRIG_TOL):
raise VennRegionException("Arcs of an poly-arc-gon must be connected via endpoints")
# Verify that arcs do not cross-intersect except at endpoints
for i in range(len(self.arcs)-1):
for j in range(i+1, len(self.arcs)):
ips = self.arcs[i].intersect_arc(self.arcs[j])
for ip in ips:
if not (np.all(abs(ip - self.arcs[i].start_point()) < TRIG_TOL) or np.all(abs(ip - self.arcs[i].end_point()) < TRIG_TOL)):
raise VennRegionException("Arcs of a poly-arc-gon may only intersect at endpoints")
if len(ips) != 0 and (i - j) % len(self.arcs) > 1 and (j - i) % len(self.arcs) > 1:
# Two non-consecutive arcs intersect. This is in general not good, but
# may occasionally happen when all arcs inbetween have length 0.
pass # raise VennRegionException("Non-consecutive arcs of a poly-arc-gon may not intersect")
# Verify that vertices are ordered so that at each point the direction along the polyarc changes towards the left.
# Note that this test only makes sense for polyarcs obtained using circle intersections & subtractions.
# A "flower-like" polyarc may have its vertices ordered counter-clockwise yet the direction would turn to the right at each of them.
for i in range(len(self.arcs)):
prev_arc = self.arcs[i-1]
cur_arc = self.arcs[i]
if box_product(prev_arc.direction_vector(prev_arc.to_angle), cur_arc.direction_vector(cur_arc.from_angle)) < -tol:
raise VennRegionException("Arcs must be ordered so that the direction at each vertex changes counter-clockwise") |
java | public String config(String subFolder, String fileName) {
return setCurrentFilename(subFolder, fileName, CONFIG);
} |
python | def _init_io_container(self, init_value):
"""Initialize container to hold lob data.
Here either a cStringIO or a io.StringIO class is used depending on the Python version.
For CLobs ensure that an initial unicode value only contains valid ascii chars.
"""
if isinstance(init_value, CLOB_STRING_IO_CLASSES):
# already a valid StringIO instance, just use it as it is
v = init_value
else:
# works for strings and unicodes. However unicodes must only contain valid ascii chars!
if PY3:
# a io.StringIO also accepts any unicode characters, but we must be sure that only
# ascii chars are contained. In PY2 we use a cStringIO class which complains by itself
# if it catches this case, so in PY2 no extra check needs to be performed here.
init_value.encode('ascii') # this is just a check, result not needed!
v = CLOB_STRING_IO(init_value)
return v |
python | def xdr(self):
"""Packs and base64 encodes this :class:`Operation` as an XDR string.
"""
op = Xdr.StellarXDRPacker()
op.pack_Operation(self.to_xdr_object())
return base64.b64encode(op.get_buffer()) |
python | def delete_calendar_event(self, id, cancel_reason=None):
"""
Delete a calendar event.
Delete an event from the calendar and return the deleted event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# OPTIONAL - cancel_reason
"""Reason for deleting/canceling the event."""
if cancel_reason is not None:
params["cancel_reason"] = cancel_reason
self.logger.debug("DELETE /api/v1/calendar_events/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/calendar_events/{id}".format(**path), data=data, params=params, no_data=True) |
java | void insertResult(PersistentStore store, Result ins) {
RowSetNavigator nav = ins.initialiseNavigator();
while (nav.hasNext()) {
Object[] data = nav.getNext();
Object[] newData =
(Object[]) ArrayUtil.resizeArrayIfDifferent(data,
getColumnCount());
insertData(store, newData);
}
} |
java | public static Date max(Date d1, Date d2)
{
Date result;
if (d1 == null)
{
result = d2;
}
else
if (d2 == null)
{
result = d1;
}
else
{
result = (d1.compareTo(d2) > 0) ? d1 : d2;
}
return result;
} |
java | public String getTopic()
{
if (tc.isEntryEnabled())
{
SibTr.entry(tc, "getTopic");
SibTr.exit(tc, "getTopic", topic);
}
return topic;
} |
java | public com.google.api.ads.admanager.axis.v201811.DeliveryRateType getDeliveryRateType() {
return deliveryRateType;
} |
java | public static OffsetGroup from(final CharOffset charOffset, final EDTOffset edtOffset) {
return new Builder().charOffset(charOffset).edtOffset(edtOffset).build();
} |
java | public void deleteNode(String path, long zxid)
throws KeeperException.NoNodeException {
int lastSlash = path.lastIndexOf('/');
String parentName = path.substring(0, lastSlash);
String childName = path.substring(lastSlash + 1);
DataNode node = nodes.get(path);
if (node == null) {
throw new KeeperException.NoNodeException();
}
nodes.remove(path);
DataNode parent = nodes.get(parentName);
if (parent == null) {
throw new KeeperException.NoNodeException();
}
synchronized (parent) {
parent.removeChild(childName);
parent.stat.setCversion(parent.stat.getCversion() + 1);
parent.stat.setPzxid(zxid);
long eowner = node.stat.getEphemeralOwner();
if (eowner != 0) {
HashSet<String> nodes = ephemerals.get(eowner);
if (nodes != null) {
synchronized (nodes) {
nodes.remove(path);
}
}
}
node.parent = null;
}
if (parentName.startsWith(procZookeeper)) {
// delete the node in the trie.
if (Quotas.limitNode.equals(childName)) {
// we need to update the trie
// as well
pTrie.deletePath(parentName.substring(quotaZookeeper.length()));
}
}
// also check to update the quotas for this node
String lastPrefix = pTrie.findMaxPrefix(path);
if (!rootZookeeper.equals(lastPrefix) && !("".equals(lastPrefix))) {
// ok we have some match and need to update
updateCount(lastPrefix, -1);
int bytes = 0;
synchronized (node) {
bytes = (node.data == null ? 0 : -(node.data.length));
}
updateBytes(lastPrefix, bytes);
}
if (LOG.isTraceEnabled()) {
ZooTrace.logTraceMessage(LOG, ZooTrace.EVENT_DELIVERY_TRACE_MASK,
"dataWatches.triggerWatch " + path);
ZooTrace.logTraceMessage(LOG, ZooTrace.EVENT_DELIVERY_TRACE_MASK,
"childWatches.triggerWatch " + parentName);
}
Set<Watcher> processed = dataWatches.triggerWatch(path,
EventType.NodeDeleted);
childWatches.triggerWatch(path, EventType.NodeDeleted, processed);
childWatches.triggerWatch(parentName.equals("") ? "/" : parentName,
EventType.NodeChildrenChanged);
} |
java | public static TransTypes instance(Context context) {
TransTypes instance = context.get(transTypesKey);
if (instance == null)
instance = new TransTypes(context);
return instance;
} |
java | public static <T, R> List<R> processList(Class<R> clazz, List<T> src, BiConsumer<R, T> biConsumer) {
if (!Lists.iterable(src)) {
log.warn("the src argument must be not null, return empty list. ");
return Lists.newArrayList();
}
return src.stream().map(e -> process(clazz, e, biConsumer)).collect(Collectors.toList());
} |
java | private void handleLeaveEvent(Node node) {
members.compute(MemberId.from(node.id().id()), (id, member) -> member == null || !member.isActive() ? null : member);
} |
python | def get_context_data(self, **kwargs):
"""
Hook for adding arguments to the context.
"""
context = {'obj': self.object }
if 'queryset' in kwargs:
context['conf_msg'] = self.get_confirmation_message(kwargs['queryset'])
context.update(kwargs)
return context |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.