language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def get_sync_binding_cmds(self, switch_bindings, expected_bindings):
"""Returns the list of commands required to synchronize ACL bindings
1. Delete any unexpected bindings
2. Add any missing bindings
"""
switch_cmds = list()
# Update any necessary switch interface ACLs
bindings_to_delete = switch_bindings - expected_bindings
bindings_to_add = expected_bindings - switch_bindings
for intf, acl, direction in bindings_to_delete:
switch_cmds.extend(['interface %s' % intf,
'no ip access-group %s %s' %
(acl, direction),
'exit'])
for intf, acl, direction in bindings_to_add:
switch_cmds.extend(['interface %s' % intf,
'ip access-group %s %s' % (acl, direction),
'exit'])
return switch_cmds |
python | def parse_rst_index(rstpth):
"""
Parse the top-level RST index file, at `rstpth`, for the example
python scripts. Returns a list of subdirectories in order of
appearance in the index file, and a dict mapping subdirectory name
to a description.
"""
pthidx = {}
pthlst = []
with open(rstpth) as fd:
lines = fd.readlines()
for i, l in enumerate(lines):
if i > 0:
if re.match(r'^ \w+', l) is not None and \
re.match(r'^\w+', lines[i - 1]) is not None:
# List of subdirectories in order of appearance in index.rst
pthlst.append(lines[i - 1][:-1])
# Dict mapping subdirectory name to description
pthidx[lines[i - 1][:-1]] = l[2:-1]
return pthlst, pthidx |
java | public String updateRunner(String oldRunnerName, Vector<Object> runnerParams)
{
return serviceDelegator.updateRunner(oldRunnerName, runnerParams);
} |
java | public UUID getMachineId() throws NoSuchAlgorithmException,
SocketException, UnknownHostException {
return calculator.getMachineId(useNetwork, useHostName, useArchitecture);
} |
java | public final DRL5Expressions.operator_key_return operator_key() throws RecognitionException {
DRL5Expressions.operator_key_return retval = new DRL5Expressions.operator_key_return();
retval.start = input.LT(1);
Token id=null;
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:771:3: ({...}? =>id= ID )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:771:10: {...}? =>id= ID
{
if ( !(((helper.isPluggableEvaluator(false)))) ) {
if (state.backtracking>0) {state.failed=true; return retval;}
throw new FailedPredicateException(input, "operator_key", "(helper.isPluggableEvaluator(false))");
}
id=(Token)match(input,ID,FOLLOW_ID_in_operator_key4794); if (state.failed) return retval;
if ( state.backtracking==0 ) { helper.emit(id, DroolsEditorType.KEYWORD); }
}
retval.stop = input.LT(-1);
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
return retval;
} |
python | def get_wordlist(language, word_source):
""" Takes in a language and a word source and returns a matching wordlist,
if it exists.
Valid languages: ['english']
Valid word sources: ['bip39', 'wiktionary', 'google']
"""
try:
wordlist_string = eval(language + '_words_' + word_source)
except NameError:
raise Exception("No wordlist could be found for the word source and language provided.")
wordlist = wordlist_string.split(',')
return wordlist |
python | def strlify(a):
'''
Used to turn hexlify() into hex string.
Does nothing in Python 2, but is necessary for Python 3, so that
all inputs and outputs are always the same encoding. Most of the
time it doesn't matter, but some functions in Python 3 brick when
they get bytes instead of a string, so it's safer to just
strlify() everything.
In Python 3 for example (examples commented out for doctest):
# >>> hexlify(unhexlify("a1b2c3"))
b'a1b2c3'
# >>> b'a1b2c3' == 'a1b2c3'
False
# >>> strlify(hexlify(unhexlify("a1b2c3")))
'a1b2c3'
Whereas in Python 2, the results would be:
# >>> hexlify(unhexlify("a1b2c3"))
'a1b2c3'
# >>> b'a1b2c3' == 'a1b2c3'
True
# >>> strlify(hexlify(unhexlify("a1b2c3")))
'a1b2c3'
Safe to use redundantly on hex and base64 that may or may not be
byte objects, as well as base58, since hex and base64 and base58
strings will never have "b'" in the middle of them.
Obviously it's NOT safe to use on random strings which might have
"b'" in the middle of the string.
Use this for making sure base 16/58/64 objects are in string
format.
Use normalize_input() below to convert unicode objects back to
ascii strings when possible.
'''
if a == b'b' or a == 'b':
return 'b'
return str(a).rstrip("'").replace("b'","",1).replace("'","") |
java | public long alignOnMagic3(InputStream is) throws IOException {
long bytesSkipped = 0;
byte lookahead[] = new byte[3];
int keep = 0;
while(true) {
if(keep == 2) {
lookahead[0] = lookahead[1];
lookahead[1] = lookahead[2];
} else if(keep == 1) {
lookahead[0] = lookahead[2];
}
int amt = is.read(lookahead, keep, 3 - keep);
if(amt == -1) {
long skippedBeforeEOF = bytesSkipped + keep;
if(skippedBeforeEOF == 0) {
return SEARCH_EOF_AT_START;
}
return -1 * skippedBeforeEOF;
}
// TODO: handle read < # of bytes wanted...
// we have 3 bytes, can it be a gzipmember?
// Legend:
// ? = uninspected byte
// 1 = gzip magic 1
// 2 = gzip magic 2
// ! = wrong byte value
// ???
if(lookahead[0] != GZIP_MAGIC_ONE) {
// !??
// nope. are the next 2 possibilities?
if((lookahead[1] == GZIP_MAGIC_ONE) &&
(lookahead[2] == GZIP_MAGIC_TWO)) {
// !12
keep = 2;
} else if(lookahead[2] == GZIP_MAGIC_ONE) {
// !!1
keep = 1;
} else {
// !!!
keep = 0;
}
bytesSkipped += (3-keep);
continue;
}
// 1??
if((lookahead[1] & 0xff) != GZIP_MAGIC_TWO) {
// 1!?
// nope. is the last a possible start?
if(lookahead[2] == GZIP_MAGIC_ONE) {
// 1!1
keep = 1;
} else {
// 1!!
// just keep lookin, no backtrack
keep = 0;
}
bytesSkipped += (3-keep);
continue;
}
// 12?
if(!GZIPHeader.isValidCompressionMethod(lookahead[2])) {
if(lookahead[2] == GZIP_MAGIC_ONE) {
// 121
keep = 1;
} else {
// 12!
// just keep lookin, no backtrack
}
bytesSkipped += (3-keep);
continue;
}
// found it!
return bytesSkipped;
}
} |
java | public void marshall(Output output, ProtocolMarshaller protocolMarshaller) {
if (output == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(output.getAudioDescriptions(), AUDIODESCRIPTIONS_BINDING);
protocolMarshaller.marshall(output.getCaptionDescriptions(), CAPTIONDESCRIPTIONS_BINDING);
protocolMarshaller.marshall(output.getContainerSettings(), CONTAINERSETTINGS_BINDING);
protocolMarshaller.marshall(output.getExtension(), EXTENSION_BINDING);
protocolMarshaller.marshall(output.getNameModifier(), NAMEMODIFIER_BINDING);
protocolMarshaller.marshall(output.getOutputSettings(), OUTPUTSETTINGS_BINDING);
protocolMarshaller.marshall(output.getPreset(), PRESET_BINDING);
protocolMarshaller.marshall(output.getVideoDescription(), VIDEODESCRIPTION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | private synchronized void load(int year) {
if (alreadyLoadedYears.contains(year)) {
return;
}
alreadyLoadedYears.add(year);
ZonedDateTime st = ZonedDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN, ZoneId.systemDefault());
ZonedDateTime et = ZonedDateTime.of(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX, ZoneId.systemDefault());
try {
startBatchUpdates();
/*
* Convert start and end times from new java.time API to old API and then to ical API :-)
*/
Period period = new Period(
new DateTime(Date.from(st.toInstant())),
new DateTime(Date.from(et.toInstant())));
Rule[] rules = new Rule[]{new PeriodRule(period)};
Filter filter = new Filter(rules, Filter.MATCH_ANY);
@SuppressWarnings("unchecked")
Collection<VEvent> events = filter.filter(calendar.getComponents(Component.VEVENT));
for (VEvent evt : events) {
if (loadedEventIds.contains(evt.getUid())) {
continue;
}
loadedEventIds.add(evt.getUid());
ICalCalendarEntry entry = new ICalCalendarEntry(evt);
ZonedDateTime entryStart = ZonedDateTime.ofInstant(evt.getStartDate().getDate().toInstant(), ZoneId.systemDefault());
ZonedDateTime entryEnd = ZonedDateTime.ofInstant(evt
.getEndDate().getDate().toInstant(),
ZoneId.systemDefault());
if (entryEnd.toLocalDate().isAfter(entryStart.toLocalDate())) {
entryEnd = entryEnd.minusDays(1);
entry.setFullDay(true);
}
entry.setInterval(new Interval(entryStart, entryEnd));
final Property prop = evt.getProperty("RRULE");
if (prop instanceof RRule) {
RRule rrule = (RRule) prop;
entry.setRecurrenceRule("RRULE:" + rrule.getValue());
}
addEntry(entry);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
stopBatchUpdates();
}
} |
python | def get_book_lookup_session(self):
"""Gets the ``OsidSession`` associated with the book lookup service.
return: (osid.commenting.BookLookupSession) - a
``BookLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_book_lookup()`` is ``false``
*compliance: optional -- This method must be implemented if
``supports_book_lookup()`` is ``true``.*
"""
if not self.supports_book_lookup():
raise errors.Unimplemented()
# pylint: disable=no-member
return sessions.BookLookupSession(runtime=self._runtime) |
java | public <T> MutateInBuilder arrayInsert(String path, T value) {
asyncBuilder.arrayInsert(path, value);
return this;
} |
java | public static WarpExecutionBuilder initiate(Activity activity) {
WarpRuntime runtime = WarpRuntime.getInstance();
if (runtime == null) {
throw new IllegalStateException(
"The Warp runtime isn't initialized. You need to make sure arquillian-warp-impl is on classpath and annotate a test class with @WarpTest in order to initialize Warp.");
}
return runtime.getWarpActivityBuilder().initiate(activity);
} |
python | def pop_event(self):
"""Pop an event from event_list."""
if len(self.event_list) > 0:
evt = self.event_list.pop(0)
return evt
return None |
python | def users(self):
"""
Returns known users by exposing as a read-only property.
"""
if not hasattr(self, "_users"):
us = {}
if "users" in self.doc:
for ur in self.doc["users"]:
us[ur["name"]] = u = copy.deepcopy(ur["user"])
BytesOrFile.maybe_set(u, "client-certificate")
BytesOrFile.maybe_set(u, "client-key")
self._users = us
return self._users |
python | def run_process(*args, **kwargs):
"""API used up to version 0.2.0."""
warnings.warn(
"procrunner.run_process() is deprecated and has been renamed to run()",
DeprecationWarning,
stacklevel=2,
)
return run(*args, **kwargs) |
python | def load_query_string_data(request_schema, query_string_data=None):
"""
Load query string data using the given schema.
Schemas are assumed to be compatible with the `PageSchema`.
"""
if query_string_data is None:
query_string_data = request.args
request_data = request_schema.load(query_string_data)
if request_data.errors:
# pass the validation errors back in the context
raise with_context(UnprocessableEntity("Validation error"), dict(errors=request_data.errors))
return request_data.data |
python | def toDebugString(self):
"""
Returns a printable version of the configuration, as a list of
key=value pairs, one per line.
"""
if self._jconf is not None:
return self._jconf.toDebugString()
else:
return '\n'.join('%s=%s' % (k, v) for k, v in self._conf.items()) |
python | def defaults(d1, d2):
"""
Update a copy of d1 with the contents of d2 that are
not in d1. d1 and d2 are dictionary like objects.
Parameters
----------
d1 : dict | dataframe
dict with the preferred values
d2 : dict | dataframe
dict with the default values
Returns
-------
out : dict | dataframe
Result of adding default values type of d1
"""
d1 = d1.copy()
tolist = isinstance(d2, pd.DataFrame)
keys = (k for k in d2 if k not in d1)
for k in keys:
if tolist:
d1[k] = d2[k].tolist()
else:
d1[k] = d2[k]
return d1 |
python | def tox_get_python_executable(envconfig):
"""Return a python executable for the given python base name.
The first plugin/hook which returns an executable path will determine it.
``envconfig`` is the testenv configuration which contains
per-testenv configuration, notably the ``.envname`` and ``.basepython``
setting.
"""
try:
# pylint: disable=no-member
pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv')
or 'pyenv')
cmd = [pyenv, 'which', envconfig.basepython]
pipe = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
out, err = pipe.communicate()
except OSError:
err = '\'pyenv\': command not found'
LOG.warning(
"pyenv doesn't seem to be installed, you probably "
"don't want this plugin installed either."
)
else:
if pipe.poll() == 0:
return out.strip()
else:
if not envconfig.tox_pyenv_fallback:
raise PyenvWhichFailed(err)
LOG.debug("`%s` failed thru tox-pyenv plugin, falling back. "
"STDERR: \"%s\" | To disable this behavior, set "
"tox_pyenv_fallback=False in your tox.ini or use "
" --tox-pyenv-no-fallback on the command line.",
' '.join([str(x) for x in cmd]), err) |
python | def get_metrics(self, reset: bool = False) -> Dict[str, float]:
"""
We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
on denotation accuracy for the set of examples where we actually have DPD output. We
only score dpd_acc on that subset.
2. denotation_acc, which is the percentage of examples where we get the correct
denotation. This is the typical "accuracy" metric, and it is what you should usually
report in an experimental result. You need to be careful, though, that you're
computing this on the full data, and not just the subset that has DPD output (make sure
you pass "keep_if_no_dpd=True" to the dataset reader, which we do for validation data,
but not training data).
3. lf_percent, which is the percentage of time that decoding actually produces a
finished logical form. We might not produce a valid logical form if the decoder gets
into a repetitive loop, or we're trying to produce a super long logical form and run
out of time steps, or something.
"""
return {
'dpd_acc': self._action_sequence_accuracy.get_metric(reset),
'denotation_acc': self._denotation_accuracy.get_metric(reset),
'lf_percent': self._has_logical_form.get_metric(reset),
} |
java | public int getDistance(Node node1, Node node2) {
if (node1 == node2) {
return 0;
}
Node n1=node1, n2=node2;
int dis = 0;
netlock.readLock().lock();
try {
int level1=node1.getLevel(), level2=node2.getLevel();
while(n1!=null && level1>level2) {
n1 = n1.getParent();
level1--;
dis++;
}
while(n2!=null && level2>level1) {
n2 = n2.getParent();
level2--;
dis++;
}
while(n1!=null && n2!=null && n1.getParent()!=n2.getParent()) {
n1=n1.getParent();
n2=n2.getParent();
dis+=2;
}
} finally {
netlock.readLock().unlock();
}
if (n1==null) {
LOG.warn("The cluster does not contain node: "+NodeBase.getPath(node1));
return Integer.MAX_VALUE;
}
if (n2==null) {
LOG.warn("The cluster does not contain node: "+NodeBase.getPath(node2));
return Integer.MAX_VALUE;
}
return dis+2;
} |
python | def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool:
"""
Upload file into Google Drive
:param folder_id:
:param file_name:
:param mine_type:
:return:
"""
service = self.__get_service()
media_body = MediaFileUpload(file_name, mimetype=mine_type, resumable=True)
body = {
'name': os.path.split(file_name)[-1],
'mimeType': "text/csv",
'parents': [folder_id],
}
return service.files().create(body=body, media_body=media_body).execute() |
java | public AttackDetail withSubResources(SubResourceSummary... subResources) {
if (this.subResources == null) {
setSubResources(new java.util.ArrayList<SubResourceSummary>(subResources.length));
}
for (SubResourceSummary ele : subResources) {
this.subResources.add(ele);
}
return this;
} |
python | def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index) |
java | public static BooleanOperation value() {
JcValue val = new WhenJcValue();
BooleanOperation ret = P.valueOf(val);
ASTNode an = APIObjectAccess.getAstNode(ret);
an.setClauseType(ClauseType.WHEN);
return ret;
} |
python | def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns y-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.sin(phi2) |
python | def plot(self):
"""
Returns a hvPlot object to provide a high-level plotting API.
To display in a notebook, be sure to run ``intake.output_notebook()``
first.
"""
try:
from hvplot import hvPlot
except ImportError:
raise ImportError("The intake plotting API requires hvplot."
"hvplot may be installed with:\n\n"
"`conda install -c pyviz hvplot` or "
"`pip install hvplot`.")
metadata = self.metadata.get('plot', {})
fields = self.metadata.get('fields', {})
for attrs in fields.values():
if 'range' in attrs:
attrs['range'] = tuple(attrs['range'])
metadata['fields'] = fields
plots = self.metadata.get('plots', {})
return hvPlot(self, custom_plots=plots, **metadata) |
python | def OnPadIntCtrl(self, event):
"""Pad IntCtrl event handler"""
self.attrs["pad"] = event.GetValue()
post_command_event(self, self.DrawChartMsg) |
java | public static byte[] decodeBase64(String encodedData) {
BufferedReader reader = new BufferedReader(new StringReader(encodedData));
int length = encodedData.length();
byte[] retval = new byte[length];
int actualLength = 0;
String line;
try {
while ((line = reader.readLine()) != null) {
byte[] rawData = line.getBytes();
int n = 0;
for (int i = 0; i < rawData.length; i += 4) {
n = (base64Chars.indexOf(rawData[i]) << 18) |
(base64Chars.indexOf(rawData[i + 1]) << 12);
retval[actualLength++] = (byte) ((n >>> 16) & 255);
if (rawData[i + 2] != '=') {
n |= (base64Chars.indexOf(rawData[i + 2]) << 6);
retval[actualLength++] = (byte) ((n >>> 8) & 255);
}
if (rawData[i + 3] != '=') {
n |= (base64Chars.indexOf(rawData[i + 3]));
retval[actualLength++] = (byte) (n & 255);
}
}
}
}
catch (IOException ioe) {
throw new IllegalStateException("exception while reading input with message: " + ioe);
}
if (actualLength != length) {
byte[] actualRetval = new byte[actualLength];
System.arraycopy(retval, 0, actualRetval, 0, actualLength);
return actualRetval;
}
return retval;
} |
python | def set_or_clear_breakpoint(self):
"""Set/Clear breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_or_clear_breakpoint() |
java | @Override
public Object getMember(String name) {
switch (name) {
case "format":
return F_format;
case "schema":
return F_schema;
case "option":
return F_option;
case "load":
return F_load;
case "json":
return F_json;
case "csv":
return F_csv;
case "parquet":
return F_parquet;
case "text":
return F_text;
}
return super.getMember(name);
} |
java | private synchronized static Pattern getPattern(String tagName,
String attrName) {
String key = tagName + " " + attrName;
Pattern pc = pcPatterns.get(key);
if (pc == null) {
String tagPatString = "<\\s*" + tagName + "\\s+[^>]*\\b" + attrName
+ "\\s*=\\s*(" + ANY_ATTR_VALUE + ")(?:\\s|>)?";
pc = Pattern.compile(tagPatString, Pattern.CASE_INSENSITIVE);
pcPatterns.put(key, pc);
}
return pc;
} |
java | boolean handleSortOrder(final List<SortMeta> sortOrder) {
boolean changed = false;
if (sortOrder == null) {
if (multiSortBy != null) {
adaptee.clearSorting();
multiSortBy = null;
lastSorting = null;
changed = true;
}
} else {
final List<SortProperty> newSorting = convert2SortProperty(sortOrder);
if (!newSorting.equals(lastSorting)) {
adaptee.setSorting(newSorting);
multiSortBy = sortOrder;
lastSorting = newSorting;
changed = true;
}
}
return changed;
} |
python | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state |
python | def crop(self, height, width, center_i=None, center_j=None):
"""Crop the image centered around center_i, center_j.
Parameters
----------
height : int
The height of the desired image.
width : int
The width of the desired image.
center_i : int
The center height point at which to crop. If not specified, the center
of the image is used.
center_j : int
The center width point at which to crop. If not specified, the center
of the image is used.
Returns
-------
:obj:`Image`
A cropped Image of the same type.
"""
# compute crop center px
height = int(np.round(height))
width = int(np.round(width))
if center_i is None:
center_i = float(self.height) / 2
if center_j is None:
center_j = float(self.width) / 2
# crop using PIL
desired_start_row = int(np.floor(center_i - float(height) / 2))
desired_end_row = int(np.floor(center_i + float(height) / 2))
desired_start_col = int(np.floor(center_j - float(width) / 2))
desired_end_col = int(np.floor(center_j + float(width) / 2))
pil_im = PImage.fromarray(self.data)
cropped_pil_im = pil_im.crop((desired_start_col,
desired_start_row,
desired_end_col,
desired_end_row))
crop_data = np.array(cropped_pil_im)
if crop_data.shape[0] != height or crop_data.shape[1] != width:
raise ValueError('Crop dims are incorrect')
return type(self)(crop_data.astype(self.data.dtype), self._frame) |
java | public String generatePoolsConfigIfClassSet() {
if (poolsConfigDocumentGenerator == null) {
return null;
}
Document document = poolsConfigDocumentGenerator.generatePoolsDocument();
if (document == null) {
LOG.warn("generatePoolsConfig: Did not generate a valid pools xml file");
return null;
}
// Write the content into a temporary xml file and rename to the
// expected file.
File tempXmlFile;
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", new Integer(2));
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(document);
tempXmlFile = File.createTempFile("tmpPoolsConfig", "xml");
if (LOG.isDebugEnabled()) {
StreamResult stdoutResult = new StreamResult(System.out);
transformer.transform(source, stdoutResult);
}
StreamResult result = new StreamResult(tempXmlFile);
transformer.transform(source, result);
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(
new FileInputStream(tempXmlFile));
File destXmlFile = new File(conf.getPoolsConfigFile());
boolean success = tempXmlFile.renameTo(destXmlFile);
LOG.info("generatePoolConfig: Renamed generated file " +
tempXmlFile.getAbsolutePath() + " to " +
destXmlFile.getAbsolutePath() + " returned " + success +
" with md5sum " + md5);
return md5;
} catch (TransformerConfigurationException e) {
LOG.warn("generatePoolConfig: Failed to write file", e);
} catch (IOException e) {
LOG.warn("generatePoolConfig: Failed to write file", e);
} catch (TransformerException e) {
LOG.warn("generatePoolConfig: Failed to write file", e);
}
return null;
} |
python | def as_tree(self, visitor=None, children=None):
""" Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by default) consists of a list of dictionary
representations of its children.
See :meth:`CTENodeManager.as_tree` and
:meth:`CTENodeManager.node_as_tree` for details on how this method
works, as well as its expected arguments.
:param visitor: optional function responsible for generating the
dictionary representation of a node.
:param children: optional function responsible for generating a
children key and list for a node.
:return: a dictionary representation of the structure of the forest.
"""
_parameters = {"node": self}
if visitor is not None:
_parameters["visitor"] = visitor
if children is not None:
_parameters["children"] = children
return self.__class__.objects.node_as_tree(**_parameters) |
java | public static JavaPlatform register(Config config) {
// guard against multiple-registration (only in headless mode because this can happen when
// running tests in Maven; in non-headless mode, we want to fail rather than silently ignore
// erroneous repeated registration)
if (config.headless && testInstance != null) {
return testInstance;
}
JavaPlatform instance = new JavaPlatform(config);
if (config.headless) {
testInstance = instance;
}
PlayN.setPlatform(instance);
return instance;
} |
python | def _getHessian(self):
"""
Internal function for estimating parameter uncertainty
COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y)
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Hessian'] is None:
ParamMask=self.gp.getParamMask()['covar']
std=sp.zeros(ParamMask.sum())
H=self.gp.LMLhess_covar()
It= (ParamMask[:,0]==1)
self.cache['Hessian']=H[It,:][:,It]
return self.cache['Hessian'] |
python | def _sections_to_raw_data(sections):
'''convert list of sections into the `raw_data` format used in neurom
This finds the soma, and attaches the neurites
'''
soma = None
neurites = []
for section in sections:
neurite = _extract_section(section)
if neurite is None:
continue
elif neurite[0][COLS.TYPE] == POINT_TYPE.SOMA:
assert soma is None, 'Multiple somas defined in file'
soma = neurite
else:
neurites.append(neurite)
assert soma is not None, 'Missing CellBody element (ie. soma)'
total_length = len(soma) + sum(len(neurite) for neurite in neurites)
ret = np.zeros((total_length, 7,), dtype=np.float64)
pos = len(soma)
ret[0:pos, :] = soma
for neurite in neurites:
end = pos + len(neurite)
ret[pos:end, :] = neurite
ret[pos:end, COLS.P] += pos
ret[pos:end, COLS.ID] += pos
# TODO: attach the neurite at the closest point on the soma
ret[pos, COLS.P] = len(soma) - 1
pos = end
return ret |
java | public static int filterCountByG_T_E(long groupId, String type,
boolean enabled) {
return getPersistence().filterCountByG_T_E(groupId, type, enabled);
} |
python | def write_system_config(base_url, datadir, tooldir):
"""Write a bcbio_system.yaml configuration file with tool information.
"""
out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url))
if not os.path.exists(os.path.dirname(out_file)):
os.makedirs(os.path.dirname(out_file))
if os.path.exists(out_file):
# if no tool directory and exists, do not overwrite
if tooldir is None:
return out_file
else:
bak_file = out_file + ".bak%s" % (datetime.datetime.now().strftime("%Y%M%d_%H%M"))
shutil.copy(out_file, bak_file)
if tooldir:
java_basedir = os.path.join(tooldir, "share", "java")
rewrite_ignore = ("log",)
with contextlib.closing(urllib_request.urlopen(base_url)) as in_handle:
with open(out_file, "w") as out_handle:
in_resources = False
in_prog = None
for line in (l.decode("utf-8") for l in in_handle):
if line[0] != " ":
in_resources = line.startswith("resources")
in_prog = None
elif (in_resources and line[:2] == " " and line[2] != " "
and not line.strip().startswith(rewrite_ignore)):
in_prog = line.split(":")[0].strip()
# Update java directories to point to install directory, avoid special cases
elif line.strip().startswith("dir:") and in_prog and in_prog not in ["log", "tmp"]:
final_dir = os.path.basename(line.split()[-1])
if tooldir:
line = "%s: %s\n" % (line.split(":")[0],
os.path.join(java_basedir, final_dir))
in_prog = None
elif line.startswith("galaxy"):
line = "# %s" % line
out_handle.write(line)
return out_file |
python | def handle_api_exceptions_inter(self, method, *url_parts, **kwargs):
"""The main (middle) part - it is enough if no error occurs."""
global request_count # used only in single thread tests - OK # pylint:disable=global-statement
# log.info("request %s %s", method, '/'.join(url_parts))
# import pdb; pdb.set_trace() # NOQA
api_ver = kwargs.pop('api_ver', None)
url = self.rest_api_url(*url_parts, api_ver=api_ver)
# The 'verify' option is about verifying TLS certificates
kwargs_in = {'timeout': getattr(settings, 'SALESFORCE_QUERY_TIMEOUT', (4, 15)),
'verify': True}
kwargs_in.update(kwargs)
log.debug('Request API URL: %s', url)
request_count += 1
session = self.sf_session
try:
response = session.request(method, url, **kwargs_in)
except requests.exceptions.Timeout:
raise SalesforceError("Timeout, URL=%s" % url)
if response.status_code == 401: # Unauthorized
# Reauthenticate and retry (expired or invalid session ID or OAuth)
if ('json' in response.headers['content-type']
and response.json()[0]['errorCode'] == 'INVALID_SESSION_ID'):
token = session.auth.reauthenticate()
if 'headers' in kwargs:
kwargs['headers'].update(Authorization='OAuth %s' % token)
try:
response = session.request(method, url, **kwargs_in)
except requests.exceptions.Timeout:
raise SalesforceError("Timeout, URL=%s" % url)
if response.status_code < 400: # OK
# 200 "OK" (GET, POST)
# 201 "Created" (POST)
# 204 "No Content" (DELETE)
# 300 ambiguous items for external ID.
# 304 "Not Modified" (after conditional HEADER request for metadata),
return response
# status codes docs (400, 403, 404, 405, 415, 500)
# https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/errorcodes.htm
self.raise_errors(response) |
python | def element_id_by_label(browser, label):
"""Return the id of a label's for attribute"""
label = XPathSelector(browser,
unicode('//label[contains(., "%s")]' % label))
if not label:
return False
return label.get_attribute('for') |
python | async def build_revoc_reg_entry_request(submitter_did: str,
revoc_reg_def_id: str,
rev_def_type: str,
value: str) -> str:
"""
Builds a REVOC_REG_ENTRY request. Request to add the RevocReg entry containing
the new accumulator value and issued/revoked indices.
This is just a delta of indices, not the whole list. So, it can be sent each time a new credential is issued/revoked.
:param submitter_did: DID of the submitter stored in secured Wallet.
:param revoc_reg_def_id: ID of the corresponding RevocRegDef.
:param rev_def_type: Revocation Registry type (only CL_ACCUM is supported for now).
:param value: Registry-specific data:
{
value: {
prevAccum: string - previous accumulator value.
accum: string - current accumulator value.
issued: array<number> - an array of issued indices.
revoked: array<number> an array of revoked indices.
},
ver: string - version revocation registry entry json
}
:return: Request result as json.
"""
logger = logging.getLogger(__name__)
logger.debug("build_revoc_reg_entry_request: >>> submitter_did: %r, rev_def_type: %r, revoc_reg_def_id: %r, "
"value: %r", submitter_did, rev_def_type, revoc_reg_def_id, value)
if not hasattr(build_revoc_reg_entry_request, "cb"):
logger.debug("build_revoc_reg_entry_request: Creating callback")
build_revoc_reg_entry_request.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))
c_submitter_did = c_char_p(submitter_did.encode('utf-8'))
c_rev_def_type = c_char_p(rev_def_type.encode('utf-8'))
c_revoc_reg_def_id = c_char_p(revoc_reg_def_id.encode('utf-8'))
c_value = c_char_p(value.encode('utf-8'))
request_json = await do_call('indy_build_revoc_reg_entry_request',
c_submitter_did,
c_revoc_reg_def_id,
c_rev_def_type,
c_value,
build_revoc_reg_entry_request.cb)
res = request_json.decode()
logger.debug("build_revoc_reg_entry_request: <<< res: %r", res)
return res |
java | public void doGet(String url, HttpResponse response) {
doGet(url, response, null, true);
} |
python | def is_string(value,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
"""Indicate whether ``value`` is a string.
:param value: The value to evaluate.
:param coerce_value: If ``True``, will check whether ``value`` can be coerced
to a string if it is not already. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if value is None:
return False
minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs)
maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs)
if isinstance(value, basestring) and not value:
if minimum_length and minimum_length > 0 and not whitespace_padding:
return False
return True
try:
value = validators.string(value,
coerce_value = coerce_value,
minimum_length = minimum_length,
maximum_length = maximum_length,
whitespace_padding = whitespace_padding,
**kwargs)
except SyntaxError as error:
raise error
except Exception:
return False
return True |
java | public static QueryRootNode createQuery(String statement,
LocationFactory resolver,
QueryNodeFactory factory)
throws InvalidQueryException {
return new XPathQueryBuilder(statement, resolver, factory).getRootNode();
} |
python | def convert_to_bool(text):
""" Convert a few common variations of "true" and "false" to boolean
:param text: string to test
:return: boolean
:raises: ValueError
"""
# handle "1" and "0"
try:
return bool(int(text))
except:
pass
text = str(text).lower()
if text == "true":
return True
if text == "yes":
return True
if text == "false":
return False
if text == "no":
return False
raise ValueError |
java | public static ErrorDescription create(Throwable ex, String correlationId) {
ErrorDescription description = new ErrorDescription();
description.setType(ex.getClass().getCanonicalName());
description.setCategory(ErrorCategory.Unknown);
description.setStatus(500);
description.setCode("Unknown");
description.setMessage(ex.getMessage());
Throwable t = ex.getCause();
description.setCause(t != null ? t.toString() : null);
StackTraceElement[] ste = ex.getStackTrace();
StringBuilder builder = new StringBuilder();
if (ste != null) {
for (int i = 0; i < ste.length; i++) {
if (builder.length() > 0)
builder.append(" ");
builder.append(ste[i].toString());
}
}
description.setStackTrace(builder.toString());
description.setCorrelationId(correlationId);
return description;
} |
java | private void pattern(Attributes attributes) throws SVGParseException
{
debug("<pattern>");
if (currentElement == null)
throw new SVGParseException("Invalid document. Root element must be <svg>");
SVG.Pattern obj = new SVG.Pattern();
obj.document = svgDocument;
obj.parent = currentElement;
parseAttributesCore(obj, attributes);
parseAttributesStyle(obj, attributes);
parseAttributesConditional(obj, attributes);
parseAttributesViewBox(obj, attributes);
parseAttributesPattern(obj, attributes);
currentElement.addChild(obj);
currentElement = obj;
} |
python | def connection(self):
"""return authenticated connection"""
c = pymongo.MongoClient(
self.hostname, fsync=True,
socketTimeoutMS=self.socket_timeout, **self.kwargs)
connected(c)
if not self.is_mongos and self.login and not self.restart_required:
db = c[self.auth_source]
if self.x509_extra_user:
auth_dict = {
'name': DEFAULT_SUBJECT, 'mechanism': 'MONGODB-X509'}
else:
auth_dict = {'name': self.login, 'password': self.password}
try:
db.authenticate(**auth_dict)
except:
logger.exception("Could not authenticate to %s with %r"
% (self.hostname, auth_dict))
raise
return c |
python | def getconfig(self, section=None):
"""
This method provides a way for decorated functions to get the
four new configuration parameters *after* it has been called.
If no section is specified, then the fully resolved zdesk
config will be returned. That is defaults, zdesk ini section,
command line options.
If a section is specified, then the same rules apply, but also
any missing items are filled in by the zdesk section. So the
resolution is defaults, zdesk ini section, specified section,
command line options.
"""
if not section:
return self.__config.copy()
cmd_line = {}
for k in self.__config:
v = self.wrapped.plac_cfg.get(k, 'PLAC__NOT_FOUND')
if v != self.__config[k]:
# This config item is different when fully resolved
# compared to the ini value. It was specified on the
# command line.
cmd_line[k] = self.__config[k]
# Get the email, password, url, and token config from the indicated
# section, falling back to the zdesk config for convenience
cfg = {
"zdesk_email": self.wrapped.plac_cfg.get(section + '_email',
self.__config['zdesk_email']),
"zdesk_oauth": self.wrapped.plac_cfg.get(section + '_oauth',
self.__config['zdesk_oauth']),
"zdesk_api": self.wrapped.plac_cfg.get(section + '_api',
self.__config['zdesk_api']),
"zdesk_password": self.wrapped.plac_cfg.get(section + '_password',
self.__config['zdesk_password']),
"zdesk_url": self.wrapped.plac_cfg.get(section + '_url',
self.__config['zdesk_url']),
"zdesk_token": self.wrapped.plac_cfg.get(section + '_token',
self.__config['zdesk_token']),
}
# The command line trumps all
cfg.update(cmd_line)
return cfg |
python | def create_highlight(self, artist):
"""Create a new highlight for the given artist."""
highlight = copy.copy(artist)
highlight.set(color=self.highlight_color, mec=self.highlight_color,
lw=self.highlight_width, mew=self.highlight_width)
artist.axes.add_artist(highlight)
return highlight |
java | @Deprecated
private void emitJvmMemMetrics(ServiceEmitter emitter)
{
// I have no idea why, but jvm/mem is slightly more than the sum of jvm/pool. Let's just include
// them both.
final Map<String, MemoryUsage> usages = ImmutableMap.of(
"heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(),
"nonheap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()
);
for (Map.Entry<String, MemoryUsage> entry : usages.entrySet()) {
final String kind = entry.getKey();
final MemoryUsage usage = entry.getValue();
final ServiceMetricEvent.Builder builder = builder().setDimension("memKind", kind);
MonitorUtils.addDimensionsToBuilder(builder, dimensions);
emitter.emit(builder.build("jvm/mem/max", usage.getMax()));
emitter.emit(builder.build("jvm/mem/committed", usage.getCommitted()));
emitter.emit(builder.build("jvm/mem/used", usage.getUsed()));
emitter.emit(builder.build("jvm/mem/init", usage.getInit()));
}
// jvm/pool
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
final String kind = pool.getType() == MemoryType.HEAP ? "heap" : "nonheap";
final MemoryUsage usage = pool.getUsage();
final ServiceMetricEvent.Builder builder = builder()
.setDimension("poolKind", kind)
.setDimension("poolName", pool.getName());
MonitorUtils.addDimensionsToBuilder(builder, dimensions);
emitter.emit(builder.build("jvm/pool/max", usage.getMax()));
emitter.emit(builder.build("jvm/pool/committed", usage.getCommitted()));
emitter.emit(builder.build("jvm/pool/used", usage.getUsed()));
emitter.emit(builder.build("jvm/pool/init", usage.getInit()));
}
} |
java | public OvhExchangeMailingListAlias organizationName_service_exchangeService_mailingList_mailingListAddress_alias_alias_GET(String organizationName, String exchangeService, String mailingListAddress, String alias) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailingList/{mailingListAddress}/alias/{alias}";
StringBuilder sb = path(qPath, organizationName, exchangeService, mailingListAddress, alias);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhExchangeMailingListAlias.class);
} |
java | public static boolean streamNotConsumed( HttpServletRequest request ) {
try {
ServletInputStream servletInputStream = request.getInputStream();
//in servlet >= 3.0, available will throw an exception (while previously it didn't)
return request.getContentLength() != 0 && servletInputStream.available() > 0;
} catch (IOException e) {
return false;
}
} |
java | private void defineSpinners(UIDefaults d) {
d.put("spinnerNextBorderBottomEnabled", new Color(0x4779bf));
d.put("spinnerNextBorderBottomPressed", new Color(0x4879bf));
d.put("spinnerNextInteriorBottomEnabled", new Color(0x85abcf));
d.put("spinnerNextInteriorBottomPressed", new Color(0x6e92b6));
d.put("spinnerPrevBorderTopEnabled", new Color(0x4778bf));
d.put("spinnerPrevInteriorTopEnabled", new Color(0x81aed4));
d.put("spinnerPrevInteriorBottomEnabled", new Color(0xaad4f1));
d.put("spinnerPrevInteriorPressedTop", new Color(0x6c91b8));
d.put("spinnerPrevInteriorPressedBottom", new Color(0x9cc3de));
d.put("spinnerPrevTopLineEnabled", new Color(0xacc8e0));
d.put("spinnerPrevTopLinePressed", new Color(0x9eb6cf));
d.put("Spinner.contentMargins", new InsetsUIResource(4, 6, 4, 6));
d.put("Spinner:\"Spinner.editor\".contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put("Spinner:\"Spinner.textField\".contentMargins", new InsetsUIResource(4, 6, 4, 0));
d.put("Spinner:\"Spinner.formattedTextField\".contentMargins", new InsetsUIResource(4, 6, 4, 2));
String c = PAINTER_PREFIX + "SpinnerFormattedTextFieldPainter";
String p = "Spinner:Panel:\"Spinner.formattedTextField\"";
d.put(p + ".contentMargins", new InsetsUIResource(3, 10, 3, 2));
d.put(p + ".background", Color.WHITE);
d.put(p + "[Selected].textForeground", Color.WHITE);
d.put(p + "[Selected].textBackground", d.get("seaGlassSelection"));
d.put(p + "[Disabled].textForeground", getDerivedColor("seaGlassDisabledText", 0.0f, 0.0f, 0.0f, 0, true));
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, SpinnerFormattedTextFieldPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, SpinnerFormattedTextFieldPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Focused].backgroundPainter", new LazyPainter(c, SpinnerFormattedTextFieldPainter.Which.BACKGROUND_FOCUSED));
d.put(p + "[Selected].backgroundPainter", new LazyPainter(c, SpinnerFormattedTextFieldPainter.Which.BACKGROUND_SELECTED));
d.put(p + "[Focused+Selected].backgroundPainter", new LazyPainter(c, SpinnerFormattedTextFieldPainter.Which.BACKGROUND_SELECTED_FOCUSED));
c = PAINTER_PREFIX + "SpinnerPreviousButtonPainter";
p = "Spinner:\"Spinner.previousButton\"";
d.put(p + ".size", new Integer(22));
d.put(p + ".States", "Disabled,Enabled,Focused,Pressed");
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Focused].backgroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.BACKGROUND_FOCUSED));
d.put(p + "[Focused+Pressed].backgroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.BACKGROUND_PRESSED_FOCUSED));
d.put(p + "[Pressed].backgroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.BACKGROUND_PRESSED));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Focused].foregroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.FOREGROUND_FOCUSED));
d.put(p + "[Focused+Pressed].foregroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.FOREGROUND_PRESSED_FOCUSED));
d.put(p + "[Pressed].foregroundPainter", new LazyPainter(c, SpinnerPreviousButtonPainter.Which.FOREGROUND_PRESSED));
c = PAINTER_PREFIX + "SpinnerNextButtonPainter";
p = "Spinner:\"Spinner.nextButton\"";
d.put(p + ".size", new Integer(22));
d.put(p + ".States", "Disabled,Enabled,Focused,Pressed");
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Focused].backgroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.BACKGROUND_FOCUSED));
d.put(p + "[Focused+Pressed].backgroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.BACKGROUND_PRESSED_FOCUSED));
d.put(p + "[Pressed].backgroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.BACKGROUND_PRESSED));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Focused].foregroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.FOREGROUND_FOCUSED));
d.put(p + "[Focused+Pressed].foregroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.FOREGROUND_PRESSED_FOCUSED));
d.put(p + "[Pressed].foregroundPainter", new LazyPainter(c, SpinnerNextButtonPainter.Which.FOREGROUND_PRESSED));
} |
java | public static <T> String makeS3CanonicalString(String method,
String resource, SignableRequest<T> request, String expires) {
return makeS3CanonicalString(method, resource, request, expires, null);
} |
python | def ok(self):
"""
Returns True if OK to use, else False
"""
try:
v = float(self._value)
if v < self.fmin or v > self.fmax:
return False
else:
return True
except:
return False |
java | @Override
public IGroupMember getGroupMember(String key, Class type) throws GroupsException {
IGroupMember gm = null;
if (type == ICompositeGroupService.GROUP_ENTITY_TYPE) gm = findGroup(key);
else gm = getEntity(key, type);
return gm;
} |
java | public static base_response delete(nitro_service client, Long clid) throws Exception {
clusterinstance deleteresource = new clusterinstance();
deleteresource.clid = clid;
return deleteresource.delete_resource(client);
} |
python | def features(self):
"""
Returns a collection of features available to the current account.
"""
self._validate_loaded()
resource = self.FEATURES.format(id=self.id)
response = Request(self.client, 'get', resource).perform()
return response.body['data'] |
python | def worker_pids(cls):
"""Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers."""
cmd = "ps -A -o pid,command | grep pyres_worker | grep -v grep"
output = commands.getoutput(cmd)
if output:
return map(lambda l: l.strip().split(' ')[0], output.split("\n"))
else:
return [] |
java | protected void merge(List<? extends ConfigElement> elements) {
if (elements.size() > 1) {
Collections.sort(elements, ConfigElementComparator.INSTANCE);
}
ConfigElement[] elementArray = elements.toArray(new ConfigElement[elements.size()]);
LinkedList<ConfigElement> flattened = new LinkedList<ConfigElement>();
flattened.add(elementArray[elements.size() - 1]);
for (int i = (elements.size() - 1); i > 0; i--) {
ConfigElement element = new SimpleElement(elementArray[i - 1]);
ConfigElement previous = flattened.getLast();
if (element.getDocumentLocation().equals(previous.getDocumentLocation())) {
// Same document, just merge
element.override(previous);
flattened.removeLast();
flattened.add(element);
} else if (previous.getParentDocumentLocation() != null && previous.getParentDocumentLocation().equals(element.getDocumentLocation())) {
// 'element' is in the immediate parent document of 'previous'. Just override using the merge behavior that's already specified
// on 'previous'
element.override(previous);
flattened.removeLast();
flattened.add(element);
} else if (previous.docLocationStack.contains(element.getDocumentLocation())) {
// If 'element' is in the hierarchy that included 'previous', 'previous' needs to use the merge behavior specified
// in the include statement in the document that contains 'element'.
int idx = previous.docLocationStack.indexOf(element.getDocumentLocation());
previous.mergeBehavior = previous.behaviorStack.get(idx + 1);
element.override(previous);
flattened.removeLast();
flattened.add(element);
} else {
// Conflicting element not in stack, add for later merging
flattened.add(element);
}
}
for (int i = flattened.size(); i > 0; i--) {
override(flattened.get(i - 1));
}
} |
java | void endCompoundEdit()
{
if(!compoundMode) {
throw new RuntimeException("not in compound mode");
}
ce.end();
undoManager.addEdit(ce);
ce = null;
compoundMode = false;
} |
python | def load():
"""Load the active experiment."""
initialize_experiment_package(os.getcwd())
try:
try:
from dallinger_experiment import experiment
except ImportError:
from dallinger_experiment import dallinger_experiment as experiment
classes = inspect.getmembers(experiment, inspect.isclass)
for name, c in classes:
if "Experiment" in c.__bases__[0].__name__:
return c
else:
raise ImportError
except ImportError:
logger.error("Could not import experiment.")
raise |
python | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app)
app.extensions['inspire-crawler'] = self
app.cli.add_command(crawler_cmd) |
python | def get(self, x, y):
"""Get the state of a pixel. Returns bool.
:param x: x coordinate of the pixel
:param y: y coordinate of the pixel
"""
x = normalize(x)
y = normalize(y)
dot_index = pixel_map[y % 4][x % 2]
col, row = get_pos(x, y)
char = self.chars.get(row, {}).get(col)
if not char:
return False
if type(char) != int:
return True
return bool(char & dot_index) |
python | def terms(self):
"""Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression`
"""
from qnet.algebra.core.scalar_algebra import ScalarValue
for mapping in yield_from_ranges(self.ranges):
term = self.term.substitute(mapping)
if isinstance(term, ScalarValue._val_types):
term = ScalarValue.create(term)
assert isinstance(term, Expression)
yield term |
java | @Override
public FilterSupportStatus isFilterSupported(
FilterAdapterContext context,
ColumnRangeFilter filter) {
// We require a single column family to be specified:
int familyCount = context.getScan().numFamilies();
if (familyCount != 1) {
return UNSUPPORTED_STATUS;
}
return FilterSupportStatus.SUPPORTED;
} |
java | public static Constraint moreControllerThanParticipant()
{
return new ConstraintAdapter(1)
{
PathAccessor partConv = new PathAccessor("PhysicalEntity/participantOf:Conversion");
PathAccessor partCompAss = new PathAccessor("PhysicalEntity/participantOf:ComplexAssembly");
PathAccessor effects = new PathAccessor("PhysicalEntity/controllerOf/controlled*:Conversion");
@Override
public boolean satisfies(Match match, int... ind)
{
PhysicalEntity pe = (PhysicalEntity) match.get(ind[0]);
int partCnvCnt = partConv.getValueFromBean(pe).size();
int partCACnt = partCompAss.getValueFromBean(pe).size();
int effCnt = effects.getValueFromBean(pe).size();
return (partCnvCnt - partCACnt) <= effCnt;
}
};
} |
python | def cli(env, identifier, domain, userfile, tag, hostname, userdata,
public_speed, private_speed):
"""Edit a virtual server's details."""
if userdata and userfile:
raise exceptions.ArgumentError(
'[-u | --userdata] not allowed with [-F | --userfile]')
data = {}
if userdata:
data['userdata'] = userdata
elif userfile:
with open(userfile, 'r') as userfile_obj:
data['userdata'] = userfile_obj.read()
data['hostname'] = hostname
data['domain'] = domain
if tag:
data['tags'] = ','.join(tag)
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not vsi.edit(vs_id, **data):
raise exceptions.CLIAbort("Failed to update virtual server")
if public_speed is not None:
vsi.change_port_speed(vs_id, True, int(public_speed))
if private_speed is not None:
vsi.change_port_speed(vs_id, False, int(private_speed)) |
python | def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False):
"""
Given a QuerySet, return just the serialized representation
based on the knockout_fields as JavaScript.
"""
try:
try:
# Get an inital instance of the QS.
queryset_instance = queryset[0]
except TypeError as e:
# We are being passed an object rather than a QuerySet.
# That's naughty, but we'll survive.
queryset_instance = queryset
queryset = [queryset]
except IndexError as e:
if not isinstance(queryset, list):
# This is an empty QS - get the model directly.
queryset_instance = queryset.model
else:
# We have been given an empty list.
# Return nothing.
return '[]'
modelName = queryset_instance.__class__.__name__
modelNameData = []
if field_names is not None:
fields = field_names
else:
fields = get_fields(queryset_instance)
for obj in queryset:
object_data = get_object_data(obj, fields, safe)
modelNameData.append(object_data)
if name:
modelNameString = name
else:
modelNameString = modelName + "Data"
dthandler = lambda obj: obj.isoformat() if isinstance(obj, (datetime.date, datetime.datetime)) else None
dumped_json = json.dumps(modelNameData, default=dthandler)
if return_json:
return dumped_json
return "var " + modelNameString + " = " + dumped_json + ';'
except Exception as e:
logger.exception(e)
return '[]' |
java | @Reference(policy = ReferencePolicy.DYNAMIC, target = "(id=unbound)")
protected void setConcurrencyPolicy(ConcurrencyPolicy svc) {
policyExecutor = svc.getExecutor();
} |
java | @Override
@ManagedOperation(description = "Resets statistics gathered by this component", displayName = "Reset statistics")
public void resetStatistics() {
replicationCount.set(0);
replicationFailures.set(0);
totalReplicationTime.set(0);
syncXSiteReplicationTime = new DefaultSimpleStat();
asyncXSiteCounter.reset();
} |
python | def exportProfile(self, filename=''):
"""
Exports the current profile to a file.
:param filename | <str>
"""
if not (filename and isinstance(filename, basestring)):
filename = QtGui.QFileDialog.getSaveFileName(self,
'Export Layout as...',
QtCore.QDir.currentPath(),
'XView (*.xview)')
if type(filename) == tuple:
filename = filename[0]
filename = nativestring(filename)
if not filename:
return
if not filename.endswith('.xview'):
filename += '.xview'
profile = self.saveProfile()
profile.save(filename) |
python | def addSignal(self, s):
"""
Adds a L{Signal} to the interface
"""
if s.nargs == -1:
s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)])
self.signals[s.name] = s
self._xml = None |
python | def send_sms_with_callback_token(user, mobile_token, **kwargs):
"""
Sends a SMS to user.mobile via Twilio.
Passes silently without sending in test environment.
"""
base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE)
try:
if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER:
# We need a sending number to send properly
if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True:
# we assume success to prevent spamming SMS during testing.
return True
from twilio.rest import Client
twilio_client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN'])
twilio_client.messages.create(
body=base_string % mobile_token.key,
to=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME),
from_=api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER
)
return True
else:
logger.debug("Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER.")
return False
except ImportError:
logger.debug("Couldn't import Twilio client. Is twilio installed?")
return False
except KeyError:
logger.debug("Couldn't send SMS."
"Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?")
except Exception as e:
logger.debug("Failed to send token SMS to user: {}. "
"Possibly no mobile number on user object or the twilio package isn't set up yet. "
"Number entered was {}".format(user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME)))
logger.debug(e)
return False |
java | public static String getType (String command)
{
int cidx = StringUtil.isBlank(command) ? -1 : command.indexOf(':');
return (cidx == -1) ? "" : command.substring(0, cidx);
} |
java | public ListAWSServiceAccessForOrganizationResult withEnabledServicePrincipals(EnabledServicePrincipal... enabledServicePrincipals) {
if (this.enabledServicePrincipals == null) {
setEnabledServicePrincipals(new java.util.ArrayList<EnabledServicePrincipal>(enabledServicePrincipals.length));
}
for (EnabledServicePrincipal ele : enabledServicePrincipals) {
this.enabledServicePrincipals.add(ele);
}
return this;
} |
python | def send_KeyEvent(self, key, down):
"""For most ordinary keys, the "keysym" is the same as the
corresponding ASCII value. Other common keys are shown in the
KEY_ constants.
"""
self.sendMessage(struct.pack('!BBxxI', 4, down, key)) |
python | def disconnect_async(self, conn_id, callback):
"""Asynchronously disconnect from a device."""
future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id))
future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback)) |
java | private static void addSuperAndInterfaces(Set<Class<?>> classes, Class<?> clazz) {
if (clazz != null) {
classes.add(clazz);
addSuperAndInterfaces(classes, clazz.getSuperclass());
for (Class<?> aClass : clazz.getInterfaces()) {
addSuperAndInterfaces(classes, aClass);
}
}
} |
java | private boolean canRun(String flowName, String flowGroup, boolean allowConcurrentExecution) {
if (allowConcurrentExecution) {
return true;
} else {
return !flowStatusGenerator.isFlowRunning(flowName, flowGroup);
}
} |
java | private static <T> T extractSingleton(Collection<T> collection) {
if (collection == null || collection.isEmpty()) {
return null;
}
if (collection.size() == 1) {
return collection.iterator().next();
} else {
throw new IllegalStateException("Expected singleton collection, but found size: " + collection.size());
}
} |
java | public boolean isValidSecretToken(String secretToken) {
return (this.secretToken == null || this.secretToken.equals(secretToken) ? true : false);
} |
java | public static boolean writeString(String filePath, String content, boolean append) throws IOException {
return writeString(filePath != null ? new File(filePath) : null, content, append);
} |
python | def exportCertificate(self, certificate, folder):
"""gets the SSL Certificates for a given machine"""
url = self._url + "/sslcertificates/%s/export" % certificate
params = {
"f" : "json",
}
return self._get(url=url,
param_dict=params,
out_folder=folder) |
python | def fastcc_consistent_subset(model, epsilon, solver):
"""Return consistent subset of model.
The largest consistent subset is returned as
a set of reaction names.
Args:
model: :class:`MetabolicModel` to solve.
epsilon: Flux threshold value.
solver: LP solver instance to use.
Returns:
Set of reaction IDs in the consistent reaction subset.
"""
reaction_set = set(model.reactions)
return reaction_set.difference(fastcc(model, epsilon, solver)) |
python | def _get_projection(cls, obj):
"""
Uses traversal to find the appropriate projection
for a nested object. Respects projections set on
Overlays before considering Element based settings,
before finally looking up the default projection on
the plot type. If more than one non-None projection
type is found an exception is raised.
"""
isoverlay = lambda x: isinstance(x, CompositeOverlay)
element3d = obj.traverse(lambda x: x, [Element3D])
if element3d:
return '3d'
opts = cls._traverse_options(obj, 'plot', ['projection'],
[CompositeOverlay, Element],
keyfn=isoverlay)
from_overlay = not all(p is None for p in opts[True]['projection'])
projections = opts[from_overlay]['projection']
custom_projs = [p for p in projections if p is not None]
if len(set(custom_projs)) > 1:
raise Exception("An axis may only be assigned one projection type")
return custom_projs[0] if custom_projs else None |
java | public static List<MetricDto> transformToDto(List<Metric> metrics) {
if (metrics == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
List<MetricDto> result = new ArrayList<>();
for (Metric metric : metrics) {
result.add(transformToDto(metric));
}
return result;
} |
java | public StreamAttribute attribute(String streamKey) throws QiniuException {
String path = encodeKey(streamKey);
return get(path, StreamAttribute.class);
} |
java | boolean skipObject()
throws IOException
{
int ch = read();
int len;
switch (ch) {
// inline string (1 byte)
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
skip(ch - 0x00);
return true;
// inline binary (1 byte)
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
skip(ch - 0x20);
return true;
// string (1 byte)
case 0x30: case 0x31: case 0x32: case 0x33:
len = 256 * (ch - 0x30) + read();
skip(len);
return true;
// binary (1 byte)
case 0x34: case 0x35: case 0x36: case 0x37:
len = 256 * (ch - 0x34) + read();
skip(len);
return true;
// 0x38-0x3b are reserved
// long three-byte
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
skip(2);
return true;
// 0x40 is reserved
// binary non-tail chunk
case 0x41:
len = readShort();
skip(len);
return skipObject();
// binary tail chunk
case 0x42:
len = readShort();
skip(len);
return true;
// class def
case 0x43:
scanObjectDef();
return skipObject();
// 64-bit double
case 0x44:
skip(8);
return true;
// error marker
case 0x45:
throw new IllegalStateException("Invalid Hessian bytecode 'E'");
// false
case 0x46:
return true;
// ext type (fixed int)
case 0x47:
skipObject();
skipObject();
return true;
case 0x48: { // untyped map 'H'
skipMap();
return true;
}
// 32-bit int
case 0x49:
skip(4);
return true;
// 64-bit date
case 0x4a:
skip(8);
return true;
// 32-bit date
case 0x4b:
skip(4);
return true;
// 64-bit long
case 0x4c:
skip(8);
return true;
case 0x4d: { // typed map 'M'
skipObject();
skipMap();
return true;
}
// null
case 0x4e:
return true;
case 0x4f: // object instance
{
int type = scanInt();
String []def = _classDefs.get(type);
len = def.length - 1;
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
}
// ext type (named)
case 0x50:
skipObject();
skipObject();
return true;
// backref
case 0x51:
skipObject();
return true;
// string non-tail chunk
case 0x52:
len = readShort();
skip(len);
return skipObject();
// string tail chunk
case 0x53:
len = readShort();
skip(len);
return true;
// true
case 0x54:
return true;
// typed variable list
case 0x55:
readType();
while (skipObject()) {
}
return true;
// typed fixed list
case 0x56:
readType();
len = scanInt();
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
// untyped variable list
case 0x57:
while (skipObject()) {
}
return true;
// untyped fixed list
case 0x58:
len = scanInt();
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
// 32-bit long
case 0x59:
skip(4);
return true;
case 0x5a: // 'Z' end
return false;
// 0.0, 1.0
case 0x5b: case 0x5c:
return true;
// (double) b0
case 0x5d:
skip(1);
return true;
// (double) b1 b0
case 0x5e:
skip(2);
return true;
// (double) int
case 0x5f:
return skipObject();
// object instance
case 0x60: case 0x61: case 0x62: case 0x63:
case 0x64: case 0x65: case 0x66: case 0x67:
case 0x68: case 0x69: case 0x6a: case 0x6b:
case 0x6c: case 0x6d: case 0x6e: case 0x6f:
{
int type = ch - 0x60;
String []def = _classDefs.get(type);
len = def.length - 1;
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
}
// direct fixed typed list
case 0x70: case 0x71: case 0x72: case 0x73:
case 0x74: case 0x75: case 0x76: case 0x77:
skipObject();
len = ch - 0x70;
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
// direct fixed untyped list
case 0x78: case 0x79: case 0x7a: case 0x7b:
case 0x7c: case 0x7d: case 0x7e: case 0x7f:
len = ch - 0x78;
for (int i = 0; i < len; i++) {
skipObject();
}
return true;
// int single-byte
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return true;
// int two-byte
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
skip(1);
return true;
// int three-byte
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
skip(2);
return true;
// long single-byte
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return true;
// long two-byte
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
skip(1);
return true;
default:
throw new UnsupportedOperationException("0x" + Integer.toHexString(ch));
}
} |
python | def page(self, recurring=values.unset, trigger_by=values.unset,
usage_category=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of TriggerInstance records from the API.
Request is executed immediately
:param TriggerInstance.Recurring recurring: The frequency of recurring UsageTriggers to read
:param TriggerInstance.TriggerField trigger_by: The trigger field of the UsageTriggers to read
:param TriggerInstance.UsageCategory usage_category: The usage category of the UsageTriggers to read
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of TriggerInstance
:rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerPage
"""
params = values.of({
'Recurring': recurring,
'TriggerBy': trigger_by,
'UsageCategory': usage_category,
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(
'GET',
self._uri,
params=params,
)
return TriggerPage(self._version, response, self._solution) |
python | def set(self, results):
"""Set results.
results is an iterable of tuples, where each tuple is a row of results.
>>> x = Results(['title'])
>>> x.set([('Konosuba',), ('Oreimo',)])
>>> x
Results(['title'], [('Konosuba',), ('Oreimo',)])
"""
self.results = list()
for row in results:
self.append(row) |
python | def _initialize_progress_bar(self):
"""Initializes the progress bar"""
widgets = ['Download: ', Percentage(), ' ', Bar(),
' ', AdaptiveETA(), ' ', FileTransferSpeed()]
self._downloadProgressBar = ProgressBar(
widgets=widgets, max_value=self._imageCount).start() |
python | def present_active(self):
"""
Strong verbs
I
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"])
>>> verb.present_active()
['lít', 'lítr', 'lítr', 'lítum', 'lítið', 'líta']
II
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["bjóða", "býðr", "bauð", "buðu", "boðinn"])
>>> verb.present_active()
['býð', 'býðr', 'býðr', 'bjóðum', 'bjóðið', 'bjóða']
III
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["verða", "verðr", "varð", "urðu", "orðinn"])
>>> verb.present_active()
['verð', 'verðr', 'verðr', 'verðum', 'verðið', 'verða']
IV
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["bera", "berr", "bar", "báru", "borinn"])
>>> verb.present_active()
['ber', 'berr', 'berr', 'berum', 'berið', 'bera']
V
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["gefa", "gefr", "gaf", "gáfu", "gefinn"])
>>> verb.present_active()
['gef', 'gefr', 'gefr', 'gefum', 'gefið', 'gefa']
VI
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["fara", "ferr", "fór", "fóru", "farinn"])
>>> verb.present_active()
['fer', 'ferr', 'ferr', 'förum', 'farið', 'fara']
VII
>>> verb = StrongOldNorseVerb()
>>> verb.set_canonic_forms(["ráða", "ræðr", "réð", "réðu", "ráðinn"])
>>> verb.present_active()
['ræð', 'ræðr', 'ræðr', 'ráðum', 'ráðið', 'ráða']
:return:
"""
forms = []
singular_stem = self.sfg3en[:-1]
forms.append(singular_stem)
forms.append(self.sfg3en)
forms.append(self.sfg3en)
plural_stem = self.sng[:-1] if self.sng[-1] == "a" else self.sng
forms.append(apply_u_umlaut(plural_stem)+"um")
forms.append(plural_stem+"ið")
forms.append(self.sng)
return forms |
java | @Override
@Nullable
public String getMapping(Class<?> type, Method method) {
Assert.notNull(type, "Type must not be null!");
Assert.notNull(method, "Method must not be null!");
String[] mapping = getMappingFrom(findMergedAnnotation(method, annotationType));
String typeMapping = getMapping(type);
if (mapping.length == 0) {
return typeMapping;
}
return typeMapping == null || "/".equals(typeMapping) ? mapping[0] : join(typeMapping, mapping[0]);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.