language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def save_seedhex_file(self, path: str) -> None:
"""
Save hexadecimal seed file from seed
:param path: Authentication file path
"""
seedhex = convert_seed_to_seedhex(self.seed)
with open(path, 'w') as fh:
fh.write(seedhex) |
python | def websso(request):
"""Logs a user in using a token from Keystone's POST."""
referer = request.META.get('HTTP_REFERER', settings.OPENSTACK_KEYSTONE_URL)
auth_url = utils.clean_up_auth_url(referer)
token = request.POST.get('token')
try:
request.user = auth.authenticate(request=request, auth_url=auth_url,
token=token)
except exceptions.KeystoneAuthException as exc:
if utils.is_websso_default_redirect():
res = django_http.HttpResponseRedirect(settings.LOGIN_ERROR)
else:
msg = 'Login failed: %s' % six.text_type(exc)
res = django_http.HttpResponseRedirect(settings.LOGIN_URL)
res.set_cookie('logout_reason', msg, max_age=10)
return res
auth_user.set_session_from_user(request, request.user)
auth.login(request, request.user)
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return django_http.HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) |
python | def setDateReceived(self, value):
"""Sets the date received to this analysis request and to secondary
analysis requests
"""
self.Schema().getField('DateReceived').set(self, value)
for secondary in self.getSecondaryAnalysisRequests():
secondary.setDateReceived(value)
secondary.reindexObject(idxs=["getDateReceived", "is_received"]) |
python | def add_argument(self, arg_name, arg_value):
'''Add an additional argument to be passed to the fitness function
via additional arguments dictionary; this argument/value is not tuned
Args:
arg_name (string): name/dictionary key of argument
arg_value (any): dictionary value of argument
'''
if len(self._employers) > 0:
self._logger.log(
'warn',
'Adding an argument after the employers have been created'
)
if self._args is None:
self._args = {}
self._args[arg_name] = arg_value |
java | public static HeartbeatServices fromConfiguration(Configuration configuration) {
long heartbeatInterval = configuration.getLong(HeartbeatManagerOptions.HEARTBEAT_INTERVAL);
long heartbeatTimeout = configuration.getLong(HeartbeatManagerOptions.HEARTBEAT_TIMEOUT);
return new HeartbeatServices(heartbeatInterval, heartbeatTimeout);
} |
java | public R setPreviousListEvents(E listEvents){
mListEvents = listEvents;
this.setStreamPosition(((IStreamPosition)mListEvents).getNextStreamPosition().toString());
return (R)this;
} |
java | @Nonnull
public <V1 extends T1, V2 extends T2> LToByteBiFunctionBuilder<T1, T2> aCase(Class<V1> argC1, Class<V2> argC2, LToByteBiFunction<V1, V2> function) {
PartialCaseWithByteProduct.The pc = partialCaseFactoryMethod((a1, a2) -> (argC1 == null || argC1.isInstance(a1)) && (argC2 == null || argC2.isInstance(a2)));
pc.evaluate(function);
return self();
} |
java | public Templates newTemplates(Source source)
throws TransformerConfigurationException
{
String baseID = source.getSystemId();
if (null != baseID) {
baseID = SystemIDResolver.getAbsoluteURI(baseID);
}
if (source instanceof DOMSource)
{
DOMSource dsource = (DOMSource) source;
Node node = dsource.getNode();
if (null != node)
return processFromNode(node, baseID);
else
{
String messageStr = XSLMessages.createMessage(
XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
throw new IllegalArgumentException(messageStr);
}
}
TemplatesHandler builder = newTemplatesHandler();
builder.setSystemId(baseID);
try
{
InputSource isource = SAXSource.sourceToInputSource(source);
isource.setSystemId(baseID);
XMLReader reader = null;
if (source instanceof SAXSource)
reader = ((SAXSource) source).getXMLReader();
if (null == reader)
{
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (m_isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
}
if (null == reader)
reader = XMLReaderFactory.createXMLReader();
// If you set the namespaces to true, we'll end up getting double
// xmlns attributes. Needs to be fixed. -sb
// reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
reader.setContentHandler(builder);
reader.parse(isource);
}
catch (org.xml.sax.SAXException se)
{
if (m_errorListener != null)
{
try
{
m_errorListener.fatalError(new TransformerException(se));
}
catch (TransformerConfigurationException ex1)
{
throw ex1;
}
catch (TransformerException ex1)
{
throw new TransformerConfigurationException(ex1);
}
}
else
{
throw new TransformerConfigurationException(se.getMessage(), se);
}
}
catch (Exception e)
{
if (m_errorListener != null)
{
try
{
m_errorListener.fatalError(new TransformerException(e));
return null;
}
catch (TransformerConfigurationException ex1)
{
throw ex1;
}
catch (TransformerException ex1)
{
throw new TransformerConfigurationException(ex1);
}
}
else
{
throw new TransformerConfigurationException(e.getMessage(), e);
}
}
return builder.getTemplates();
} |
java | public static IVarargDependencyInjector bean(final Object target) {
return new AbstractVarargDependencyInjector() {
public void with(Object... dependencies) {
TypeBasedInjector injector = new TypeBasedInjector();
for (Object dependency : dependencies) {
injector.validateInjectionOf(target, dependency);
}
for (Object dependency : dependencies) {
injector.inject(target, dependency);
}
}
};
} |
python | def _update_ned_query_history(
self):
"""*Update the database helper table to give details of the ned cone searches performed*
*Usage:*
.. code-block:: python
stream._update_ned_query_history()
"""
self.log.debug('starting the ``_update_ned_query_history`` method')
myPid = self.myPid
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=self.log
)
# UPDATE THE DATABASE HELPER TABLE TO GIVE DETAILS OF THE NED CONE
# SEARCHES PERFORMED
dataList = []
for i, coord in enumerate(self.coordinateList):
if isinstance(coord, str):
ra = coord.split(" ")[0]
dec = coord.split(" ")[1]
elif isinstance(coord, tuple) or isinstance(coord, list):
ra = coord[0]
dec = coord[1]
dataList.append(
{"raDeg": ra,
"decDeg": dec,
"arcsecRadius": self.radiusArcsec}
)
if len(dataList) == 0:
return None
# CREATE TABLE IF NOT EXIST
createStatement = """CREATE TABLE IF NOT EXISTS `tcs_helper_ned_query_history` (
`primaryId` bigint(20) NOT NULL AUTO_INCREMENT,
`raDeg` double DEFAULT NULL,
`decDeg` double DEFAULT NULL,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,
`updated` varchar(45) DEFAULT '0',
`arcsecRadius` int(11) DEFAULT NULL,
`dateQueried` datetime DEFAULT CURRENT_TIMESTAMP,
`htm16ID` bigint(20) DEFAULT NULL,
`htm13ID` int(11) DEFAULT NULL,
`htm10ID` int(11) DEFAULT NULL,
PRIMARY KEY (`primaryId`),
KEY `idx_htm16ID` (`htm16ID`),
KEY `dateQueried` (`dateQueried`),
KEY `dateHtm16` (`dateQueried`,`htm16ID`),
KEY `idx_htm10ID` (`htm10ID`),
KEY `idx_htm13ID` (`htm13ID`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
"""
writequery(
log=self.log,
sqlQuery=createStatement,
dbConn=self.cataloguesDbConn
)
# USE dbSettings TO ACTIVATE MULTIPROCESSING
insert_list_of_dictionaries_into_database_tables(
dbConn=self.cataloguesDbConn,
log=self.log,
dictList=dataList,
dbTableName="tcs_helper_ned_query_history",
uniqueKeyList=[],
dateModified=True,
batchSize=10000,
replace=True,
dbSettings=self.settings["database settings"][
"static catalogues"]
)
# INDEX THE TABLE FOR LATER SEARCHES
add_htm_ids_to_mysql_database_table(
raColName="raDeg",
declColName="decDeg",
tableName="tcs_helper_ned_query_history",
dbConn=self.cataloguesDbConn,
log=self.log,
primaryIdColumnName="primaryId"
)
self.log.debug('completed the ``_update_ned_query_history`` method')
return None |
python | def links(self) -> _Links:
"""All found links on page, in as–is form. Only works for Atom feeds."""
return list(set(x.text for x in self.xpath('//link'))) |
python | def start(self, proxy=None, cookie_db=None, disk_cache_dir=None,
disk_cache_size=None):
'''
Starts chrome/chromium process.
Args:
proxy: http proxy 'host:port' (default None)
cookie_db: raw bytes of chrome/chromium sqlite3 cookies database,
which, if supplied, will be written to
{chrome_user_data_dir}/Default/Cookies before running the
browser (default None)
disk_cache_dir: use directory for disk cache. The default location
is inside `self._home_tmpdir` (default None).
disk_cache_size: Forces the maximum disk space to be used by the disk
cache, in bytes. (default None)
Returns:
websocket url to chrome window with about:blank loaded
'''
# these can raise exceptions
self._home_tmpdir = tempfile.TemporaryDirectory()
self._chrome_user_data_dir = os.path.join(
self._home_tmpdir.name, 'chrome-user-data')
if cookie_db:
self._init_cookie_db(cookie_db)
self._shutdown.clear()
new_env = os.environ.copy()
new_env['HOME'] = self._home_tmpdir.name
chrome_args = [
self.chrome_exe,
'--remote-debugging-port=%s' % self.port,
'--use-mock-keychain', # mac thing
'--user-data-dir=%s' % self._chrome_user_data_dir,
'--disable-background-networking',
'--disable-renderer-backgrounding', '--disable-hang-monitor',
'--disable-background-timer-throttling', '--mute-audio',
'--disable-web-sockets',
'--window-size=1100,900', '--no-default-browser-check',
'--disable-first-run-ui', '--no-first-run',
'--homepage=about:blank', '--disable-direct-npapi-requests',
'--disable-web-security', '--disable-notifications',
'--disable-extensions', '--disable-save-password-bubble']
if disk_cache_dir:
chrome_args.append('--disk-cache-dir=%s' % disk_cache_dir)
if disk_cache_size:
chrome_args.append('--disk-cache-size=%s' % disk_cache_size)
if self.ignore_cert_errors:
chrome_args.append('--ignore-certificate-errors')
if proxy:
chrome_args.append('--proxy-server=%s' % proxy)
chrome_args.append('about:blank')
self.logger.info('running: %r', subprocess.list2cmdline(chrome_args))
# start_new_session - new process group so we can kill the whole group
self.chrome_process = subprocess.Popen(
chrome_args, env=new_env, start_new_session=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
self._out_reader_thread = threading.Thread(
target=self._read_stderr_stdout,
name='ChromeOutReaderThread:%s' % self.port, daemon=True)
self._out_reader_thread.start()
self.logger.info('chrome running, pid %s' % self.chrome_process.pid)
return self._websocket_url() |
python | def issue(self, issue_instance_id):
"""Select an issue.
Parameters:
issue_instance_id: int id of the issue instance to select
Note: We are selecting issue instances, even though the command is called
issue.
"""
with self.db.make_session() as session:
selected_issue = (
session.query(IssueInstance)
.filter(IssueInstance.id == issue_instance_id)
.scalar()
)
if selected_issue is None:
self.warning(
f"Issue {issue_instance_id} doesn't exist. "
"Type 'issues' for available issues."
)
return
self.sources = self._get_leaves_issue_instance(
session, issue_instance_id, SharedTextKind.SOURCE
)
self.sinks = self._get_leaves_issue_instance(
session, issue_instance_id, SharedTextKind.SINK
)
self.current_issue_instance_id = int(selected_issue.id)
self.current_frame_id = -1
self.current_trace_frame_index = 1 # first one after the source
print(f"Set issue to {issue_instance_id}.")
if int(selected_issue.run_id) != self.current_run_id:
self.current_run_id = int(selected_issue.run_id)
print(f"Set run to {self.current_run_id}.")
print()
self._generate_trace_from_issue()
self.show() |
python | def override(self, obj):
"""Overrides the plain fields of the dashboard."""
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field)) |
java | private int getColorDigit( int idx, CssFormatter formatter ) {
Expression expression = get( idx );
double d = expression.doubleValue( formatter );
if( expression.getDataType( formatter ) == PERCENT ) {
d *= 2.55;
}
return colorDigit(d);
} |
java | public static RepeatingView createFieldList(String id, Class<?> bean, Map<String, String> values) {
List<AttributeDefinition> attributes = MethodUtil.buildAttributesList(bean);
return createFieldList(id, attributes, values);
} |
python | def p_expression_uor(self, p):
'expression : OR expression %prec UOR'
p[0] = Uor(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
python | def validate(item, namespace='accounts', version=2, context=None):
"""Validate item against version schema.
Args:
item: data object
namespace: backend namespace
version: schema version
context: schema context object
"""
if namespace == 'accounts':
if version == 2:
schema = v2.AccountSchema(strict=True, context=context)
return schema.load(item).data
elif version == 1:
return v1.AccountSchema(strict=True).load(item).data
raise InvalidSWAGDataException('Schema version is not supported. Version: {}'.format(version))
raise InvalidSWAGDataException('Namespace not supported. Namespace: {}'.format(namespace)) |
python | def cmd(send, msg, args):
"""Microwaves something.
Syntax: {command} <level> <target>
"""
nick = args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
levels = {
1: 'Whirr...',
2: 'Vrrm...',
3: 'Zzzzhhhh...',
4: 'SHFRRRRM...',
5: 'GEEEEZZSH...',
6: 'PLAAAAIIID...',
7: 'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...',
8: 'Nuke',
9: 'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM',
10: 'ssh [email protected] rm -rf ~%s'
}
if not msg:
send('What to microwave?')
return
match = re.match('(-?[0-9]*) (.*)', msg)
if not match:
send('Power level?')
else:
level = int(match.group(1))
target = match.group(2)
if level > 10:
send('Aborting to prevent extinction of human race.')
return
if level < 1:
send('Anti-matter not yet implemented.')
return
if level > 7:
if not args['is_admin'](nick):
send("I'm sorry. Nukes are a admin-only feature")
return
elif msg == args['botnick']:
send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
else:
with args['handler'].data_lock:
if target not in args['handler'].channels[channel].users():
send("I'm sorry. Anonymous Nuking is not allowed")
return
msg = levels[1]
for i in range(2, level + 1):
if i < 8:
msg += ' ' + levels[i]
send(msg)
if level >= 8:
do_nuke(args['handler'].connection, nick, target, channel)
if level >= 9:
send(levels[9])
if level == 10:
send(levels[10] % target)
send('Ding, your %s is ready.' % target) |
python | def ebs_volume_exists(region, volume_id, access_key_id, secret_access_key):
""" finds out if a ebs volume exists """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
for vol in conn.get_all_volumes():
if vol.id == volume_id:
return True |
python | def pairedBEDIterator(inputStreams, mirror=False, mirrorScore=None,
ignoreStrand=False, ignoreScore=True, ignoreName=True,
sortedby=ITERATOR_SORTED_END, scoreType=float,
verbose=False):
"""
Iterate over multiple BED format files simultaneously and yield lists of
genomic intervals for each matching set of intervals found. By default,
regions which are not found in all files will be skipped (mirror = false).
Optionally (by setting mirror to true) if a file is missing an interval,
it can be added on-the-fly, and will have the same chrom, start and end and
name as in other files. The score will be taken from the first file in
inputStreams if mirrorScore is not set, otherwise that value will be used.
:param inputStreams: a list of input streams in BED format
:param mirror: if true, add missing elements so all streams contain the
same elements. Inserted elements will have the same
:param ignoreStrand: ignore strand when comparing elements for equality?
:param ignoreScore: ignore score when comparing elements for equality?
:param ignoreScore: ignore name when comparing elements for equality?
:param sortedby: must be set to one of the sorting orders for BED streams;
we require the streams to be sorted in some fashion.
:param scoreType: interpret scores as what type? Defaults to float, which
is generally the most flexible.
"""
# let's build our sorting order...
sortOrder = ["chrom"]
if sortedby == ITERATOR_SORTED_START:
sortOrder.append("start")
sortOrder.append("end")
elif sortedby == ITERATOR_SORTED_END:
sortOrder.append("end")
sortOrder.append("start")
if not ignoreStrand:
sortOrder.append("strand")
if not ignoreName:
sortOrder.append("name")
if not ignoreScore:
sortOrder.append("score")
keyFunc = attrgetter(*sortOrder)
def next_item(iterator):
""" little internal function to return the next item, or None """
try:
return iterator.next()
except StopIteration:
return None
bIterators = [BEDIterator(bfh, verbose=verbose,
sortedby=sortedby,
scoreType=scoreType) for bfh in inputStreams]
elements = [next_item(it) for it in bIterators]
while True:
assert(len(elements) >= 2)
if None not in elements and len(set([keyFunc(x) for x in elements])) == 1:
# All equal -- yield and move on for all streams
yield [e for e in elements]
elements = [next_item(it) for it in bIterators]
else:
# something wasn't equal.. find the smallest thing, it's about to drop
# out of range and will never have the chance to match anything again
minElement = min([x for x in elements if x is not None], key=keyFunc)
minIndices = [i for i in range(0, len(elements))
if elements[i] is not None and
keyFunc(elements[i]) == keyFunc(minElement)]
if mirror:
# mirror the min item for any streams in which it doesn't match
score = minElement.score if mirrorScore is None else mirrorScore
yield [elements[i] if i in minIndices
else GenomicInterval(minElement.chrom, minElement.start,
minElement.end, minElement.name,
score, minElement.strand,
scoreType=scoreType)
for i in range(0, len(elements))]
# move the smallest element onwards now, we're done with it
for index in minIndices:
elements[index] = next_item(bIterators[index])
# stop once all streams are exhausted
if reduce(lambda x, y: x and y, [e is None for e in elements]):
break |
java | public static List<UIParameter> getValidUIParameterChildren(
FacesContext facesContext, List<UIComponent> children,
boolean skipNullValue, boolean skipUnrendered)
{
return getValidUIParameterChildren(facesContext, children,
skipNullValue, skipUnrendered, true);
} |
python | def route_create(credential_file=None,
project_id=None,
name=None,
dest_range=None,
next_hop_instance=None,
instance_zone=None,
tags=None,
network=None,
priority=None
):
'''
Create a route to send traffic destined to the Internet through your
gateway instance
credential_file : string
File location of application default credential. For more information,
refer: https://developers.google.com/identity/protocols/application-default-credentials
project_id : string
Project ID where instance and network resides.
name : string
name of the route to create
next_hop_instance : string
the name of an instance that should handle traffic matching this route.
instance_zone : string
zone where instance("next_hop_instance") resides
network : string
Specifies the network to which the route will be applied.
dest_range : string
The destination range of outgoing packets that the route will apply to.
tags : list
(optional) Identifies the set of instances that this route will apply to.
priority : int
(optional) Specifies the priority of this route relative to other routes.
default=1000
CLI Example:
salt 'salt-master.novalocal' gcp.route_create
credential_file=/root/secret_key.json
project_id=cp100-170315
name=derby-db-route1
next_hop_instance=instance-1
instance_zone=us-central1-a
network=default
dest_range=0.0.0.0/0
tags=['no-ip']
priority=700
In above example, the instances which are having tag "no-ip" will route the
packet to instance "instance-1"(if packet is intended to other network)
'''
credentials = oauth2client.service_account.ServiceAccountCredentials.\
from_json_keyfile_name(credential_file)
service = googleapiclient.discovery.build('compute', 'v1',
credentials=credentials)
routes = service.routes()
routes_config = {
'name': six.text_type(name),
'network': _get_network(project_id, six.text_type(network),
service=service)['selfLink'],
'destRange': six.text_type(dest_range),
'nextHopInstance': _get_instance(project_id, instance_zone,
next_hop_instance,
service=service)['selfLink'],
'tags': tags,
'priority': priority
}
route_create_request = routes.insert(project=project_id,
body=routes_config)
return route_create_request.execute() |
python | def get_bits(block_representation, coin_symbol='btc', api_key=None):
'''
Takes a block_representation and returns the number of bits
'''
return get_block_overview(block_representation=block_representation,
coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits'] |
java | @NonNull
private ScrollListener createScrollViewScrollListener() {
return new ScrollListener() {
@Override
public void onScrolled(final boolean scrolledToTop, final boolean scrolledToBottom) {
adaptDividerVisibilities(scrolledToTop, scrolledToBottom, true);
}
};
} |
java | @Override
public SchemaManager getSchemaManager(Map<String, Object> puProperties)
{
if (schemaManager == null)
{
initializePropertyReader();
setExternalProperties(puProperties);
schemaManager = new CouchbaseSchemaManager(CouchbaseClientFactory.class.getName(), puProperties,
kunderaMetadata);
}
return schemaManager;
} |
python | def dump(self, tempy_tree_list, filename, pretty=False):
"""Dumps a Tempy object to a python file"""
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
'"filename" argument should have a .py extension, if given.'
)
if not filename.endswith(".py"):
filename += ".py"
with open(filename, "w") as f:
f.write(
"# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n"
)
for tempy_tree in tempy_tree_list:
f.write(tempy_tree.to_code(pretty=pretty))
return filename |
java | public static <T> Mono<T> illegalState(String format, Object... args) {
String message = String.format(format, args);
return Mono.error(new IllegalStateException(message));
} |
java | protected static void cloneInternal ( JAASAuthenticator to, JAASAuthenticator from ) {
Kerb5Authenticator.cloneInternal(to, from);
to.serviceName = from.serviceName;
to.configuration = from.configuration;
to.cachedSubject = from.cachedSubject;
} |
python | def expand(self):
"""
Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, each representing a single dimension
continuous {0<=x<=1, 2<=y<=3} -> continuous {0<=x<=1}, continuous {2<=y<=3}
"""
expanded_variables = []
for i in range(self.dimensionality):
one_d_variable = deepcopy(self)
one_d_variable.dimensionality = 1
if self.dimensionality > 1:
one_d_variable.name = '{}_{}'.format(self.name, i+1)
else:
one_d_variable.name = self.name
one_d_variable.dimensionality_in_model = 1
expanded_variables.append(one_d_variable)
return expanded_variables |
java | @XmlElementDecl(namespace = PROV_NS, name = "role")
public JAXBElement<Role> createRole(Role value) {
return new JAXBElement<Role>(_Role_QNAME, Role.class, null, value);
} |
python | def _ondim(self, dimension, valuestring):
"""Converts valuestring to int and assigns result to self.dim
If there is an error (such as an empty valuestring) or if
the value is < 1, the value 1 is assigned to self.dim
Parameters
----------
dimension: int
\tDimension that is to be updated. Must be in [1:4]
valuestring: string
\t A string that can be converted to an int
"""
try:
self.dimensions[dimension] = int(valuestring)
except ValueError:
self.dimensions[dimension] = 1
self.textctrls[dimension].SetValue(str(1))
if self.dimensions[dimension] < 1:
self.dimensions[dimension] = 1
self.textctrls[dimension].SetValue(str(1)) |
java | private void sendMessageToSelfAndDeferRetirement(ActiveInvokeContext<EhcacheEntityResponse> context, KeyBasedServerStoreOpMessage message, Chain newChain) {
try {
long clientId = context.getClientSource().toLong();
entityMessenger.messageSelfAndDeferRetirement(message, new PassiveReplicationMessage.ChainReplicationMessage(message.getKey(), newChain,
context.getCurrentTransactionId(), context.getOldestTransactionId(), clientId));
} catch (MessageCodecException e) {
throw new AssertionError("Codec error", e);
}
} |
python | def parse(cls, format):
"""
Parse a format string. Factory function for the Format class.
:param format: The format string to parse.
:returns: An instance of class Format.
"""
fmt = cls()
# Return an empty Format if format is empty
if not format:
return fmt
# Initialize the state for parsing
state = ParseState(fmt, format)
# Loop through the format string with a state-based parser
for idx, char in enumerate(format):
# Some characters get ignored
if state.check_ignore():
continue
if state == 'string':
if char == '%':
# Handle '%%'
if format[idx:idx + 2] == '%%':
# Add one % to the string context
state.add_text(idx + 1, idx + 2)
state.set_ignore(1)
else:
state.add_text(idx)
state.conversion(idx)
elif char == '\\':
state.add_text(idx)
state.escape(idx)
elif state == 'escape':
state.add_escape(idx + 1, char)
state.pop_state(idx + 1)
elif state == 'param':
if char == '}':
state.set_param(idx)
state.pop_state()
elif state == 'conv':
if char == ')':
state.set_conversion(idx)
state.pop_state() # now in 'conversion'
state.pop_state(idx + 1) # now in 'string'
else: # state == 'conversion'
if char in '<>':
# Allowed for Apache compatibility, but ignored
continue
elif char == '!':
state.set_reject()
continue
elif char == ',' and state.code_last:
# Syntactically allowed ','
continue
elif char.isdigit():
# True if the code is valid
if state.set_code(idx):
continue
elif char == '{' and state.param_begin is None:
state.param(idx + 1)
continue
elif char == '(' and state.conv_begin is None:
state.conv(idx + 1)
continue
# OK, we have a complete conversion
state.set_conversion(idx)
state.pop_state(idx + 1)
# Finish the parse and return the completed format
return state.end_state() |
java | public static void apply(Element element, int offset, Functions.Func callback) {
MaterialScrollfire scrollfire = new MaterialScrollfire();
scrollfire.setElement(element);
scrollfire.setCallback(callback);
scrollfire.setOffset(offset);
scrollfire.apply();
} |
python | def get_date_from_utterance(tokenized_utterance: List[Token],
year: int = 1993) -> List[datetime]:
"""
When the year is not explicitly mentioned in the utterance, the query assumes that
it is 1993 so we do the same here. If there is no mention of the month or day then
we do not return any dates from the utterance.
"""
dates = []
utterance = ' '.join([token.text for token in tokenized_utterance])
year_result = re.findall(r'199[0-4]', utterance)
if year_result:
year = int(year_result[0])
trigrams = ngrams([token.text for token in tokenized_utterance], 3)
for month, tens, digit in trigrams:
# This will match something like ``september twenty first``.
day = ' '.join([tens, digit])
if month in MONTH_NUMBERS and day in DAY_NUMBERS:
try:
dates.append(datetime(year, MONTH_NUMBERS[month], DAY_NUMBERS[day]))
except ValueError:
print('invalid month day')
bigrams = ngrams([token.text for token in tokenized_utterance], 2)
for month, day in bigrams:
if month in MONTH_NUMBERS and day in DAY_NUMBERS:
# This will match something like ``september first``.
try:
dates.append(datetime(year, MONTH_NUMBERS[month], DAY_NUMBERS[day]))
except ValueError:
print('invalid month day')
fivegrams = ngrams([token.text for token in tokenized_utterance], 5)
for tens, digit, _, year_match, month in fivegrams:
# This will match something like ``twenty first of 1993 july``.
day = ' '.join([tens, digit])
if month in MONTH_NUMBERS and day in DAY_NUMBERS and year_match.isdigit():
try:
dates.append(datetime(int(year_match), MONTH_NUMBERS[month], DAY_NUMBERS[day]))
except ValueError:
print('invalid month day')
if month in MONTH_NUMBERS and digit in DAY_NUMBERS and year_match.isdigit():
try:
dates.append(datetime(int(year_match), MONTH_NUMBERS[month], DAY_NUMBERS[digit]))
except ValueError:
print('invalid month day')
return dates |
java | public static String getName(String datatypeKey)
{
Datatype datatype = getDatatype(datatypeKey);
return datatype.getName();
} |
python | def receive_message(source, auth=None, timeout=0, debug=False):
"""Receive a single message from an AMQP endpoint.
:param source: The AMQP source endpoint to receive from.
:type source: str, bytes or ~uamqp.address.Source
:param auth: The authentication credentials for the endpoint.
This should be one of the subclasses of uamqp.authentication.AMQPAuth. Currently
this includes:
- uamqp.authentication.SASLAnonymous
- uamqp.authentication.SASLPlain
- uamqp.authentication.SASTokenAuth
If no authentication is supplied, SASLAnnoymous will be used by default.
:type auth: ~uamqp.authentication.common.AMQPAuth
:param timeout: The timeout in milliseconds after which to return None if no messages
are retrieved. If set to `0` (the default), the receiver will not timeout and
will continue to wait for messages until interrupted.
:param debug: Whether to turn on network trace logs. If `True`, trace logs
will be logged at INFO level. Default is `False`.
:type debug: bool
:rtype: ~uamqp.message.Message or None
"""
received = receive_messages(source, auth=auth, max_batch_size=1, timeout=timeout, debug=debug)
if received:
return received[0]
return None |
python | def has_missing_break(real_seg, pred_seg):
"""
Parameters
----------
real_seg : list of integers
The segmentation as it should be.
pred_seg : list of integers
The predicted segmentation.
Returns
-------
bool :
True, if strokes of two different symbols are put in the same symbol.
"""
for symbol_pred in pred_seg:
for symbol_real in real_seg:
if symbol_pred[0] in symbol_real:
for stroke in symbol_pred:
if stroke not in symbol_real:
return True
return False |
java | public void set(IntFloatSortedVector other) {
this.used = other.used;
this.indices = IntArrays.copyOf(other.indices);
this.values = FloatArrays.copyOf(other.values);
} |
java | Object convertArgument(String arg, Type paramType) throws IllegalArgumentException {
Object result = null;
if (null == arg || "null".equals(arg)) {
return result;
}
logger.debug("Try to convert {} : param = {} : {}", new Object[]{arg, paramType, paramType.getClass()});
try { // GenericArrayType, ParameterizedType, TypeVariable<D>, WildcardType, Class
if (ParameterizedType.class.isInstance(paramType)) {
JavaType javaType = getJavaType(paramType);
logger.debug("Try to convert '{}' to JavaType : '{}'", arg, paramType);
result = getObjectMapper().readValue(arg, javaType);
logger.debug("Conversion of '{}' to '{}' : OK", arg, paramType);
} else if (Class.class.isInstance(paramType)) {
Class cls = (Class) paramType;
logger.debug("Try to convert '{}' to Class '{}'", arg, paramType);
checkStringArgument(cls, arg);
result = getObjectMapper().readValue(arg, cls);
logger.debug("Conversion of '{}' to '{}' : OK", arg, paramType);
} else { // GenericArrayType, TypeVariable<D>, WildcardType
logger.warn("Conversion of '{}' to '{}' not yet supported", arg, paramType);
}
} catch (IOException ex) {
logger.debug("Conversion of '{}' to '{}' failed", arg, paramType);
throw new IllegalArgumentException(paramType.toString());
}
return result;
} |
python | def evalAsync(self, amplstatements, callback, **kwargs):
"""
Interpret the given AMPL statement asynchronously.
Args:
amplstatements: A collection of AMPL statements and declarations to
be passed to the interpreter.
callback: Callback to be executed when the statement has been
interpreted.
Raises:
RuntimeError: if the input is not a complete AMPL statement (e.g.
if it does not end with semicolon) or if the underlying
interpreter is not running.
"""
if self._langext is not None:
amplstatements = self._langext.translate(amplstatements, **kwargs)
def async_call():
self._lock.acquire()
try:
self._impl.eval(amplstatements)
self._errorhandler_wrapper.check()
except Exception:
self._lock.release()
raise
else:
self._lock.release()
callback.run()
Thread(target=async_call).start() |
python | def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""
return list(dict((val[key], val) for val in dlist).values()) |
python | def _psi(self,m):
"""\psi(m) = -\int_m^\infty d m^2 \rho(m^2)"""
return 2.*self.a2*(1./(1.+m/self.a)+numpy.log(m/(m+self.a))) |
python | def _parse(value, strict=True):
"""
Preliminary duration value parser
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)'
match = re.match(pattern, value)
if not match:
raise ValueError('Invalid duration value: %s' % value)
hours = safe_int(match.group('hours'))
minutes = safe_int(match.group('minutes'))
seconds = safe_int(match.group('seconds'))
check_tuple((hours, minutes, seconds,), strict)
return (hours, minutes, seconds,) |
java | public Observable<List<DatabaseInner>> listByServerAsync(String resourceGroupName, String serverName) {
return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<List<DatabaseInner>>, List<DatabaseInner>>() {
@Override
public List<DatabaseInner> call(ServiceResponse<List<DatabaseInner>> response) {
return response.body();
}
});
} |
java | public static Map orderByValue(Map unsortMap, Comparator... comparators) {
// Convert Map to List
List<Map.Entry> list = new LinkedList<>(unsortMap.entrySet());
// Sort list with comparator, to compare the Map values
Collections.sort(list, new Comparator<Map.Entry>() {
public int compare(Map.Entry o1, Map.Entry o2) {
if (comparators.length == 0) {
if (o1.getValue() instanceof Comparable/* && o2.getValue() instanceof Comparable*/) {
Comparable ov1 = (Comparable) o1.getValue()/*, ov2 = (Comparable)o2.getValue()*/;
return ov1.compareTo(o2.getValue());
} else {
throw new IllegalArgumentException(o1.getValue().getClass() + " 必须是comparable,否则无法进行比较排序");
}
} else {
return comparators[0].compare(o1.getValue(), o2.getValue());
}
}
});
// Convert sorted map back to a Map
Map sortedMap = new LinkedHashMap<String, Integer>();
for (Iterator<Map.Entry> it = list.iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
} |
java | @Override
public CreateReceiptRuleResult createReceiptRule(CreateReceiptRuleRequest request) {
request = beforeClientExecution(request);
return executeCreateReceiptRule(request);
} |
java | static MultiMap removeCookieHeaders(MultiMap headers) {
// We don't want to remove the JSESSION cookie.
String cookieHeader = headers.get(COOKIE);
if (cookieHeader != null) {
headers.remove(COOKIE);
Set<Cookie> nettyCookies = ServerCookieDecoder.STRICT.decode(cookieHeader);
for (Cookie cookie: nettyCookies) {
if (cookie.name().equals("JSESSIONID")) {
headers.add(COOKIE, ServerCookieEncoder.STRICT.encode(cookie));
break;
}
}
}
return headers;
} |
java | public void marshall(AttributeDefinition attributeDefinition, ProtocolMarshaller protocolMarshaller) {
if (attributeDefinition == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(attributeDefinition.getAttributeName(), ATTRIBUTENAME_BINDING);
protocolMarshaller.marshall(attributeDefinition.getAttributeType(), ATTRIBUTETYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public boolean isSubscriptionPreApprovalSupported() throws NotLoggedInException {
final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
return connection.hasFeature(SubscriptionPreApproval.ELEMENT, SubscriptionPreApproval.NAMESPACE);
} |
python | def _add_keyword(self, collection_id, name, doc, args):
"""Insert data into the keyword table
'args' should be a list, but since we can't store a list in an
sqlite database we'll make it json we can can convert it back
to a list later.
"""
argstring = json.dumps(args)
self.db.execute("""
INSERT INTO keyword_table
(collection_id, name, doc, args)
VALUES
(?,?,?,?)
""", (collection_id, name, doc, argstring)) |
java | public void setDiffuse(float red, float green, float blue){
diffuse[0] = red;
diffuse[1] = green;
diffuse[2] = blue;
Di = true;
} |
python | def get_service_name(*args):
'''
The Display Name is what is displayed in Windows when services.msc is
executed. Each Display Name has an associated Service Name which is the
actual name of the service. This function allows you to discover the
Service Name by returning a dictionary of Display Names and Service Names,
or filter by adding arguments of Display Names.
If no args are passed, return a dict of all services where the keys are the
service Display Names and the values are the Service Names.
If arguments are passed, create a dict of Display Names and Service Names
Returns:
dict: A dictionary of display names and service names
CLI Examples:
.. code-block:: bash
salt '*' service.get_service_name
salt '*' service.get_service_name 'Google Update Service (gupdate)' 'DHCP Client'
'''
raw_services = _get_services()
services = dict()
for raw_service in raw_services:
if args:
if raw_service['DisplayName'] in args or \
raw_service['ServiceName'] in args or \
raw_service['ServiceName'].lower() in args:
services[raw_service['DisplayName']] = raw_service['ServiceName']
else:
services[raw_service['DisplayName']] = raw_service['ServiceName']
return services |
python | def get_re_experiment(case, minor=1):
""" Returns an experiment that uses the Roth-Erev learning method.
"""
locAdj = "ac"
experimentation = 0.55
recency = 0.3
tau = 100.0
decay = 0.999
nStates = 3 # stateless RE?
Pd0 = get_pd_max(case, profile)
Pd_min = get_pd_min(case, profile)
market = pyreto.SmartMarket(case, priceCap=cap, decommit=decommit,
auctionType=auctionType,
locationalAdjustment=locAdj)
experiment = pyreto.continuous.MarketExperiment([], [], market)
portfolios, sync_cond = get_portfolios3()
for gidx in portfolios:
g = [case.generators[i] for i in gidx]
learner = VariantRothErev(experimentation, recency)
learner.explorer = BoltzmannExplorer(tau, decay)
task, agent = get_discrete_task_agent(g, market, nStates, nOffer,
markups, withholds, maxSteps, learner, Pd0, Pd_min)
print "ALL ACTIONS:", len(task.env._allActions) * nStates
experiment.tasks.append(task)
experiment.agents.append(agent)
passive = [case.generators[i] for i in sync_cond]
passive[0].p_min = 0.001 # Avoid invalid offer withholding.
passive[0].p_max = 0.002
task, agent = get_zero_task_agent(passive, market, 1, maxSteps)
experiment.tasks.append(task)
experiment.agents.append(agent)
return experiment |
java | public Observable<Void> beginCreateOrUpdateSecuritySettingsAsync(String deviceName, String resourceGroupName, AsymmetricEncryptedSecret deviceAdminPassword) {
return beginCreateOrUpdateSecuritySettingsWithServiceResponseAsync(deviceName, resourceGroupName, deviceAdminPassword).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} |
java | public void start(BundleContext context) throws Exception {
ClassServiceUtility.log(context, LogService.LOG_INFO, "Starting " + this.getClass().getName() + " Bundle");
this.context = context;
this.init(); // Setup the properties
String interfaceClassName = getInterfaceClassName();
this.setProperty(BundleConstants.ACTIVATOR, this.getClass().getName()); // In case I have to find this service by activator class
try {
context.addServiceListener(this, ClassServiceUtility.addToFilter((String)null, Constants.OBJECTCLASS, interfaceClassName));
} catch (InvalidSyntaxException e) {
e.printStackTrace();
}
if (service == null)
{
boolean allStarted = this.checkDependentServices(context);
if (allStarted)
{
service = this.startupService(context);
this.registerService(service);
}
}
} |
java | protected void handleConfigureResponseFailure(MemberState member, ConfigureRequest request, Throwable error) {
// Log the failed attempt to contact the member.
failAttempt(member, error);
} |
java | public static Map<String, Object> generateMap(InputStream inputStream) {
logger.trace("Converting XML document [{}]");
Map<String, Object> map = asMap(inputStream);
logger.trace("Generated JSON: {}", map);
return map;
} |
python | def simulate_roi(self, name=None, randomize=True, restore=False):
"""Generate a simulation of the ROI using the current best-fit model
and replace the data counts cube with this simulation. The
simulation is created by generating an array of Poisson random
numbers with expectation values drawn from the model cube of
the binned analysis instance. This function will update the
counts cube both in memory and in the source map file. The
counts cube can be restored to its original state by calling
this method with ``restore`` = True.
Parameters
----------
name : str
Name of the model component to be simulated. If None then
the whole ROI will be simulated.
restore : bool
Restore the data counts cube to its original state.
"""
self.logger.info('Simulating ROI')
self._fitcache = None
if restore:
self.logger.info('Restoring')
self._restore_counts_maps()
self.logger.info('Finished')
return
for c in self.components:
c.simulate_roi(name=name, clear=True, randomize=randomize)
if hasattr(self.like.components[0].logLike, 'setCountsMap'):
self._init_roi_model()
else:
self.write_xml('tmp')
self._like = SummedLikelihood()
for i, c in enumerate(self._components):
c._create_binned_analysis('tmp.xml')
self._like.addComponent(c.like)
self._init_roi_model()
self.load_xml('tmp')
self.logger.info('Finished') |
python | def setAttributesJson(self, attributesJson):
"""
Sets the attributes dictionary from a JSON string.
"""
try:
self._attributes = json.loads(attributesJson)
except:
raise exceptions.InvalidJsonException(attributesJson)
return self |
java | public static File[] listFiles(final File aDir, final FilenameFilter aFilter, final boolean aDeepListing,
final String... aIgnoreList) throws FileNotFoundException {
if (!aDir.exists()) {
throw new FileNotFoundException(aDir.getAbsolutePath());
}
if (aDir.isFile()) {
if (aFilter.accept(aDir.getParentFile(), aDir.getName())) {
return new File[] { aDir };
} else {
return new File[0];
}
}
if (!aDeepListing) {
return aDir.listFiles(aFilter);
} else {
final ArrayList<File> fileList = new ArrayList<>();
final String[] ignoreList;
if (aIgnoreList == null) {
ignoreList = new String[0];
} else {
ignoreList = aIgnoreList;
}
for (final File file : aDir.listFiles()) {
final String fileName = file.getName();
if (aFilter.accept(aDir, fileName)) {
LOGGER.debug(MessageCodes.UTIL_010, file);
fileList.add(file);
}
if (file.isDirectory() && Arrays.binarySearch(ignoreList, fileName) < 0) {
final File[] files;
LOGGER.debug(MessageCodes.UTIL_011, file);
files = listFiles(file, aFilter, aDeepListing);
fileList.addAll(Arrays.asList(files));
}
}
return fileList.toArray(new File[0]);
}
} |
java | public static boolean isAnonymousDiamond(JCTree tree) {
switch(tree.getTag()) {
case NEWCLASS: {
JCNewClass nc = (JCNewClass)tree;
return nc.def != null && isDiamond(nc.clazz);
}
case ANNOTATED_TYPE: return isAnonymousDiamond(((JCAnnotatedType)tree).underlyingType);
default: return false;
}
} |
python | def sys_mem_limit(self):
"""Determine the default memory limit for the current service unit."""
if platform.machine() in ['armv7l']:
_mem_limit = self.human_to_bytes('2700M') # experimentally determined
else:
# Limit for x86 based 32bit systems
_mem_limit = self.human_to_bytes('4G')
return _mem_limit |
java | public void dumpObjectMetaData() {
LOGGER.debug("dump class={}", className);
LOGGER.debug("----------------------------------------");
for (FieldMetaData md : fieldList) {
LOGGER.debug(md.toString());
}
} |
python | def tokenize(text, format=None):
"""
tokenize text for word segmentation
:param text: raw text input
:return: tokenize text
"""
text = Text(text)
text = text.replace("\t", " ")
tokens = re.findall(patterns, text)
tokens = [token[0] for token in tokens]
if format == "text":
return " ".join(tokens)
else:
return tokens |
python | def _update_secret(namespace, name, data, apiserver_url):
'''Replace secrets data by a new one'''
# Prepare URL
url = "{0}/api/v1/namespaces/{1}/secrets/{2}".format(apiserver_url,
namespace, name)
# Prepare data
data = [{"op": "replace", "path": "/data", "value": data}]
# Make request
ret = _kpatch(url, data)
if ret.get("status") == 404:
return "Node {0} doesn't exist".format(url)
return ret |
python | def items(self):
"""
:return: a list of name/value attribute pairs sorted by attribute name.
"""
sorted_keys = sorted(self.keys())
return [(k, self[k]) for k in sorted_keys] |
python | def guess_interval(nums, accuracy=0):
"""Given a seq of number, return the median, only calculate interval >= accuracy.
::
from torequests.utils import guess_interval
import random
seq = [random.randint(1, 100) for i in range(20)]
print(guess_interval(seq, 5))
# sorted_seq: [2, 10, 12, 19, 19, 29, 30, 32, 38, 40, 41, 54, 62, 69, 75, 79, 82, 88, 97, 99]
# diffs: [8, 7, 10, 6, 13, 8, 7, 6, 6, 9]
# median: 8
"""
if not nums:
return 0
nums = sorted([int(i) for i in nums])
if len(nums) == 1:
return nums[0]
diffs = [nums[i + 1] - nums[i] for i in range(len(nums) - 1)]
diffs = [item for item in diffs if item >= accuracy]
sorted_diff = sorted(diffs)
result = sorted_diff[len(diffs) // 2]
return result |
java | TextView generateSplit(int i) {
TextView split = new TextView(getContext());
int generateViewId = PinViewUtils.generateViewId();
split.setId(generateViewId);
setStylesSplit(split);
pinSplitsIds[i] = generateViewId;
return split;
} |
python | def to_edgelist(self):
"""
Export the current transforms as a list of edge tuples, with
each tuple having the format:
(node_a, node_b, {metadata})
Returns
-------
edgelist: (n,) list of tuples
"""
# save cleaned edges
export = []
# loop through (node, node, edge attributes)
for edge in nx.to_edgelist(self.transforms):
a, b, c = edge
# geometry is a node property but save it to the
# edge so we don't need two dictionaries
if 'geometry' in self.transforms.node[b]:
c['geometry'] = self.transforms.node[b]['geometry']
# save the matrix as a float list
c['matrix'] = np.asanyarray(c['matrix'], dtype=np.float64).tolist()
export.append((a, b, c))
return export |
java | public Material addVoice(InputStream inputStream, String fileName) {
return upload(MediaType.voice, inputStream, fileName);
} |
python | def set_change(name, change):
'''
Sets the time at which the password expires (in seconds since the UNIX
epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on
FreeBSD.
A value of ``0`` sets the password to never expire.
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 1419980400
'''
pre_info = info(name)
if change == pre_info['change']:
return True
if __grains__['kernel'] == 'FreeBSD':
cmd = ['pw', 'user', 'mod', name, '-f', change]
else:
cmd = ['usermod', '-f', change, name]
__salt__['cmd.run'](cmd, python_shell=False)
post_info = info(name)
if post_info['change'] != pre_info['change']:
return post_info['change'] == change |
java | public final static PipeConnectionEvent build(AbstractPipe source, EventType type, IProvider provider, Map<String, Object> paramMap) {
return new PipeConnectionEvent(source, type, provider, paramMap);
} |
java | public static MenuItem newMenuItem(final IModel<String> labelModel)
{
final MenuItem menuItem = new MenuItem(labelModel);
return menuItem;
} |
java | public static <T extends Comparable<T>> int compare(Iterable<T> collection1, Iterable<T> collection2) {
return compare(collection1.iterator(), collection2.iterator());
} |
java | @Deprecated
@JsonProperty
public List<Object> getLiteralArguments()
{
List<Object> result = new ArrayList<>();
for (ClientTypeSignatureParameter argument : arguments) {
switch (argument.getKind()) {
case NAMED_TYPE:
result.add(argument.getNamedTypeSignature().getName());
break;
default:
return new ArrayList<>();
}
}
return result;
} |
python | def get_instances(self):
"""Returns a list of the instances of all the configured nodes.
"""
return [c.get('instance') for c in self.runtime._nodes.values()
if c.get('instance')] |
java | @Override
public EClass getIfcGeographicElementType() {
if (ifcGeographicElementTypeEClass == null) {
ifcGeographicElementTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(301);
}
return ifcGeographicElementTypeEClass;
} |
python | def location_path(cls, project, location):
"""Return a fully-qualified location string."""
return google.api_core.path_template.expand(
"projects/{project}/locations/{location}",
project=project,
location=location,
) |
java | public <T, E extends Exception> Nullable<T> mapIfNotEmpty(Try.Function<? super String, T, E> mapper) throws E {
N.checkArgNotNull(mapper);
return buffer == null ? Nullable.<T> empty() : Nullable.of(mapper.apply(toString()));
} |
python | def set_maintenance_mode(value):
"""
Set maintenance_mode state to state file.
"""
# If maintenance mode is defined in settings, it can't be changed.
if settings.MAINTENANCE_MODE is not None:
raise ImproperlyConfigured(
'Maintenance mode cannot be set dynamically '
'if defined in settings.')
if not isinstance(value, bool):
raise TypeError('value argument type is not boolean')
backend = get_maintenance_mode_backend()
backend.set_value(value) |
python | def load_stylesheet(pyside=True):
"""
Loads the stylesheet. Takes care of importing the rc module.
:param pyside: True to load the pyside rc file, False to load the PyQt rc file
:return the stylesheet string
"""
# Smart import of the rc file
if pyside:
import qdarkstyle.pyside_style_rc
else:
import qdarkstyle.pyqt_style_rc
# Load the stylesheet content from resources
if not pyside:
from PyQt4.QtCore import QFile, QTextStream
else:
from PySide.QtCore import QFile, QTextStream
f = QFile(":qdarkstyle/style.qss")
if not f.exists():
_logger().error("Unable to load stylesheet, file not found in "
"resources")
return ""
else:
f.open(QFile.ReadOnly | QFile.Text)
ts = QTextStream(f)
stylesheet = ts.readAll()
if platform.system().lower() == 'darwin': # see issue #12 on github
mac_fix = '''
QDockWidget::title
{
background-color: #31363b;
text-align: center;
height: 12px;
}
'''
stylesheet += mac_fix
return stylesheet |
java | public void write(Bean bean, OutputStream output) throws IOException {
write(bean, true, output);
} |
java | public void marshall(InstanceHealthSummary instanceHealthSummary, ProtocolMarshaller protocolMarshaller) {
if (instanceHealthSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(instanceHealthSummary.getInstanceName(), INSTANCENAME_BINDING);
protocolMarshaller.marshall(instanceHealthSummary.getInstanceHealth(), INSTANCEHEALTH_BINDING);
protocolMarshaller.marshall(instanceHealthSummary.getInstanceHealthReason(), INSTANCEHEALTHREASON_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public List<WsByteBuffer> compress(WsByteBuffer buffer) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "compress, input=" + buffer);
}
List<WsByteBuffer> list = new LinkedList<WsByteBuffer>();
list = compress(list, buffer);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "compress, return list of size " + list.size());
}
return list;
} |
python | def _validate_datetime_from_to(cls, start, end):
"""
validate from-to
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:return: None or MlbAmException
"""
if not start <= end:
raise MlbAmBadParameter("not Start Day({start}) <= End Day({end})".format(start=start, end=end)) |
java | public void setText(String strText)
{
if ((strText == null) || (strText.length() == 0))
{
if (!m_bInFocus)
{
strText = m_strDescription;
this.changeFont(true);
}
}
else
this.changeFont(false);
super.setText(strText);
} |
java | private void computeScales() {
int width = getWidth();
int height = getHeight();
width = (width-borderSize)/2;
// compute the scale factor for each image
scaleLeft = scaleRight = 1;
if( leftImage.getWidth() > width || leftImage.getHeight() > height ) {
double scaleX = (double)width/(double)leftImage.getWidth();
double scaleY = (double)height/(double)leftImage.getHeight();
scaleLeft = Math.min(scaleX,scaleY);
}
if( rightImage.getWidth() > width || rightImage.getHeight() > height ) {
double scaleX = (double)width/(double)rightImage.getWidth();
double scaleY = (double)height/(double)rightImage.getHeight();
scaleRight = Math.min(scaleX,scaleY);
}
} |
python | def randomize(self, rand_gen=None, *args, **kwargs):
"""
Randomize the model.
Make this draw from the prior if one exists, else draw from given random generator
:param rand_gen: np random number generator which takes args and kwargs
:param flaot loc: loc parameter for random number generator
:param float scale: scale parameter for random number generator
:param args, kwargs: will be passed through to random number generator
"""
if rand_gen is None:
rand_gen = np.random.normal
# first take care of all parameters (from N(0,1))
x = rand_gen(size=self._size_transformed(), *args, **kwargs)
updates = self.update_model()
self.update_model(False) # Switch off the updates
self.optimizer_array = x # makes sure all of the tied parameters get the same init (since there's only one prior object...)
# now draw from prior where possible
x = self.param_array.copy()
[np.put(x, ind, p.rvs(ind.size)) for p, ind in self.priors.items() if not p is None]
unfixlist = np.ones((self.size,),dtype=np.bool)
from paramz.transformations import __fixed__
unfixlist[self.constraints[__fixed__]] = False
self.param_array.flat[unfixlist] = x.view(np.ndarray).ravel()[unfixlist]
self.update_model(updates) |
java | public static List<ColumnMetaData> buildColumns(final String colsAsCsv) {
final List<ColumnMetaData> listCol = new ArrayList<>();
buildColumns(listCol, colsAsCsv);
return listCol;
} |
java | @Override
public Place getGeoDetails(String placeId) throws TwitterException {
return factory.createPlace(get(conf.getRestBaseURL() + "geo/id/" + placeId
+ ".json"));
} |
python | def _parse_processor_embedded_health(self, data):
"""Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: processor details like cpu arch and number of cpus.
"""
processor = self.get_value_as_list((data['GET_EMBEDDED_HEALTH_DATA']
['PROCESSORS']), 'PROCESSOR')
if processor is None:
msg = "Unable to get cpu data. Error: Data missing"
raise exception.IloError(msg)
cpus = 0
for proc in processor:
for val in proc.values():
processor_detail = val['VALUE']
proc_core_threads = processor_detail.split('; ')
for x in proc_core_threads:
if "thread" in x:
v = x.split()
try:
cpus = cpus + int(v[0])
except ValueError:
msg = ("Unable to get cpu data. "
"The Value %s returned couldn't be "
"manipulated to get number of "
"actual processors" % processor_detail)
raise exception.IloError(msg)
cpu_arch = 'x86_64'
return cpus, cpu_arch |
java | public static void setThreadInstance(Application application) {
if (instance == null) {
instance = new ThreadLocalApplication();
} else if (!(instance instanceof ThreadLocalApplication)) {
throw new IllegalStateException();
}
((ThreadLocalApplication) instance).setCurrentApplication(application);
} |
java | public final void setAxisAngle(Vector3D axis, double angle) {
setAxisAngle(axis.getX(), axis.getY(), axis.getZ(), angle);
} |
python | def get_all_resources(datasets):
# type: (List['Dataset']) -> List[hdx.data.resource.Resource]
"""Get all resources from a list of datasets (such as returned by search)
Args:
datasets (List[Dataset]): list of datasets
Returns:
List[hdx.data.resource.Resource]: list of resources within those datasets
"""
resources = []
for dataset in datasets:
for resource in dataset.get_resources():
resources.append(resource)
return resources |
java | public void setRootComponent(final MvcComponent component) {
if (uiThreadRunner.isOnUiThread()) {
try {
graph.setRootComponent(component);
} catch (Graph.IllegalRootComponentException e) {
throw new MvcGraphException(e.getMessage(), e);
}
} else {
uiThreadRunner.post(new Runnable() {
@Override
public void run() {
try {
graph.setRootComponent(component);
} catch (Graph.IllegalRootComponentException e) {
throw new MvcGraphException(e.getMessage(), e);
}
}
});
}
} |
python | def child(self, subkey):
"""
Retrieves a subkey for this Registry key, given its name.
@type subkey: str
@param subkey: Name of the subkey.
@rtype: L{RegistryKey}
@return: Subkey.
"""
path = self._path + '\\' + subkey
handle = win32.RegOpenKey(self.handle, subkey)
return RegistryKey(path, handle) |
java | public static List<InetSocketAddress> getMasterRpcAddresses(AlluxioConfiguration conf) {
// First check whether rpc addresses are explicitly configured.
if (conf.isSet(PropertyKey.MASTER_RPC_ADDRESSES)) {
return parseInetSocketAddresses(conf.getList(PropertyKey.MASTER_RPC_ADDRESSES, ","));
}
// Fall back on server-side journal configuration.
int rpcPort = NetworkAddressUtils.getPort(NetworkAddressUtils.ServiceType.MASTER_RPC, conf);
return overridePort(getEmbeddedJournalAddresses(conf, ServiceType.MASTER_RAFT), rpcPort);
} |
python | def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.