language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def sun_rise_set_transit_ephem(times, latitude, longitude,
next_or_previous='next',
altitude=0,
pressure=101325,
temperature=12, horizon='0:00'):
"""
Calculate the next sunrise and sunset times using the PyEphem package.
Parameters
----------
time : pandas.DatetimeIndex
Must be localized
latitude : float
Latitude in degrees, positive north of equator, negative to south
longitude : float
Longitude in degrees, positive east of prime meridian, negative to west
next_or_previous : str
'next' or 'previous' sunrise and sunset relative to time
altitude : float, default 0
distance above sea level in meters.
pressure : int or float, optional, default 101325
air pressure in Pascals.
temperature : int or float, optional, default 12
air temperature in degrees C.
horizon : string, format +/-X:YY
arc degrees:arc minutes from geometrical horizon for sunrise and
sunset, e.g., horizon='+0:00' to use sun center crossing the
geometrical horizon to define sunrise and sunset,
horizon='-0:34' for when the sun's upper edge crosses the
geometrical horizon
Returns
-------
pandas.DataFrame
index is the same as input `time` argument
columns are 'sunrise', 'sunset', and 'transit'
See also
--------
pyephem
"""
try:
import ephem
except ImportError:
raise ImportError('PyEphem must be installed')
# times must be localized
if times.tz:
tzinfo = times.tz
else:
raise ValueError('times must be localized')
obs, sun = _ephem_setup(latitude, longitude, altitude,
pressure, temperature, horizon)
# create lists of sunrise and sunset time localized to time.tz
if next_or_previous.lower() == 'next':
rising = obs.next_rising
setting = obs.next_setting
transit = obs.next_transit
elif next_or_previous.lower() == 'previous':
rising = obs.previous_rising
setting = obs.previous_setting
transit = obs.previous_transit
else:
raise ValueError("next_or_previous must be either 'next' or" +
" 'previous'")
sunrise = []
sunset = []
trans = []
for thetime in times:
thetime = thetime.to_pydatetime()
# pyephem drops timezone when converting to its internal datetime
# format, so handle timezone explicitly here
obs.date = ephem.Date(thetime - thetime.utcoffset())
sunrise.append(_ephem_to_timezone(rising(sun), tzinfo))
sunset.append(_ephem_to_timezone(setting(sun), tzinfo))
trans.append(_ephem_to_timezone(transit(sun), tzinfo))
return pd.DataFrame(index=times, data={'sunrise': sunrise,
'sunset': sunset,
'transit': trans}) |
python | def libc(cls):
"""
Alpine linux uses a non glibc version of the standard library, it uses
the stripped down musl instead. The core agent can be built against it,
but which one is running must be detected. Shelling out to `ldd`
appears to be the most reliable way to do this.
"""
try:
output = subprocess.check_output(
["ldd", "--version"], stderr=subprocess.STDOUT
)
except (OSError, subprocess.CalledProcessError):
return "gnu"
else:
if b"musl" in output:
return "musl"
else:
return "gnu" |
java | @Override
public void sessionCreated(NextFilter nextFilter, IoSession session)
throws Exception {
if (profileSessionCreated) {
long start = timeNow();
nextFilter.sessionCreated(session);
long end = timeNow();
sessionCreatedTimerWorker.addNewDuration(end - start);
} else {
nextFilter.sessionCreated(session);
}
} |
python | def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal:
"""
Returns aggregate sum of queryset 'amount' field.
:param qs: QuerySet
:param key: Field to sum (default: 'amount')
:param default: Default value if no results
:return: Sum of 'amount' field values (coalesced 0 if None)
"""
res = qs.aggregate(b=Sum(key))['b']
return default if res is None else res |
java | protected void initDataSource() {
if (dataSource == null) {
if (dataSourceJndiName != null) {
try {
dataSource = (DataSource) new InitialContext().lookup(dataSourceJndiName);
} catch (Exception e) {
throw new ProcessEngineException("couldn't lookup datasource from " + dataSourceJndiName + ": " + e.getMessage(), e);
}
} else if (jdbcUrl != null) {
if ((jdbcDriver == null) || (jdbcUrl == null) || (jdbcUsername == null)) {
throw new ProcessEngineException("DataSource or JDBC properties have to be specified in a process engine configuration");
}
PooledDataSource pooledDataSource =
new PooledDataSource(ReflectUtil.getClassLoader(), jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword);
if (jdbcMaxActiveConnections > 0) {
pooledDataSource.setPoolMaximumActiveConnections(jdbcMaxActiveConnections);
}
if (jdbcMaxIdleConnections > 0) {
pooledDataSource.setPoolMaximumIdleConnections(jdbcMaxIdleConnections);
}
if (jdbcMaxCheckoutTime > 0) {
pooledDataSource.setPoolMaximumCheckoutTime(jdbcMaxCheckoutTime);
}
if (jdbcMaxWaitTime > 0) {
pooledDataSource.setPoolTimeToWait(jdbcMaxWaitTime);
}
if (jdbcPingEnabled == true) {
pooledDataSource.setPoolPingEnabled(true);
if (jdbcPingQuery != null) {
pooledDataSource.setPoolPingQuery(jdbcPingQuery);
}
pooledDataSource.setPoolPingConnectionsNotUsedFor(jdbcPingConnectionNotUsedFor);
}
dataSource = pooledDataSource;
}
if (dataSource instanceof PooledDataSource) {
// ACT-233: connection pool of Ibatis is not properely initialized if this is not called!
((PooledDataSource) dataSource).forceCloseAll();
}
}
if (databaseType == null) {
initDatabaseType();
}
} |
python | def toProtocolElement(self):
"""
Returns the GA4GH protocol representation of this ReadGroupSet.
"""
readGroupSet = protocol.ReadGroupSet()
readGroupSet.id = self.getId()
readGroupSet.read_groups.extend(
[readGroup.toProtocolElement()
for readGroup in self.getReadGroups()]
)
readGroupSet.name = self.getLocalId()
readGroupSet.dataset_id = self.getParentContainer().getId()
readGroupSet.stats.CopyFrom(self.getStats())
self.serializeAttributes(readGroupSet)
return readGroupSet |
java | public void removeIgnoreCase(String key) {
int i = indexOfKeyIgnoreCase(key);
if (i != NotFound)
remove(i);
} |
python | def request_booking_details(self, poll_url, **params):
"""
Request for booking details
URL Format:
{API_HOST}/apiservices/pricing/v1.0/{session key}/booking
?apiKey={apiKey}
"""
return self.make_request("%s/booking" % poll_url,
method='put',
headers=self._headers(),
callback=lambda resp: resp.headers[
'location'],
**params) |
python | def confd_state_loaded_data_models_data_model_namespace(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
loaded_data_models = ET.SubElement(confd_state, "loaded-data-models")
data_model = ET.SubElement(loaded_data_models, "data-model")
name_key = ET.SubElement(data_model, "name")
name_key.text = kwargs.pop('name')
namespace = ET.SubElement(data_model, "namespace")
namespace.text = kwargs.pop('namespace')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
java | public static List<String> loadOptions(String optionFileName) {
List<String> args = new ArrayList<String>();
File optionFile = new File(optionFileName);
StringWriter stringWriter = new StringWriter();
try {
InputStream inputStream = new FileInputStream(optionFile);
IOUtils.copy(inputStream, stringWriter);
} catch (FileNotFoundException e) {
System.err.println("Error reading options file: " + e.getMessage());
System.exit(1);
} catch (IOException e) {
System.err.println("Error reading options file: " + e.getMessage());
System.exit(1);
}
String string = stringWriter.toString();
StringTokenizer stringTokenizer = new StringTokenizer(string);
while (stringTokenizer.hasMoreTokens()) {
args.add(stringTokenizer.nextToken());
}
return args;
} |
java | private void appendAffix(StringBuffer buffer, String affixPattern,
String expAffix, boolean localized) {
if (affixPattern == null) {
appendAffix(buffer, expAffix, localized);
} else {
int i;
for (int pos=0; pos<affixPattern.length(); pos=i) {
i = affixPattern.indexOf(QUOTE, pos);
if (i < 0) {
appendAffix(buffer, affixPattern.substring(pos), localized);
break;
}
if (i > pos) {
appendAffix(buffer, affixPattern.substring(pos, i), localized);
}
char c = affixPattern.charAt(++i);
++i;
if (c == QUOTE) {
buffer.append(c);
// Fall through and append another QUOTE below
} else if (c == CURRENCY_SIGN &&
i<affixPattern.length() &&
affixPattern.charAt(i) == CURRENCY_SIGN) {
++i;
buffer.append(c);
// Fall through and append another CURRENCY_SIGN below
} else if (localized) {
switch (c) {
case PATTERN_PERCENT:
c = symbols.getPercent();
break;
case PATTERN_PER_MILLE:
c = symbols.getPerMill();
break;
case PATTERN_MINUS:
c = symbols.getMinusSign();
break;
}
}
buffer.append(c);
}
}
} |
python | def _cookie_parse_impl(b):
"""Lowlevel cookie parsing facility that operates on bytes."""
i = 0
n = len(b)
while i < n:
match = _cookie_re.search(b + b";", i)
if not match:
break
key = match.group("key").strip()
value = match.group("val") or b""
i = match.end(0)
yield _cookie_unquote(key), _cookie_unquote(value) |
java | public void setHealthCheckRegistry(Object healthCheckRegistry)
{
checkIfSealed();
if (healthCheckRegistry != null) {
healthCheckRegistry = getObjectOrPerformJndiLookup(healthCheckRegistry);
if (!(healthCheckRegistry instanceof HealthCheckRegistry)) {
throw new IllegalArgumentException("Class must be an instance of com.codahale.metrics.health.HealthCheckRegistry");
}
}
this.healthCheckRegistry = healthCheckRegistry;
} |
java | public static boolean hasForUpdate(Object parameter) {
if (parameter != null && parameter instanceof Example) {
Example example = (Example) parameter;
return example.isForUpdate();
}
return false;
} |
java | public void greet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
SpanBuilder spanBuilder =
tracer.spanBuilder("client").setRecordEvents(true).setSampler(Samplers.alwaysSample());
try (Scope scope = spanBuilder.startScopedSpan()) {
tracer.getCurrentSpan().addAnnotation("Saying Hello to Server.");
response = blockingStub.sayHello(request);
tracer.getCurrentSpan().addAnnotation("Received response from Server.");
} catch (StatusRuntimeException e) {
tracer
.getCurrentSpan()
.setStatus(
CanonicalCode.valueOf(e.getStatus().getCode().name())
.toStatus()
.withDescription(e.getMessage()));
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
} |
java | protected void handleListCache() {
reportable.output("Listing resources in the cache");
List<CachedResource> resources = cacheLookupService.getResources();
if (resources.isEmpty()) {
reportable.output("No resources in the cache.");
}
for (CachedResource resource : resources) {
reportable.output("\t" + resource.getType().getResourceFolderName()
+ "\t" + resource.getRemoteLocation());
}
} |
java | public PaymillList<Client> list( Integer count, Integer offset ) {
return this.list( null, null, count, offset );
} |
python | def _set_up_inheritance_and_subclass_sets(self, schema_data):
"""Load all inheritance data from the OrientDB schema. Used as part of __init__."""
# For each class name, construct its inheritance set:
# itself + the set of class names from which it inherits.
for class_definition in schema_data:
class_name = class_definition['name']
immediate_superclass_names = get_superclasses_from_class_definition(
class_definition)
inheritance_set = set(immediate_superclass_names)
inheritance_set.add(class_name)
# Since the input data must be in topological order, the superclasses of
# the current class should have already been processed.
# A KeyError on the following line would mean that the input
# was not topologically sorted.
inheritance_set.update(chain.from_iterable(
self._inheritance_sets[superclass_name]
for superclass_name in immediate_superclass_names
))
# Freeze the inheritance set so it can't ever be modified again.
self._inheritance_sets[class_name] = frozenset(inheritance_set)
# For each class name, construct its subclass set:
# itself + the set of class names that inherit from it.
for subclass_name, superclass_names in six.iteritems(self._inheritance_sets):
for superclass_name in superclass_names:
self._subclass_sets.setdefault(
superclass_name, set()).add(subclass_name)
# Freeze all subclass sets so they can never be modified again,
# making a list of all keys before modifying any of their values.
# It's bad practice to mutate a dict while iterating over it.
for class_name in list(six.iterkeys(self._subclass_sets)):
self._subclass_sets[class_name] = frozenset(self._subclass_sets[class_name]) |
java | void doParse(String filePath, Reader fileContents) {
this.filePath = filePath;
parseSucceeded = true;
BufferedReader lineBuffer = new BufferedReader(fileContents);
// Parse all lines.
String line = null;
lineNum = 0;
boolean inMultilineComment = false;
boolean inJsDocComment = false;
try {
while (null != (line = lineBuffer.readLine())) {
++lineNum;
try {
String revisedLine = line;
String revisedJsDocCommentLine = "";
if (inMultilineComment) {
int endOfComment = revisedLine.indexOf("*/");
if (endOfComment != -1) {
if (inJsDocComment) {
revisedJsDocCommentLine = revisedLine.substring(0, endOfComment + 2);
inJsDocComment = false;
}
revisedLine = revisedLine.substring(endOfComment + 2);
inMultilineComment = false;
} else {
if (inJsDocComment) {
revisedJsDocCommentLine = line;
}
revisedLine = "";
}
}
if (!inMultilineComment) {
while (true) {
int startOfLineComment = revisedLine.indexOf("//");
int startOfMultilineComment = revisedLine.indexOf("/*");
if (startOfLineComment != -1 &&
(startOfMultilineComment == -1 ||
startOfLineComment < startOfMultilineComment)) {
revisedLine = revisedLine.substring(0, startOfLineComment);
break;
} else if (startOfMultilineComment != -1) {
// If comment is in a string (single or double quoted), don't parse as a comment.
if (isCommentQuoted(revisedLine, startOfMultilineComment, '\'')) {
break;
}
if (isCommentQuoted(revisedLine, startOfMultilineComment, '"')) {
break;
}
if (startOfMultilineComment == revisedLine.indexOf("/**")) {
inJsDocComment = true;
}
int endOfMultilineComment = revisedLine.indexOf("*/", startOfMultilineComment + 2);
if (endOfMultilineComment == -1) {
if (inJsDocComment) {
revisedJsDocCommentLine = revisedLine.substring(startOfMultilineComment);
}
revisedLine = revisedLine.substring(0, startOfMultilineComment);
inMultilineComment = true;
break;
} else {
if (inJsDocComment) {
String jsDocComment =
revisedLine.substring(startOfMultilineComment, endOfMultilineComment + 2);
if (!parseJsDocCommentLine(jsDocComment) && shortcutMode) {
break;
}
inJsDocComment = false;
}
revisedLine =
revisedLine.substring(0, startOfMultilineComment) +
revisedLine.substring(endOfMultilineComment + 2);
}
} else {
break;
}
}
}
if (!revisedJsDocCommentLine.isEmpty()) {
if (!parseJsDocCommentLine(revisedJsDocCommentLine) && shortcutMode) {
break;
}
}
if (!revisedLine.isEmpty()) {
// This check for shortcut mode should be redundant, but
// it's done for safety reasons.
if (!parseLine(revisedLine) && shortcutMode) {
break;
}
}
} catch (ParseException e) {
// Inform the error handler of the exception.
errorManager.report(
e.isFatal() ? CheckLevel.ERROR : CheckLevel.WARNING,
JSError.make(filePath, lineNum, 0 /* char offset */,
e.isFatal() ? PARSE_ERROR : PARSE_WARNING,
e.getMessage(), line));
parseSucceeded = parseSucceeded && !e.isFatal();
}
}
} catch (IOException e) {
errorManager.report(CheckLevel.ERROR,
JSError.make(filePath, 0, 0 /* char offset */,
PARSE_ERROR, "Error reading file: " + filePath));
parseSucceeded = false;
}
} |
java | private static int getMessageCountExcludeSelf(Messenger<String> messenger, String id) {
Set<String> messageSet = newHashSet(messenger.receiveMessages());
messageSet.remove(id);
return messageSet.size();
} |
java | @Override
public Collection<String> getAppliesToMinimumVersions() {
Collection<String> versions = new HashSet<String>();
try {
List<AppliesToFilterInfo> entries = generateAppliesToFilterInfoList(false);
if (entries != null) {
for (AppliesToFilterInfo appliesToFilterInfo : entries) {
FilterVersion minVersion = appliesToFilterInfo.getMinVersion();
if (minVersion != null) {
versions.add(minVersion.toString());
}
}
}
} catch (RepositoryResourceCreationException e) {
// Impossible as we don't validate the applies to
}
return versions;
} |
python | def OnHelpMove(self, event):
"""Help window move event handler stores position in config"""
position = event.GetPosition()
config["help_window_position"] = repr((position.x, position.y))
event.Skip() |
java | public void removeDependentVariables(Variable ... depVars) {
ArrayList<Variable> newDepVars = new ArrayList<Variable>();
for (Variable v : this.dependentVariables) {
boolean toRemove = false;
for (Variable v1 : depVars) {
if (v.equals(v1)) {
toRemove = true;
break;
}
}
if (!toRemove) newDepVars.add(v);
}
this.dependentVariables = newDepVars.toArray(new Variable[newDepVars.size()]);
} |
java | protected Object getAllValues(BackedSession sess) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_ALL_VALUES]);
}
Connection conn = getConnection(false);
String id = sess.getId();
if (conn == null) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_ALL_VALUES], null);
}
return null;
}
long startTime = System.currentTimeMillis();
long readSize = 0;
PreparedStatement s = null;
ResultSet rs = null;
Hashtable h = new Hashtable();
try {
s = conn.prepareStatement(findProps);
s.setString(1, id);
s.setString(2, id);
s.setString(3, getAppName());
rs = s.executeQuery();
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "querying database for properties");
}
while (rs.next()) {
// start PM36949: If an attribute is already in appDataRemovals or appDataChanges, then the attribute was already retrieved from the db. Skip retrieval from the db here.
if (sess.appDataRemovals != null && sess.appDataRemovals.containsKey(rs.getString(DatabaseHashMap.propCol))) { //
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "Found property: "
+ rs.getString(DatabaseHashMap.propCol)
+ " in appDataRemovals, skipping db query for this prop");
}
continue;
} else if (sess.appDataChanges != null && sess.appDataChanges.containsKey(rs.getString(DatabaseHashMap.propCol))) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES], "Found property: "
+ rs.getString(DatabaseHashMap.propCol)
+ " in appDataChanges, skipping db query for this prop");
}
continue;
} // end PM36949
byte[] b = rs.getBytes(smallCol);
if (b == null) {
b = rs.getBytes(medCol);
}
if (b == null) {
b = rs.getBytes(lgCol);
}
ByteArrayInputStream bais = new ByteArrayInputStream(b);
BufferedInputStream bis = new BufferedInputStream(bais);
Object obj = null;
try {
obj = ((DatabaseStore) getIStore()).getLoader().loadObject(bis);
readSize += b.length;
} catch (ClassNotFoundException ce) {
com.ibm.ws.ffdc.FFDCFilter.processException(ce, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "864", sess);
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.getSwappableListenersErr");
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.sessionid", id);
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", ce);
}
bis.close();
bais.close();
if (obj != null) {
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[GET_ALL_VALUES],
"put prop in mSwappableData: " + rs.getString(DatabaseHashMap.propCol));
}
h.put(rs.getString(propCol), obj);
}
}
SessionStatistics pmiStats = _iStore.getSessionStatistics();
if (pmiStats != null) {
pmiStats.readTimes(readSize, System.currentTimeMillis() - startTime);
}
} catch (SQLException se) {
com.ibm.ws.ffdc.FFDCFilter.processException(se, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "885", sess);
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.checkListErr");
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.object", sess.toString());
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", se);
} catch (Exception e) {
com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMapMR.getAllValues", "892", sess);
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "DatabaseHashMapMR.checkListErr");
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.object", sess.toString());
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[GET_ALL_VALUES], "CommonMessage.exception", e);
} finally {
if (rs != null)
closeResultSet(rs);
if (s != null)
closeStatement(s);
closeConnection(conn);
}
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[GET_ALL_VALUES], h);
}
return h;
} |
python | def parse_commandline(argv):
"""
Returns the arguments parsed from *argv* as a namespace.
"""
ap = ArgumentParser(
prog='wdiffhtml',
description=DESCRIPTION,
epilog=EPILOG,
)
ap.add_argument(
'--version', action='version', version='wdiffhtml v{}'.format(version),
help="shows version and exits"
)
ap.add_argument(
'org_file', metavar='FILENAME',
help="original file"
)
ap.add_argument(
'new_file', metavar='FILENAME',
help="changed file"
)
g_html = ap.add_argument_group(
'Wrapper',
"Without these settings, only the `wdiff` output is returned (with INS "
"and DEL tags). Here are some options to wrap the output in a HTML "
"document."
)
g_html.add_argument(
'-w', '--wrap-with-html', action='store_true',
help="wrap the diff with a HTML document"
)
g_html.add_argument(
'-f', '--fold-tags', action='store_true',
help="allow INS and DEL tags to span linebraks"
)
g_html.add_argument(
'-b', '--hard-breaks', action='store_true',
help="replace line breaks with BR tags"
)
g_context = ap.add_argument_group(
'Context',
"With these options you can add additional information to the HTML "
"output (means these only work alongside the `--wrap-with-html` option)."
)
g_context.add_argument(
'-r', '--revision', metavar='STRING',
help="add a revision tag or version number to the output"
)
x_stamp = g_context.add_mutually_exclusive_group()
x_stamp.add_argument(
'-d', '--datestamp', action='store_true',
help="add a date to the output (UTC now)"
)
x_stamp.add_argument(
'-D', '--timestamp', action='store_true',
help="add date and time to the output (UTC now)"
)
g_files = ap.add_argument_group(
'Files',
"Instead of using the default templates, you can use your own files. "
"These only work alongside the `--wrap-with-html` option"
)
g_files.add_argument(
'-t', '--template', type=FileType('r'), metavar='FILE',
help="load the Jinja2 template from this file"
)
g_files.add_argument(
'-c', '--css', type=FileType('r'), metavar='FILE',
help="load CSS from this file"
)
g_files.add_argument(
'-j', '--js', type=FileType('r'), metavar='FILE',
help="load Javascript from this file"
)
g_files.add_argument(
'-J', '--js2', type=FileType('r'), metavar='FILE',
help="load another Javascript from this file (like Zepto)"
)
# parse args
args = ap.parse_args(argv)
# check for wrapper
if not args.wrap_with_html:
# check context arguments and file arguments
for group in (g_context, g_files):
args_to_check = [opt.dest for opt in group._group_actions]
if any([getattr(args, attr) for attr in args_to_check]):
msg = "the options require that `--wrap-with-html` is used"
ap.error(msg)
return args |
python | def author_impact_factor(self, year=2014, refresh=True):
"""Get author_impact_factor for the .
Parameters
----------
year : int (optional, default=2014)
The year based for which the impact factor is to be calculated.
refresh : bool (optional, default=True)
Whether to refresh the cached search file (if it exists) or not.
Returns
-------
(ncites, npapers, aif) : tuple of integers
The citations count, publication count, and author impact factor.
"""
scopus_abstracts = self.get_journal_abstracts(refresh=refresh)
cites = [int(ab.citedby_count) for ab in scopus_abstracts]
years = [int(ab.coverDate.split('-')[0]) for ab in scopus_abstracts]
data = zip(years, cites, scopus_abstracts)
data = sorted(data, key=itemgetter(1), reverse=True)
# now get aif papers for year-1 and year-2
aif_data = [tup for tup in data if tup[0] in (year - 1, year - 2)]
Ncites = sum([tup[1] for tup in aif_data])
if len(aif_data) > 0:
return (Ncites, len(aif_data), Ncites / float(len(aif_data)))
else:
return (Ncites, len(aif_data), 0) |
python | def from_transport(cls, t):
"""
Create an SFTP client channel from an open L{Transport}.
@param t: an open L{Transport} which is already authenticated
@type t: L{Transport}
@return: a new L{SFTPClient} object, referring to an sftp session
(channel) across the transport
@rtype: L{SFTPClient}
"""
chan = t.open_session()
if chan is None:
return None
chan.invoke_subsystem('sftp')
return cls(chan) |
java | public static ValueMatcher makeValueMatcherGeneric(DimensionSelector selector, @Nullable String value)
{
IdLookup idLookup = selector.idLookup();
if (idLookup != null) {
return makeDictionaryEncodedValueMatcherGeneric(selector, idLookup.lookupId(value), value == null);
} else if (selector.getValueCardinality() >= 0 && selector.nameLookupPossibleInAdvance()) {
// Employ caching BitSet optimization
return makeDictionaryEncodedValueMatcherGeneric(selector, Predicates.equalTo(value));
} else {
return makeNonDictionaryEncodedValueMatcherGeneric(selector, value);
}
} |
java | private void generateInnerAccessPaths(BranchNode parentNode) {
JoinNode innerChildNode = parentNode.getRightNode();
assert(innerChildNode != null);
// In case of inner join WHERE and JOIN expressions can be merged
if (parentNode.getJoinType() == JoinType.INNER) {
parentNode.m_joinInnerOuterList.addAll(parentNode.m_whereInnerOuterList);
parentNode.m_whereInnerOuterList.clear();
parentNode.m_joinInnerList.addAll(parentNode.m_whereInnerList);
parentNode.m_whereInnerList.clear();
}
if (innerChildNode instanceof BranchNode) {
generateOuterAccessPaths((BranchNode)innerChildNode);
generateInnerAccessPaths((BranchNode)innerChildNode);
// The inner node is a join node itself. Only naive access path is possible
innerChildNode.m_accessPaths.add(
getRelevantNaivePath(parentNode.m_joinInnerOuterList, parentNode.m_joinInnerList));
return;
}
// The inner table can have multiple index access paths based on
// inner and inner-outer join expressions plus the naive one.
List<AbstractExpression> filterExprs = null;
List<AbstractExpression> postExprs = null;
// For the FULL join type, the inner join expressions must stay at the join node and
// not go down to the inner node as filters (as predicates for SeqScan nodes and/or
// index expressions for Index Scan). The latter case (IndexScan) won't work for NLJ because
// the inner join expression will effectively filter out inner tuple prior to the NLJ.
if (parentNode.getJoinType() != JoinType.FULL) {
filterExprs = parentNode.m_joinInnerList;
}
else {
postExprs = parentNode.m_joinInnerList;
}
StmtTableScan innerTable = innerChildNode.getTableScan();
assert(innerTable != null);
innerChildNode.m_accessPaths.addAll(
getRelevantAccessPathsForTable(innerTable,
parentNode.m_joinInnerOuterList, filterExprs, postExprs));
// If there are inner expressions AND inner-outer expressions, it could be that there
// are indexed access paths that use elements of both in the indexing expressions,
// especially in the case of a compound index.
// These access paths can not be considered for use with an NLJ because they rely on
// inner-outer expressions.
// If there is a possibility that NLIJ will not be an option due to the
// "special case" processing that puts a send/receive plan between the join node
// and its inner child node, other access paths need to be considered that use the
// same indexes as those identified so far but in a simpler, less effective way
// that does not rely on inner-outer expressions.
// The following simplistic method of finding these access paths is to force
// inner-outer expressions to be handled as NLJ-compatible post-filters and repeat
// the search for access paths.
// This will typically generate some duplicate access paths, including the naive
// sequential scan path and any indexed paths that happened to use only the inner
// expressions.
// For now, we deal with this redundancy by dropping (and re-generating) all
// access paths EXCPT those that reference the inner-outer expressions.
// TODO: implementing access path hash and equality and possibly using a "Set"
// would allow deduping as new access paths are added OR
// the simplified access path search process could be based on
// the existing indexed access paths -- for each access path that "hasInnerOuterIndexExpression"
// try to generate and add a simpler access path using the same index,
// this time with the inner-outer expressions used only as non-indexable post-filters.
// Don't bother generating these redundant or inferior access paths unless there is
// an inner-outer expression and a chance that NLIJ will be taken out of the running.
boolean mayNeedInnerSendReceive = ( ! m_partitioning.wasSpecifiedAsSingle()) &&
(m_partitioning.getCountOfPartitionedTables() > 0) &&
(parentNode.getJoinType() != JoinType.INNER) &&
! innerTable.getIsReplicated();
// too expensive/complicated to test here? (parentNode.m_leftNode has a replicated result?) &&
if (mayNeedInnerSendReceive && ! parentNode.m_joinInnerOuterList.isEmpty()) {
List<AccessPath> innerOuterAccessPaths = new ArrayList<>();
for (AccessPath innerAccessPath : innerChildNode.m_accessPaths) {
if ((innerAccessPath.index != null) &&
hasInnerOuterIndexExpression(innerChildNode.getTableAlias(),
innerAccessPath.indexExprs,
innerAccessPath.initialExpr,
innerAccessPath.endExprs)) {
innerOuterAccessPaths.add(innerAccessPath);
}
}
if (parentNode.getJoinType() != JoinType.FULL) {
filterExprs = parentNode.m_joinInnerList;
postExprs = parentNode.m_joinInnerOuterList;
}
else {
// For FULL join type the inner join expressions must be part of the post predicate
// in order to stay at the join node and not be pushed down to the inner node
filterExprs = null;
postExprs = new ArrayList<>(parentNode.m_joinInnerList);
postExprs.addAll(parentNode.m_joinInnerOuterList);
}
Collection<AccessPath>
nljAccessPaths = getRelevantAccessPathsForTable(
innerTable, null, filterExprs, postExprs);
innerChildNode.m_accessPaths.clear();
innerChildNode.m_accessPaths.addAll(nljAccessPaths);
innerChildNode.m_accessPaths.addAll(innerOuterAccessPaths);
}
assert(innerChildNode.m_accessPaths.size() > 0);
} |
java | public int add(final Message msg, boolean resize) {
if(msg == null) return 0;
if(index >= messages.length) {
if(!resize)
return 0;
resize();
}
messages[index++]=msg;
return 1;
} |
java | public static void addInitParameters(Holder holder, Properties subSection) {
//TODO rename initparam to property
Properties properties = PropertiesSupport.getSubsection(subSection, "initparam");
// System.out.println("PROPS:" + properties);
for (Object key : properties.keySet()) {
// System.out.println(key + "->" + properties.get(key));
holder.setInitParameter(key.toString(), (String)properties.get(key));
}
} |
java | public UrlChain moreUrl(Object... urlParts) {
final String argTitle = "urlParts";
assertArgumentNotNull(argTitle, urlParts);
checkWrongUrlChainUse(argTitle, urlParts);
this.urlParts = urlParts;
return this;
} |
python | def showPluginMenu(self, panel, point=None):
"""
Creates the interface menu for this view widget. If no point is \
supplied, then the current cursor position will be used.
:param panel | <XViewPanel>
point | <QPoint> || None
"""
if not self._pluginMenu:
self._pluginMenu = XViewPluginMenu(self)
if point is None:
point = QtGui.QCursor.pos()
self._pluginMenu.setCurrentPanel(panel)
self._pluginMenu.exec_(point) |
python | def load_all(self):
'''
Helper function for actual Insights client use
'''
# check for custom conf file before loading conf
self._load_command_line(conf_only=True)
self._load_config_file()
self._load_env()
self._load_command_line()
self._imply_options()
self._validate_options()
return self |
java | protected Association getAssociation(final ServerManager serverManager, final ParameterList parameterList) {
try {
val authReq = AuthRequest.createAuthRequest(parameterList, serverManager.getRealmVerifier());
val parameterMap = authReq.getParameterMap();
if (parameterMap != null && !parameterMap.isEmpty()) {
val assocHandle = (String) parameterMap.get(OpenIdProtocolConstants.OPENID_ASSOCHANDLE);
if (assocHandle != null) {
return serverManager.getSharedAssociations().load(assocHandle);
}
}
} catch (final MessageException e) {
LOGGER.error("Message exception : [{}]", e.getMessage(), e);
}
return null;
} |
java | List<MemberState> getReserveMemberStates(Comparator<MemberState> comparator) {
List<MemberState> reserveMembers = new ArrayList<>(getReserveMemberStates());
Collections.sort(reserveMembers, comparator);
return reserveMembers;
} |
python | def _GetHeader(self):
"""Returns header."""
header = []
for value in self.values:
try:
header.append(value.Header())
except SkipValue:
continue
return header |
java | public static String sha256(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest messageDigest;
messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(string.getBytes("UTF-8"));
return String.valueOf(Hex.encodeHex(hash));
} |
python | def exclude(self, col: str, val):
"""
Delete rows based on value
:param col: column name
:type col: str
:param val: value to delete
:type val: any
:example: ``ds.exclude("Col 1", "value")``
"""
try:
self.df = self.df[self.df[col] != val]
except Exception as e:
self.err(e, "Can not exclude rows based on value " + str(val)) |
python | def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # 文章图片list
'abstract': '', # 文章摘要
'time': '' # 文章推送时间
},
'gzh': {
'profile_url': '', # 公众号最近10条群发页链接
'headimage': '', # 头像
'wechat_name': '', # 名称
'isv': '', # 是否加v
}
}
"""
page = etree.HTML(text)
lis = page.xpath('//ul[@class="news-list"]/li')
articles = []
for li in lis:
url = get_first_of_element(li, 'div[1]/a/@href')
if url:
title = get_first_of_element(li, 'div[2]/h3/a')
imgs = li.xpath('div[1]/a/img/@src')
abstract = get_first_of_element(li, 'div[2]/p')
time = get_first_of_element(li, 'div[2]/div/span/script/text()')
gzh_info = li.xpath('div[2]/div/a')[0]
else:
url = get_first_of_element(li, 'div/h3/a/@href')
title = get_first_of_element(li, 'div/h3/a')
imgs = []
spans = li.xpath('div/div[1]/a')
for span in spans:
img = span.xpath('span/img/@src')
if img:
imgs.append(img)
abstract = get_first_of_element(li, 'div/p')
time = get_first_of_element(li, 'div/div[2]/span/script/text()')
gzh_info = li.xpath('div/div[2]/a')[0]
if title is not None:
title = get_elem_text(title).replace("red_beg", "").replace("red_end", "")
if abstract is not None:
abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "")
time = re.findall('timeConvert\(\'(.*?)\'\)', time)
time = list_or_empty(time, int)
profile_url = get_first_of_element(gzh_info, '@href')
headimage = get_first_of_element(gzh_info, '@data-headimage')
wechat_name = get_first_of_element(gzh_info, 'text()')
gzh_isv = get_first_of_element(gzh_info, '@data-isv', int)
articles.append({
'article': {
'title': title,
'url': url,
'imgs': format_image_url(imgs),
'abstract': abstract,
'time': time
},
'gzh': {
'profile_url': profile_url,
'headimage': headimage,
'wechat_name': wechat_name,
'isv': gzh_isv,
}
})
return articles |
java | public static void assertNotEqual(Object a, Object b, String message) {
if (Objects.equals(a, b)) {
fail(message);
}
} |
java | public void configure(Object obj, Element cfg, int startIdx)
throws Exception {
String id = getAttribute(cfg, "id");
if (id != null) {
_idMap.put(id, obj);
}
Element[] children = getChildren(cfg);
for (int i = startIdx; i < children.length; i++) {
Element node = children[i];
//CHECKSTYLE:OFF
try {
// TODO: in case switching to jdk 7, this could be a switch!
String tag = node.getTagName();
if ("Set".equals(tag)) {
set(obj, node);
} else if ("Put".equals(tag)) {
put(obj, node);
} else if ("Call".equals(tag)) {
call(obj, node);
} else if ("Get".equals(tag)) {
get(obj, node);
} else if ("New".equals(tag)) {
newObj(obj, node);
} else if ("Array".equals(tag)) {
newArray(obj, node);
} else if ("Ref".equals(tag)) {
refObj(obj, node);
} else if ("Property".equals(tag)) {
propertyObj(obj, node);
} else {
throw new IllegalStateException("Unknown tag: " + tag);
}
} catch (Exception e) {
LOG.warn("Config error at " + node, e.toString());
throw e;
}
//CHECKSTYLE:ON
}
} |
java | public StringColumn append(String value) {
try {
lookupTable.append(value);
} catch (NoKeysAvailableException ex) {
lookupTable = lookupTable.promoteYourself();
try {
lookupTable.append(value);
} catch (NoKeysAvailableException e) {
// this can't happen
throw new IllegalStateException(e);
}
}
return this;
} |
python | def as_dict(self):
""" Return a dictionary containing the current values
of the object.
Returns:
(dict): The object represented as a dictionary
"""
out = {}
for prop in self:
propval = getattr(self, prop)
if hasattr(propval, 'for_json'):
out[prop] = propval.for_json()
elif isinstance(propval, list):
out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval]
elif isinstance(propval, (ProtocolBase, LiteralValue)):
out[prop] = propval.as_dict()
elif propval is not None:
out[prop] = propval
return out |
java | public static <A extends Number & Comparable<?>> NumberExpression<Double> degrees(Expression<A> num) {
return Expressions.numberOperation(Double.class, Ops.MathOps.DEG, num);
} |
java | public static LocalResource createLocalResource(FileSystem fs, Path provisionedResourcePath){
try {
FileStatus scFileStatus = fs.getFileStatus(provisionedResourcePath);
LocalResource localResource = LocalResource.newInstance(
ConverterUtils.getYarnUrlFromURI(provisionedResourcePath.toUri()),
LocalResourceType.FILE,
LocalResourceVisibility.APPLICATION, scFileStatus.getLen(),
scFileStatus.getModificationTime());
return localResource;
}
catch (Exception e) {
throw new IllegalStateException("Failed to communicate with FileSystem while creating LocalResource: " + fs, e);
}
} |
python | def put(self, key, value, lease=None):
"""Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean
"""
payload = {
"key": _encode(key),
"value": _encode(value)
}
if lease:
payload['lease'] = lease.id
self.post(self.get_url("/kv/put"), json=payload)
return True |
java | @Override
protected void checkForSessionIdListenerAndAdd(Object listener){
// Added for Servlet 3.1 support
if (isHttpSessionIdListener(listener)) {
// add to the HttpSessionIdListener list
((IHttpSessionContext31)this.sessionCtx).addHttpSessionIdListener((javax.servlet.http.HttpSessionIdListener) listener, name);
this.sessionIdListeners.add(listener);
}
} |
java | @Override
public Collection<String> sendEmailMessages(final Collection<EmailMessage> emailMessages)
throws MessagingException
{
final List<String> messageIds = new ArrayList<>();
for (final EmailMessage emailMessage : emailMessages)
{
final String messageId = sendEmailMessage(emailMessage);
messageIds.add(messageId);
}
return messageIds;
} |
java | public void setTransportControlFlags(int transportControlFlags) {
if (sHasRemoteControlAPIs) {
try {
sRCCSetTransportControlFlags.invoke(mActualRemoteControlClient,
transportControlFlags);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
java | protected void closeDialog(boolean breakingUp) {
m_controller.stopEditingGroupcontainer();
m_editingPlaceholder.removeFromParent();
m_editorDialog.hide();
RootPanel.get().removeStyleName(I_CmsLayoutBundle.INSTANCE.containerpageCss().groupcontainerEditing());
if (!breakingUp) {
m_groupContainer.clearEditingPlaceholder();
Style style = m_groupContainer.getElement().getStyle();
style.clearPosition();
style.clearTop();
style.clearLeft();
style.clearZIndex();
style.clearWidth();
m_parentContainer.insert(m_groupContainer, m_indexPosition);
m_groupContainer.getElementOptionBar().setVisible(true);
if (!m_groupContainer.iterator().hasNext()) {
// group-container is empty, mark it
m_groupContainer.addStyleName(I_CmsLayoutBundle.INSTANCE.containerpageCss().emptyGroupContainer());
}
}
clearInstance();
removeFromParent();
if (!m_controller.getData().isUseClassicEditor()) {
for (Widget element : m_groupContainer) {
if (element instanceof CmsContainerPageElementPanel) {
((CmsContainerPageElementPanel)element).removeInlineEditor();
}
}
}
m_controller.reinitializeButtons();
m_controller.reInitInlineEditing();
m_controller.fireEvent(new CmsContainerpageEvent(EventType.elementEdited));
} |
java | @Override
public Object invokeMethod(final Class sender, final Object object, final String methodName, final Object[] arguments, final boolean isCallToSuper, final boolean fromInsideClass) {
return doCall(object, methodName, arguments, interceptor, new Callable() {
public Object call() {
return adaptee.invokeMethod(sender, object, methodName, arguments, isCallToSuper, fromInsideClass);
}
});
} |
java | public static long count_filtered(nitro_service service, String monitorname, String filter) throws Exception{
lbmonbindings_service_binding obj = new lbmonbindings_service_binding();
obj.set_monitorname(monitorname);
options option = new options();
option.set_count(true);
option.set_filter(filter);
lbmonbindings_service_binding[] response = (lbmonbindings_service_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} |
python | def get_index(lis, argument):
"""Find the index of an item, given either the item or index as an argument.
Particularly useful as a wrapper for arguments like channel or axis.
Parameters
----------
lis : list
List to parse.
argument : int or object
Argument.
Returns
-------
int
Index of chosen object.
"""
# get channel
if isinstance(argument, int):
if -len(lis) <= argument < len(lis):
return argument
else:
raise IndexError("index {0} incompatible with length {1}".format(argument, len(lis)))
else:
return lis.index(argument) |
java | @Deprecated
public void fatal(Object message, Object[] params) {
doLog(Level.FATAL, FQCN, message, params, null);
} |
python | def get_all_allowed_plugins(self):
"""
Return which plugins are allowed by the placeholder fields.
"""
# Get all allowed plugins of the various placeholders together.
if not hasattr(self.model, '_meta_placeholder_fields'):
# No placeholder fields in the model, no need for inlines.
return []
plugins = []
for name, field in self.model._meta_placeholder_fields.items():
assert isinstance(field, PlaceholderField)
if field.plugins is None:
# no limitations, so all is allowed
return extensions.plugin_pool.get_plugins()
else:
plugins += field.plugins
return list(set(plugins)) |
java | public SignedJWT signToken(JWTClaimsSet claims) {
try {
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims);
signedJWT.sign(new MACSigner(this.jwtSharedSecret));
return signedJWT;
} catch (JOSEException e) {
throw new RuntimeException("Error signing JSON Web Token", e);
}
} |
java | @XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "arcsech")
public JAXBElement<ElementaryFunctionsType> createArcsech(ElementaryFunctionsType value) {
return new JAXBElement<ElementaryFunctionsType>(_Arcsech_QNAME, ElementaryFunctionsType.class, null, value);
} |
java | public static <S extends RepresentationModel<?>> HeaderLinksResponseEntity<S> wrap(S entity) {
Assert.notNull(entity, "ResourceSupport must not be null!");
return new HeaderLinksResponseEntity<>(ResponseEntity.ok(entity));
} |
java | @XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "jpegPhoto")
public JAXBElement<byte[]> createJpegPhoto(byte[] value) {
return new JAXBElement<byte[]>(_JpegPhoto_QNAME, byte[].class, null, (value));
} |
java | private static int parseDotted(String javaVersion) {
try {
String[] parts = javaVersion.split("[._]");
int firstVer = Integer.parseInt(parts[0]);
if (firstVer == 1 && parts.length > 1) {
return Integer.parseInt(parts[1]);
} else {
return firstVer;
}
} catch (NumberFormatException e) {
return -1;
}
} |
python | def get_gconf_http_proxy ():
"""Return host:port for GConf HTTP proxy if found, else None."""
try:
import gconf
except ImportError:
return None
try:
client = gconf.client_get_default()
if client.get_bool("/system/http_proxy/use_http_proxy"):
host = client.get_string("/system/http_proxy/host")
port = client.get_int("/system/http_proxy/port")
if host:
if not port:
port = 8080
return "%s:%d" % (host, port)
except Exception as msg:
log.debug(LOG_CHECK, "error getting HTTP proxy from gconf: %s", msg)
pass
return None |
python | def _decode8(self, offset):
"""
Decode an UTF-8 String at the given offset
:param offset: offset of the string inside the data
:return: str
"""
# UTF-8 Strings contain two lengths, as they might differ:
# 1) the UTF-16 length
str_len, skip = self._decode_length(offset, 1)
offset += skip
# 2) the utf-8 string length
encoded_bytes, skip = self._decode_length(offset, 1)
offset += skip
data = self.m_charbuff[offset: offset + encoded_bytes]
assert self.m_charbuff[offset + encoded_bytes] == 0, \
"UTF-8 String is not null terminated! At offset={}".format(offset)
return self._decode_bytes(data, 'utf-8', str_len) |
python | def vector_drive(self, vx, vy, vw, tm_diff):
"""Call this from your :func:`PhysicsEngine.update_sim` function.
Will update the robot's position on the simulation field.
This moves the robot using a velocity vector relative to the robot
instead of by speed/rotation speed.
:param vx: Speed in x direction relative to robot in ft/s
:param vy: Speed in y direction relative to robot in ft/s
:param vw: Clockwise rotational speed in rad/s
:param tm_diff: Amount of time speed was traveled
"""
# if the robot is disabled, don't do anything
if not self.robot_enabled:
return
angle = vw * tm_diff
vx = vx * tm_diff
vy = vy * tm_diff
x = vx * math.sin(angle) + vy * math.cos(angle)
y = vx * math.cos(angle) + vy * math.sin(angle)
self.distance_drive(x, y, angle) |
java | public void setMobileCarrierTargeting(com.google.api.ads.admanager.axis.v201805.MobileCarrierTargeting mobileCarrierTargeting) {
this.mobileCarrierTargeting = mobileCarrierTargeting;
} |
java | public RetryTemplateBuilder customPolicy(RetryPolicy policy) {
Assert.notNull(policy, "Policy should not be null");
Assert.isNull(this.baseRetryPolicy,
"You have already selected another retry policy");
this.baseRetryPolicy = policy;
return this;
} |
java | public void checkServerTrusted( X509Certificate[] chain, String authType )
throws CertificateException
{
X509Certificate certificate = chain[0];
String cert = fingerprint( certificate );
if ( this.fingerprint == null )
{
try
{
saveTrustedHost( cert );
}
catch ( IOException e )
{
throw new CertificateException( format(
"Failed to save the server ID and the certificate received from the server to file %s.\n" +
"Server ID: %s\nReceived cert:\n%s",
knownHosts.getAbsolutePath(), serverId, X509CertToString( cert ) ), e );
}
}
else
{
if ( !this.fingerprint.equals( cert ) )
{
throw new CertificateException( format(
"Unable to connect to neo4j at `%s`, because the certificate the server uses has changed. " +
"This is a security feature to protect against man-in-the-middle attacks.\n" +
"If you trust the certificate the server uses now, simply remove the line that starts with " +
"`%s` " +
"in the file `%s`.\n" +
"The old certificate saved in file is:\n%sThe New certificate received is:\n%s",
serverId, serverId, knownHosts.getAbsolutePath(),
X509CertToString( this.fingerprint ), X509CertToString( cert ) ) );
}
}
} |
java | public void setAuthorizationPersistencePolicy(PersistencePolicy policy) {
if (policy == null) {
throw new IllegalArgumentException("The policy argument cannot be null");
}
if (preferences.persistencePolicy.get() != policy) {
preferences.persistencePolicy.set(policy);
preferences.accessToken.updateStateByPolicy();
preferences.idToken.updateStateByPolicy();
}
} |
python | def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular to the begin and end vectors
# Perp = Vector3fT()
Perp = Vector3fCross(self.m_StVec, self.m_EnVec)
NewRot = Quat4fT()
# //Compute the length of the perpendicular vector
if Vector3fLength(Perp) > Epsilon: # //if its non-zero
# //We're ok, so return the perpendicular vector as the transform after all
NewRot[X] = Perp[X]
NewRot[Y] = Perp[Y]
NewRot[Z] = Perp[Z]
# //In the quaternion values, w is cosine(theta / 2), where theta is rotation angle
NewRot[W] = Vector3fDot(self.m_StVec, self.m_EnVec)
else: # //if its zero
# //The begin and end vectors coincide, so return a quaternion of zero matrix (no rotation)
NewRot[X] = NewRot[Y] = NewRot[Z] = NewRot[W] = 0.0
return NewRot |
java | private static Object deserializePage(String value, Type resultType, Type wireType, SerializerAdapter serializer, SerializerEncoding encoding) throws IOException {
final Type wireResponseType;
if (wireType == Page.class) {
// If the type is the 'Page' interface [i.e. `@ReturnValueWireType(Page.class)`], we will use the 'ItemPage' class instead.
wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType);
} else {
wireResponseType = wireType;
}
return serializer.deserialize(value, wireResponseType, encoding);
} |
python | def set(cls, var_name: str, value: Any) -> 'Configuration':
"""
Set the variable
:param var_name: Variable name
:param value: Value of variable
:return: :class:`~haps.config.Configuration` instance for easy\
chaining
"""
with cls._lock:
if var_name not in cls().cache:
cls().cache[var_name] = value
else:
raise ConfigurationError(
f'Value for {var_name} already set')
return cls() |
python | def unregister(self, alias):
"""Unregisters a service instance.
Stops a service and removes it from the manager.
Args:
alias: string, the alias of the service instance to unregister.
"""
if alias not in self._service_objects:
raise Error(self._device,
'No service is registered with alias "%s".' % alias)
service_obj = self._service_objects.pop(alias)
if service_obj.is_alive:
with expects.expect_no_raises(
'Failed to stop service instance "%s".' % alias):
service_obj.stop() |
java | protected synchronized static void drawAt(final Canvas canvas, final Drawable drawable,
final int x, final int y, final boolean shadow,
final float aMapOrientation) {
canvas.save();
canvas.rotate(-aMapOrientation, x, y);
drawable.copyBounds(mRect);
drawable.setBounds(mRect.left + x, mRect.top + y, mRect.right + x, mRect.bottom + y);
drawable.draw(canvas);
drawable.setBounds(mRect);
canvas.restore();
} |
java | public com.google.api.ads.admanager.axis.v201902.Location[] getExcludedLocations() {
return excludedLocations;
} |
java | public boolean wrapInAnchor() {
if (ext(ANCHORLINKS | EXTANCHORLINKS)) {
SuperNode node = (SuperNode) peek();
List<Node> children = node.getChildren();
if (ext(EXTANCHORLINKS)) {
if (children.size() > 0) {
AnchorNodeInfo nodeInfo = new AnchorNodeInfo();
collectChildrensText(node, nodeInfo);
String text = nodeInfo.text.toString().trim();
if (text.length() > 0) {
AnchorLinkNode anchor = new AnchorLinkNode(text, "");
anchor.setStartIndex(nodeInfo.startIndex);
anchor.setEndIndex(nodeInfo.endIndex);
children.add(0, anchor);
}
}
} else {
if (children.size() == 1) {
Node child = children.get(0);
if (child instanceof TextNode) {
AnchorLinkNode anchor = new AnchorLinkNode(((TextNode) child).getText());
anchor.setStartIndex(child.getStartIndex());
anchor.setEndIndex(child.getEndIndex());
children.set(0, anchor);
}
}
}
}
return true;
} |
python | def is_iframe(self, el):
"""Check if element is an `iframe`."""
return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el) |
python | def _rule2path(cls, rule):
"""Convert relative Flask rule to absolute OpenAPI path."""
typeless = re.sub(r'<\w+?:', '<', rule) # remove Flask types
return typeless.replace('<', '{').replace('>', '}') |
java | protected ClientVersionBean getClientVersionInternal(String organizationId, String clientId, String version,
boolean hasPermission) {
try {
storage.beginTx();
ClientVersionBean clientVersion = storage.getClientVersion(organizationId, clientId, version);
if (clientVersion == null) {
throw ExceptionFactory.clientVersionNotFoundException(clientId, version);
}
// Hide some data if the user doesn't have the clientView permission
if (!hasPermission) {
clientVersion.setApikey(null);
}
storage.commitTx();
log.debug(String.format("Got new client version %s: %s", clientVersion.getClient().getName(), clientVersion)); //$NON-NLS-1$
return clientVersion;
} catch (AbstractRestException e) {
storage.rollbackTx();
throw e;
} catch (Exception e) {
storage.rollbackTx();
throw new SystemErrorException(e);
}
} |
java | @Modified
protected void modified(ComponentContext context) throws Exception {
processProperties(context.getProperties());
deregisterJavaMailMBean();
registerJavaMailMBean();
} |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
@Deprecated
public <T, I extends Serializable> ResourceRepositoryStub<T, I> getQueryParamsRepository(Class<T> resourceClass) {
init();
RegistryEntry entry = resourceRegistry.findEntry(resourceClass);
// TODO fix this in katharsis, should be able to get original resource
ResourceRepositoryAdapter repositoryAdapter = entry.getResourceRepository(null);
return (ResourceRepositoryStub<T, I>) repositoryAdapter.getResourceRepository();
} |
python | def count_start(tokenizer):
"""
A decorator which wrap the given tokenizer to yield (token, start).
Notice! the decorated tokenizer must take a int arguments stands for the start position of the input context/sentence
>>> tokenizer = lambda sentence: sentence.split(' ')
>>> tokenizer('The quick brown fox jumps over the lazy dog')
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the',
'lazy', 'dog']
>>> tokenizer = count_start(tokenizer)
>>> tokenizer('The quick brown fox jumps over the lazy dog', 0)
('The', 0)
('quick', 4)
...
"""
def wrapper(context, base):
tokens = list(tokenizer(context))
flag = 0
for token in tokens:
start = context.index(token, flag)
flag = start + len(token)
yield (token, base + start)
return wrapper |
python | def duplicate_transcript(self, transcript_id, organism=None, sequence=None):
"""
Duplicate a transcripte
:type transcript_id: str
:param transcript_id: Transcript UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
:param sequence: Sequence Name
:rtype: dict
:return: A standard apollo feature dictionary ({"features": [{...}]})
"""
data = {
'features': [
{
'uniquename': transcript_id
}
]
}
data = self._update_data(data, organism, sequence)
return self.post('duplicateTranscript', data) |
java | public SmbTransport getDc(String domain, SmbExtendedAuthenticator authenticator,
NtlmPasswordAuthentication auth) throws SmbAuthException {
// public SmbTransport getDc(String domain,
// NtlmPasswordAuthentication auth) throws SmbAuthException {
// SmbAuthenticator<<
if (DISABLED)
return null;
try {
UniAddress addr = UniAddress.getByName(domain, true);
SmbTransport trans = SmbTransport.getSmbTransport(addr, 0);
// >>SmbAuthenticator Fixed trusted domain issue.
DfsReferral dr = trans.getDfsReferrals(authenticator,auth, "\\" + domain, 1);
// DfsReferral dr = trans.getDfsReferrals(auth, "\\" + domain, 1);
// SmbAuthenticator<<
if (dr != null) {
DfsReferral start = dr;
IOException e = null;
do {
try {
addr = UniAddress.getByName(dr.server);
return SmbTransport.getSmbTransport(addr, 0);
} catch (IOException ioe) {
e = ioe;
}
dr = dr.next;
} while (dr != start);
throw e;
}
} catch (IOException ioe) {
if (log.level >= 3)
ioe.printStackTrace(log);
if (strictView && ioe instanceof SmbAuthException) {
throw (SmbAuthException)ioe;
}
}
return null;
} |
python | def get_domain_event(self, originator_id, position):
"""
Gets a domain event from the sequence identified by `originator_id`
at position `eq`.
:param originator_id: ID of a sequence of events
:param position: get item at this position
:return: domain event
"""
sequenced_item = self.record_manager.get_item(
sequence_id=originator_id,
position=position,
)
return self.mapper.event_from_item(sequenced_item) |
python | def record_calculation_start(self, variable_name, period, **parameters):
"""
Record that OpenFisca started computing a variable.
:param str variable_name: Name of the variable starting to be computed
:param Period period: Period for which the variable is being computed
:param list parameters: Parameter with which the variable is being computed
"""
key = self._get_key(variable_name, period, **parameters)
if self.stack: # The variable is a dependency of another variable
parent = self.stack[-1]
self.trace[parent]['dependencies'].append(key)
else: # The variable has been requested by the client
self.requested_calculations.add(key)
if not self.trace.get(key):
self.trace[key] = {'dependencies': [], 'parameters': {}}
self.stack.append(key)
self._computation_log.append((key, len(self.stack)))
self.usage_stats[variable_name]['nb_requests'] += 1 |
python | def display(self, img, title=None, colormap=None, style='image',
subtitles=None, auto_contrast=False, contrast_level=None, **kws):
"""display image"""
if title is not None:
self.SetTitle(title)
if subtitles is not None:
self.subtitles = subtitles
cmode = self.config_mode.lower()[:3]
img = np.array(img)
if len(img.shape) == 3:
ishape = img.shape
# make sure 3d image is shaped (NY, NX, 3)
if ishape[2] != 3:
if ishape[0] == 3:
img = img.swapaxes(0, 1).swapaxes(1, 2)
elif ishape[1] == 3:
img = img.swapaxes(1, 2)
if cmode != 'rgb':
for comp in self.config_panel.Children:
comp.Destroy()
self.config_mode = 'rgb'
self.panel.conf.tricolor_mode = 'rgb'
self.Build_ConfigPanel()
else:
if cmode != 'int':
for comp in self.config_panel.Children:
comp.Destroy()
self.config_mode = 'int'
self.Build_ConfigPanel()
if contrast_level is None:
if auto_contrast:
cl_str = '1.0'
else:
cl_str = self.contrast_panel.choice.GetStringSelection()
else:
cl_int = max(np.where(Contrast_NDArray<=contrast_level)[0])
cl_str = Contrast_List[cl_int]
if cl_str == 'None':
contrast_level = 0
else:
contrast_level = float(cl_str)
self.contrast_panel.choice.SetStringSelection(cl_str)
self.panel.conf.contrast_level = contrast_level
self.panel.display(img, style=style, contrast_level=contrast_level,
**kws)
self.set_contrast_levels(contrast_level=contrast_level)
self.panel.conf.title = title
if colormap is not None and self.config_mode == 'int':
self.cmap_panels[0].set_colormap(name=colormap)
if subtitles is not None:
if isinstance(subtitles, dict):
self.set_subtitles(**subtitles)
elif self.config_mode == 'int':
self.set_subtitles(red=subtitles)
self.panel.conf.style = 'image'
self.contrast_panel.Enable()
self.interp_panel.Enable()
if style == 'contour':
self.panel.conf.style = 'contour'
self.contrast_panel.Disable()
self.interp_panel.Disable()
self.config_panel.Refresh()
self.SendSizeEvent()
wx.CallAfter(self.EnableMenus) |
java | private String buildCacheKey(final String[] objectIds, final String namespace) {
if (objectIds.length == 1) {
checkKeyPart(objectIds[0]);
return namespace + SEPARATOR + objectIds[0];
}
StringBuilder cacheKey = new StringBuilder(namespace);
cacheKey.append(SEPARATOR);
for (String id : objectIds) {
checkKeyPart(id);
cacheKey.append(id);
cacheKey.append(ID_SEPARATOR);
}
cacheKey.deleteCharAt(cacheKey.length() - 1);
return cacheKey.toString();
} |
java | public Object navigation(Context context, NavigationCallback callback) {
return ARouter.getInstance().navigation(context, this, -1, callback);
} |
python | def process_request(self, request):
"""
Reloads glitter URL patterns if page URLs change.
Avoids having to restart the server to recreate the glitter URLs being used by Django.
"""
global _urlconf_pages
page_list = list(
Page.objects.exclude(glitter_app_name='').values_list('id', 'url').order_by('id')
)
with _urlconf_lock:
if page_list != _urlconf_pages:
glitter_urls = 'glitter.urls'
if glitter_urls in sys.modules:
importlib.reload(sys.modules[glitter_urls])
_urlconf_pages = page_list |
java | @Override
public BundleHashcodeType getBundleHashcodeType(String requestedPath) {
BundleHashcodeType typeBundleHashcode = BundleHashcodeType.UNKNOW_BUNDLE;
String[] pathInfos = PathNormalizer.extractBundleInfoFromPath(requestedPath, bundlePrefixes);
if (pathInfos != null) {
String bundlePrefix = pathInfos[0];
String bundleId = pathInfos[1];
String variantKey = pathInfos[2];
String hashcode = pathInfos[3];
JoinableResourceBundle bundle = resolveBundleForPath(bundleId);
if (bundle != null) {
String bundleHashcode = bundle.getBundleDataHashCode(variantKey);
if (hashcode == null && bundleHashcode == null || hashcode != null && hashcode.equals(bundleHashcode)
&& ((bundlePrefix == null && bundle.getBundlePrefix() == null)
|| (bundlePrefix != null && bundlePrefix.equals(bundle.getBundlePrefix())))) {
typeBundleHashcode = BundleHashcodeType.VALID_HASHCODE;
} else {
typeBundleHashcode = BundleHashcodeType.INVALID_HASHCODE;
}
}
}
return typeBundleHashcode;
} |
java | public Properties getProperties() {
Properties props = new Properties();
for(String name : this.users.keySet()) {
SimpleAccount acct = this.users.get(name);
props.setProperty(USERNAME_PREFIX + name, acct.getCredentials().toString());
}
return props;
} |
python | def eth_getTransactionByBlockHashAndIndex(self, bhash, index=0):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblockhashandindex
:param bhash: Block hash
:type bhash: str
:param index: Index position (optional)
:type index: int
"""
result = yield from self.rpc_call('eth_getTransactionByBlockHashAndIndex',
[bhash, hex(index)])
# TODO: Update result response
return result |
java | private void setParentIcon(boolean iconify) {
if (rootParent instanceof JFrame) {
JFrame frame = (JFrame) rootParent;
int state = frame.getExtendedState();
((JFrame) rootParent).setExtendedState(iconify ? state | Frame.ICONIFIED : state & ~Frame.ICONIFIED);
}
} |
python | def generate_scan_configuration_description(scan_parameters):
'''Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription
Parameters
----------
scan_parameters : list, tuple
List of scan parameters names (strings).
Returns
-------
table_description : dict
Table description.
Usage
-----
pytables.createTable(self.raw_data_file_h5.root, name = 'scan_parameters', description = generate_scan_configuration_description(['PlsrDAC']), title = 'scan_parameters', filters = filter_tables)
'''
table_description = np.dtype([(key, tb.StringCol(512, pos=idx)) for idx, key in enumerate(scan_parameters)])
return table_description |
python | def setup(app):
"""Initialize Sphinx extension."""
import sphinx
from .parser import CommonMarkParser
if sphinx.version_info >= (1, 8):
app.add_source_suffix('.md', 'markdown')
app.add_source_parser(CommonMarkParser)
elif sphinx.version_info >= (1, 4):
app.add_source_parser('.md', CommonMarkParser)
return {'version': __version__, 'parallel_read_safe': True} |
python | def ret_range_minions(self):
'''
Return minions that are returned by a range query
'''
if HAS_RANGE is False:
raise RuntimeError("Python lib 'seco.range' is not available")
minions = {}
range_hosts = _convert_range_to_list(self.tgt, __opts__['range_server'])
return self._ret_minions(range_hosts.__contains__) |
python | def split_args_text_to_list(self, args_text):
"""Split the text including multiple arguments to list.
This function uses a comma to separate arguments and ignores a comma in
brackets ans quotes.
"""
args_list = []
idx_find_start = 0
idx_arg_start = 0
try:
pos_quote = self._find_quote_position(args_text)
pos_round = self._find_bracket_position(args_text, '(', ')',
pos_quote)
pos_curly = self._find_bracket_position(args_text, '{', '}',
pos_quote)
pos_square = self._find_bracket_position(args_text, '[', ']',
pos_quote)
except IndexError:
return None
while True:
pos_comma = args_text.find(',', idx_find_start)
if pos_comma == -1:
break
idx_find_start = pos_comma + 1
if self.is_char_in_pairs(pos_comma, pos_round) or \
self.is_char_in_pairs(pos_comma, pos_curly) or \
self.is_char_in_pairs(pos_comma, pos_square) or \
self.is_char_in_pairs(pos_comma, pos_quote):
continue
args_list.append(args_text[idx_arg_start:pos_comma])
idx_arg_start = pos_comma + 1
if idx_arg_start < len(args_text):
args_list.append(args_text[idx_arg_start:])
return args_list |
java | boolean isEquivalent(final Path other) {
if (pathComponents.isEmpty() && other.pathComponents.isEmpty()) {
return true;
}
if (pathComponents.isEmpty() || other.pathComponents.isEmpty()) {
return false;
}
final String thisFirst = this.pathComponents.getFirst();
final String otherFirst = other.pathComponents.getFirst();
final int thisStartIndex;
final int otherStartIndex;
if ((START_TOKEN.equals(thisFirst) && START_TOKEN.equals(otherFirst))) {
thisStartIndex = 1;
otherStartIndex = 1;
} else if (!START_TOKEN.equals(thisFirst) && !START_TOKEN.equals(otherFirst)) {
thisStartIndex = 0;
otherStartIndex = 0;
} else if (START_TOKEN.equals(thisFirst)) {
thisStartIndex = 1;
otherStartIndex = other.pathComponents.indexOf(this.pathComponents.get(1));
} else {
thisStartIndex = this.pathComponents.indexOf(other.pathComponents.get(1));
otherStartIndex = 1;
}
return !(thisStartIndex == -1 || otherStartIndex == -1)
&& this.pathComponents.subList(thisStartIndex, this.pathComponents.size()).equals(other.pathComponents.subList(otherStartIndex, other.pathComponents.size()));
} |
java | B append(String path) {
Preconditions.checkArgument(
path != null && !path.isEmpty(), "'path' must be a non-empty String");
ImmutableList.Builder<String> components = ImmutableList.builder();
components.addAll(this.getSegments());
components.add(splitChildPath(path));
return createPathWithSegments(components.build());
} |
python | def _match_to_morph_parents(self, type, results):
"""
Match the results for a given type to their parent.
:param type: The parent type
:type type: str
:param results: The results to match to their parent
:type results: Collection
"""
for result in results:
if result.get_key() in self._dictionary.get(type, []):
for model in self._dictionary[type][result.get_key()]:
model.set_relation(
self._relation, Result(result, self, model, related=result)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.