language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def info(self, server_id):
"""return dicionary object with info about server
Args:
server_id - server identity
"""
result = self._storage[server_id].info()
result['id'] = server_id
return result |
python | def execute(self, eopatch):
"""
Add requested feature to this existing EOPatch.
"""
data_arr = eopatch[FeatureType.MASK]['IS_DATA']
_, height, width, _ = data_arr.shape
request = self._get_wms_request(eopatch.bbox, width, height)
request_data, = np.asarray(request.get_data())
if isinstance(self.raster_value, dict):
raster = self._map_from_multiclass(eopatch, (height, width), request_data)
elif isinstance(self.raster_value, (int, float)):
raster = self._map_from_binaries(eopatch, (height, width), request_data)
else:
raise ValueError("Unsupported raster value type")
if self.feature_type is FeatureType.MASK_TIMELESS and raster.ndim == 2:
raster = raster[..., np.newaxis]
eopatch[self.feature_type][self.feature_name] = raster
return eopatch |
python | def copy(self):
"""Return a shallow copy of the sorted dictionary."""
return self.__class__(self._key, self._load, self._iteritems()) |
java | public Document cmisDocument( CmisObject cmisObject ) {
org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)cmisObject;
DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId()));
ObjectType objectType = cmisObject.getType();
if (objectType.isBaseType()) {
writer.setPrimaryType(NodeType.NT_FILE);
} else {
writer.setPrimaryType(objectType.getId());
}
List<Folder> parents = doc.getParents();
ArrayList<String> parentIds = new ArrayList<String>();
for (Folder f : parents) {
parentIds.add(ObjectId.toString(ObjectId.Type.OBJECT, f.getId()));
}
writer.setParents(parentIds);
writer.addMixinType(NodeType.MIX_REFERENCEABLE);
writer.addMixinType(NodeType.MIX_LAST_MODIFIED);
// document specific property conversation
cmisProperties(doc, writer);
writer.addChild(ObjectId.toString(ObjectId.Type.CONTENT, doc.getId()), JcrConstants.JCR_CONTENT);
writer.addMixinType("mode:accessControllable");
writer.addChild(ObjectId.toString(ObjectId.Type.ACL, cmisObject.getId()), "mode:acl");
return writer.document();
} |
python | def square(m, eff_max,c,m0,sigma,m1=21):
"""
eff_max: Maximum of the efficiency function (peak efficiency)
c: shape of the drop-off in the efficiency at bright end
m0: transition to tappering at faint magnitudes
sigma: width of the transition in efficeincy
m1: magnitude at which peak efficeincy occurs
square(m) = (eff_max-c*(m-21)**2)/(1+exp((m-M_0)/sig))
"""
return (eff_max-c*(m-21)**2)/(1+numpy.exp((m-m0)/sigma)) |
java | public ControllerRoute withBasicAuthentication(String username, String password) {
Objects.requireNonNull(username, Required.USERNAME.toString());
Objects.requireNonNull(password, Required.PASSWORD.toString());
this.username = username;
this.password = password;
return this;
} |
python | def delete_cookie(self, key, path='/', domain=None):
"""Delete a cookie (by setting it to a blank value).
The path and domain values must match that of the original cookie.
"""
self.set_cookie(key, value='', max_age=0, path=path, domain=domain,
expires=datetime.utcfromtimestamp(0)) |
java | @Override
public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) {
return AVRO_FLATTENER.flatten(inputSchema, false);
} |
java | private void launchMyRichClient() {
if (startupContext == null) {
displaySplashScreen(rootApplicationContext);
}
final Application application;
try {
application = rootApplicationContext.getBean(Application.class);
}
catch (NoSuchBeanDefinitionException e) {
throw new IllegalArgumentException(
"A single bean definition of type "
+ Application.class.getName()
+ " must be defined in the main application context",
e);
}
try {
// To avoid deadlocks when events fire during initialization of some swing components
// Possible to do: in theory not a single Swing component should be created (=modified) in the launcher thread...
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
application.start();
}
});
}
catch (InterruptedException e) {
logger.warn("Application start interrupted", e);
}
catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw new IllegalStateException("Application start thrown an exception: " + cause.getMessage(), cause);
}
logger.debug("Launcher thread exiting...");
} |
java | @Override
public ProtocolDef protocol(String type) {
return new ProtocolDefImpl(
getDescriptorName(),
getRootNode(),
container,
container.getOrCreate("protocol@type=" + type));
} |
python | def remove_indicator(self, nid, prune=False):
"""
Removes a Indicator or IndicatorItem node from the IOC. By default,
if nodes are removed, any children nodes are inherited by the removed
node. It has the ability to delete all children Indicator and
IndicatorItem nodes underneath an Indicator node if the 'prune'
argument is set.
This will not remove the top level Indicator node from an IOC.
If the id value has been reused within the IOC, this will remove the
first node which contains the id value.
This also removes any parameters associated with any nodes that are
removed.
:param nid: The Indicator/@id or IndicatorItem/@id value indicating a specific node to remove.
:param prune: Remove all children of the deleted node. If a Indicator node is removed and prune is set to
False, the children nodes will be promoted to be children of the removed nodes' parent.
:return: True if nodes are removed, False otherwise.
"""
try:
node_to_remove = self.top_level_indicator.xpath(
'//IndicatorItem[@id="{}"]|//Indicator[@id="{}"]'.format(str(nid), str(nid)))[0]
except IndexError:
log.exception('Node [{}] not present'.format(nid))
return False
if node_to_remove.tag == 'IndicatorItem':
node_to_remove.getparent().remove(node_to_remove)
self.remove_parameter(ref_id=nid)
return True
elif node_to_remove.tag == 'Indicator':
if node_to_remove == self.top_level_indicator:
raise IOCParseError('Cannot remove the top level indicator')
if prune:
pruned_ids = node_to_remove.xpath('.//@id')
node_to_remove.getparent().remove(node_to_remove)
for pruned_id in pruned_ids:
self.remove_parameter(ref_id=pruned_id)
else:
for child_node in node_to_remove.getchildren():
node_to_remove.getparent().append(child_node)
node_to_remove.getparent().remove(node_to_remove)
self.remove_parameter(ref_id=nid)
return True
else:
raise IOCParseError(
'Bad tag found. Expected "IndicatorItem" or "Indicator", got [[}]'.format(node_to_remove.tag)) |
python | def writeRunSetInfoToLog(self, runSet):
"""
This method writes the information about a run set into the txt_file.
"""
runSetInfo = "\n\n"
if runSet.name:
runSetInfo += runSet.name + "\n"
runSetInfo += "Run set {0} of {1} with options '{2}' and propertyfile '{3}'\n\n".format(
runSet.index, len(self.benchmark.run_sets),
" ".join(runSet.options),
runSet.propertyfile)
titleLine = self.create_output_line(runSet, "inputfile", "status", "cpu time",
"wall time", "host", self.benchmark.columns, True)
runSet.simpleLine = "-" * (len(titleLine))
runSetInfo += titleLine + "\n" + runSet.simpleLine + "\n"
# write into txt_file
self.txt_file.append(runSetInfo) |
java | private EmptyStatementTree parseEmptyStatement() {
SourcePosition start = getTreeStartLocation();
eat(TokenType.SEMI_COLON);
return new EmptyStatementTree(getTreeLocation(start));
} |
java | public static long count_filtered(nitro_service service, String sitepath, String filter) throws Exception{
wisite_translationinternalip_binding obj = new wisite_translationinternalip_binding();
obj.set_sitepath(sitepath);
options option = new options();
option.set_count(true);
option.set_filter(filter);
wisite_translationinternalip_binding[] response = (wisite_translationinternalip_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
} |
java | public String findPrefix(String uri){
if(uri==null)
uri = "";
String prefix = getPrefix(uri);
if(prefix==null){
String defaultURI = getURI("");
if(defaultURI==null)
defaultURI = "";
if(Util.equals(uri, defaultURI))
prefix = "";
}
return prefix;
} |
java | @Deprecated
public Redemptions getCouponRedemptionsByInvoice(final Integer invoiceNumber, final QueryParams params) {
return getCouponRedemptionsByInvoice(invoiceNumber.toString(), params);
} |
java | @Override
public DataResponse<Team> getTeam(ObjectId componentId,
String teamId) {
Component component = componentRepository.findOne(componentId);
CollectorItem item = component.getCollectorItems()
.get(CollectorType.AgileTool).get(0);
// Get one scope by Id
Team team = teamRepository.findByTeamId(teamId);
Collector collector = collectorRepository
.findOne(item.getCollectorId());
return new DataResponse<>(team, collector.getLastExecuted());
} |
java | public int getHTTPStatus() throws InterruptedException, BOSHException {
if (toThrow != null) {
throw(toThrow);
}
lock.lock();
try {
if (!sent) {
awaitResponse();
}
} finally {
lock.unlock();
}
return statusCode;
} |
python | def run_output(self):
"""Output finalized data"""
for f in logdissect.output.__formats__:
ouroutput = self.output_modules[f]
ouroutput.write_output(self.data_set['finalized_data'],
args=self.args)
del(ouroutput)
# Output to terminal if silent mode is not set:
if not self.args.silentmode:
if self.args.verbosemode:
print('\n==== ++++ ==== Output: ==== ++++ ====\n')
for line in self.data_set['finalized_data']['entries']:
print(line['raw_text']) |
python | def _integrateOrbit_dxdv(vxvv,dxdv,pot,t,method,rectIn,rectOut):
"""
NAME:
_integrateOrbit_dxdv
PURPOSE:
integrate an orbit and area of phase space in a Phi(R) potential
in the (R,phi)-plane
INPUT:
vxvv - array with the initial conditions stacked like
[R,vR,vT,phi]; vR outward!
dxdv - difference to integrate [dR,dvR,dvT,dphi]
pot - Potential instance
t - list of times at which to output (0 has to be in this!)
method - 'odeint' or 'leapfrog'
rectIn= (False) if True, input dxdv is in rectangular coordinates
rectOut= (False) if True, output dxdv (that in orbit_dxdv) is in rectangular coordinates
OUTPUT:
[:,8] array of [R,vR,vT,phi,dR,dvR,dvT,dphi] at each t
error message from integrator
HISTORY:
2010-10-17 - Written - Bovy (IAS)
"""
#First check that the potential has C
if '_c' in method:
allHasC= _check_c(pot) and _check_c(pot,dxdv=True)
if not ext_loaded or \
(not allHasC and not 'leapfrog' in method and not 'symplec' in method):
method= 'odeint'
if not ext_loaded: # pragma: no cover
warnings.warn("Using odeint because C extension not loaded",galpyWarning)
else:
warnings.warn("Using odeint because not all used potential have adequate C implementations to integrate phase-space volumes",galpyWarning)
#go to the rectangular frame
this_vxvv= nu.array([vxvv[0]*nu.cos(vxvv[3]),
vxvv[0]*nu.sin(vxvv[3]),
vxvv[1]*nu.cos(vxvv[3])-vxvv[2]*nu.sin(vxvv[3]),
vxvv[2]*nu.cos(vxvv[3])+vxvv[1]*nu.sin(vxvv[3])])
if not rectIn:
this_dxdv= nu.array([nu.cos(vxvv[3])*dxdv[0]
-vxvv[0]*nu.sin(vxvv[3])*dxdv[3],
nu.sin(vxvv[3])*dxdv[0]
+vxvv[0]*nu.cos(vxvv[3])*dxdv[3],
-(vxvv[1]*nu.sin(vxvv[3])
+vxvv[2]*nu.cos(vxvv[3]))*dxdv[3]
+nu.cos(vxvv[3])*dxdv[1]-nu.sin(vxvv[3])*dxdv[2],
(vxvv[1]*nu.cos(vxvv[3])
-vxvv[2]*nu.sin(vxvv[3]))*dxdv[3]
+nu.sin(vxvv[3])*dxdv[1]+nu.cos(vxvv[3])*dxdv[2]])
else:
this_dxdv= dxdv
if 'leapfrog' in method.lower() or 'symplec' in method.lower():
raise TypeError('Symplectic integration for phase-space volume is not possible')
elif ext_loaded and \
(method.lower() == 'rk4_c' or method.lower() == 'rk6_c' \
or method.lower() == 'dopr54_c' or method.lower() == 'dop853_c'):
warnings.warn("Using C implementation to integrate orbits",galpyWarningVerbose)
#integrate
tmp_out, msg= integratePlanarOrbit_dxdv_c(pot,this_vxvv,this_dxdv,
t,method)
elif method.lower() == 'odeint' or not ext_loaded or method.lower() == 'dop853':
init= [this_vxvv[0],this_vxvv[1],this_vxvv[2],this_vxvv[3],
this_dxdv[0],this_dxdv[1],this_dxdv[2],this_dxdv[3]]
#integrate
if method.lower() == "dop853":
tmp_out = dop853(_EOM_dxdv, init, t, args=(pot,))
else:
tmp_out= integrate.odeint(_EOM_dxdv,init,t,args=(pot,),
rtol=10.**-8.)#,mxstep=100000000)
msg= 0
else:
raise NotImplementedError("requested integration method does not exist")
#go back to the cylindrical frame
R= nu.sqrt(tmp_out[:,0]**2.+tmp_out[:,1]**2.)
phi= nu.arccos(tmp_out[:,0]/R)
phi[(tmp_out[:,1] < 0.)]= 2.*nu.pi-phi[(tmp_out[:,1] < 0.)]
vR= tmp_out[:,2]*nu.cos(phi)+tmp_out[:,3]*nu.sin(phi)
vT= tmp_out[:,3]*nu.cos(phi)-tmp_out[:,2]*nu.sin(phi)
cp= nu.cos(phi)
sp= nu.sin(phi)
dR= cp*tmp_out[:,4]+sp*tmp_out[:,5]
dphi= (cp*tmp_out[:,5]-sp*tmp_out[:,4])/R
dvR= cp*tmp_out[:,6]+sp*tmp_out[:,7]+vT*dphi
dvT= cp*tmp_out[:,7]-sp*tmp_out[:,6]-vR*dphi
out= nu.zeros((len(t),8))
out[:,0]= R
out[:,1]= vR
out[:,2]= vT
out[:,3]= phi
if rectOut:
out[:,4:]= tmp_out[:,4:]
else:
out[:,4]= dR
out[:,7]= dphi
out[:,5]= dvR
out[:,6]= dvT
_parse_warnmessage(msg)
return (out,msg) |
python | def __gen_struct_anno_files(self, top_level_layer):
"""
A struct annotation file contains node (struct) attributes (of
non-token nodes). It is e.g. used to annotate the type of a syntactic
category (NP, VP etc.).
See also: __gen_hierarchy_file()
"""
paula_id = '{0}.{1}.{2}_{3}_struct'.format(top_level_layer,
self.corpus_name, self.name,
top_level_layer)
E, tree = gen_paula_etree(paula_id)
base_paula_id = self.paulamap['hierarchy'][top_level_layer]
mflist = E('multiFeatList',
{XMLBASE: base_paula_id+'.xml'})
for node_id in select_nodes_by_layer(self.dg, top_level_layer):
if not istoken(self.dg, node_id):
mfeat = E('multiFeat',
{XLINKHREF: '#{0}'.format(node_id)})
node_dict = self.dg.node[node_id]
for attr in node_dict:
if attr not in IGNORED_NODE_ATTRIBS:
mfeat.append(
E('feat',
{'name': attr, 'value': node_dict[attr]}))
if self.human_readable: # adds node label as a <!--comment-->
mfeat.append(Comment(node_dict.get('label')))
mflist.append(mfeat)
tree.append(mflist)
self.files[paula_id] = tree
self.file2dtd[paula_id] = PaulaDTDs.multifeat
return paula_id |
python | def _ExtractYahooSearchQuery(self, url):
"""Extracts a search query from a Yahoo search URL.
Examples:
https://search.yahoo.com/search?p=query
https://search.yahoo.com/search;?p=query
Args:
url (str): URL.
Returns:
str: search query or None if no query was found.
"""
if 'p=' not in url:
return None
_, _, line = url.partition('p=')
before_and, _, _ = line.partition('&')
if not before_and:
return None
yahoo_search_url = before_and.split()[0]
return yahoo_search_url.replace('+', ' ') |
python | def init_duts(self, args): # pylint: disable=too-many-locals,too-many-branches
"""
Initializes duts of different types based on configuration provided by AllocationContext.
Able to do the initialization of duts in parallel, if --parallel_flash was provided.
:param args: Argument Namespace object
:return: list of initialized duts.
"""
# TODO: Split into smaller chunks to reduce complexity.
threads = []
abort_queue = Queue()
def thread_wrapper(*thread_args, **thread_kwargs):
"""
Run initialization function for dut
:param thread_args: arguments to pass to the function
:param thread_kwargs: keyword arguments, (func: callable, abort_queue: Queue)
:return: Result of func(*thread_args)
"""
# pylint: disable=broad-except
try:
return thread_kwargs["func"](*thread_args)
except Exception as error:
thread_kwargs["abort_queue"].put((thread_args[2], error))
for index, dut_conf in enumerate(self._allocation_contexts):
dut_type = dut_conf.get("type")
func = self.get_dut_init_function(dut_type)
if func is None:
continue
threads.append(((self, dut_conf.get_alloc_data().get_requirements(), index + 1, args),
{"func": func, "abort_queue": abort_queue}))
try:
thread_limit = len(threads) if args.parallel_flash else 1
pool = ThreadPool(thread_limit)
async_results = [pool.apply_async(func=thread_wrapper,
args=t[0], kwds=t[1])
for t in threads]
# Wait for resources to be ready.
[res.get() for res in async_results] # pylint: disable=expression-not-assigned
pool.close()
pool.join()
if not abort_queue.empty():
msg = "Dut Initialization failed, reason(s):"
while not abort_queue.empty():
dut_index, error = abort_queue.get()
msg = "{}\nDUT index {} - {}".format(msg, dut_index, error)
raise AllocationError(msg)
# Sort duts to same order as in dut_conf_list
self.duts.sort(key=lambda d: d.index)
self.dutinformations.sort(key=lambda d: d.index)
except KeyboardInterrupt:
msg = "Received keyboard interrupt, waiting for flashing to finish"
self.logger.info(msg)
for dut in self.duts:
dut.close_dut(False)
dut.close_connection()
if hasattr(dut, "release"):
dut.release()
dut = None
raise
except RuntimeError:
self.logger.exception("RuntimeError during flashing")
# ValueError is raised if ThreadPool is tried to initiate with
# zero threads.
except ValueError:
self.logger.exception("No devices allocated")
raise AllocationError("Dut Initialization failed!")
except (DutConnectionError, TypeError):
for dut in self.duts:
if hasattr(dut, "release"):
dut.release()
raise AllocationError("Dut Initialization failed!")
finally:
if pool:
pool.close()
pool.join()
self.logger.debug("Allocated following duts:")
for dut in self.duts:
dut.print_info()
return self.duts |
java | @SuppressWarnings("unchecked")
private byte[] generateColumnFamilyKeyFromPkObj(CFMappingDef<?> cfMapDef, Object pkObj) {
List<byte[]> segmentList = new ArrayList<byte[]>(cfMapDef.getKeyDef().getIdPropertyMap().size());
if (cfMapDef.getKeyDef().isComplexKey()) {
Map<String, PropertyDescriptor> propertyDescriptorMap = cfMapDef.getKeyDef().getPropertyDescriptorMap();
for (String key : cfMapDef.getKeyDef().getIdPropertyMap().keySet()) {
PropertyDescriptor pd = propertyDescriptorMap.get(key);
segmentList.add(callMethodAndConvertToCassandraType(pkObj, pd.getReadMethod(),
new DefaultConverter()));
}
} else {
PropertyMappingDefinition md = cfMapDef.getKeyDef().getIdPropertyMap().values().iterator()
.next();
segmentList.add(md.getConverter().convertObjTypeToCassType(pkObj));
}
return keyConcatStrategy.concat(segmentList);
} |
python | def _write_cache_to_file(self):
"""Write the contents of the cache to a file on disk."""
with(open(self._cache_file_name, 'w')) as fp:
fp.write(simplejson.dumps(self._cache)) |
java | public void calcOffset(Container compAnchor, Point offset)
{
offset.x = 0;
offset.y = 0;
Container parent = this;
while (parent != null)
{
offset.x -= parent.getLocation().x;
offset.y -= parent.getLocation().y;
parent = parent.getParent();
if (parent == compAnchor)
return; // Success
}
// Failure - comp not found.
offset.x = 0;
offset.y = 0;
} |
java | public ApiResponse<ApiSuccessResponse> switchToListenInWithHttpInfo(String id, MonitoringScopeData monitoringScopeData) throws ApiException {
com.squareup.okhttp.Call call = switchToListenInValidateBeforeCall(id, monitoringScopeData, null, null);
Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} |
java | @Override
public void connectController(String host, int port) {
try {
if (host == null && port == -1) {
try {
this.controllerHost = this.defaultControllerHost;
this.controllerPort = this.defaultControllerPort;
client.connect(new InetSocketAddress(this.controllerHost, this.controllerPort));
this.prompt = this.prefix + "(local)" + Shell.CLI_POSTFIX;
} catch (IOException e) {
this.printLine(e.getMessage());
}
} else {
this.controllerHost = host;
this.controllerPort = port;
client.connect(new InetSocketAddress(this.controllerHost, this.controllerPort));
this.prompt = this.prefix + "(" + host + ":" + port + ")" + Shell.CLI_POSTFIX;
}
Message incomingFirstMessage = this.client.run(null);
String mesage = incomingFirstMessage.toString();
this.printLine(mesage);
if (mesage.contains(CONNECTED_AUTHENTICATING_MESSAGE)) {
username = this.console.readLine("Username:");
this.client.run(messageFactory.createMessage(username));
password = this.console.readLine("Password:", '*');
Message message = this.client.run(messageFactory.createMessage(password));
mesage = message.toString();
if (mesage.equals(CONNECTED_AUTHENTICATION_FAILED)) {
this.printLine(message.toString());
this.disconnectController();
}
} else if (mesage.contains(CLOSING_CONNECTION_MESSAGE)) {
this.disconnectController();
}
} catch (Exception e) {
this.printLine(e.getMessage());
}
} |
python | def createExternalTable(self, tableName, path=None, source=None, schema=None, **options):
"""Creates an external table based on the dataset in a data source.
It returns the DataFrame associated with the external table.
The data source is specified by the ``source`` and a set of ``options``.
If ``source`` is not specified, the default data source configured by
``spark.sql.sources.default`` will be used.
Optionally, a schema can be provided as the schema of the returned :class:`DataFrame` and
created external table.
:return: :class:`DataFrame`
"""
return self.sparkSession.catalog.createExternalTable(
tableName, path, source, schema, **options) |
java | public static Object getId(Object object) {
Objects.nonNull(object);
try {
Field idField = getIdField(object.getClass());
if (idField == null) throw new IllegalArgumentException(object.getClass().getName() + " has no id field to get");
Object id = idField.get(object);
return id;
} catch (SecurityException | IllegalAccessException e) {
throw new LoggingRuntimeException(e, logger, "getting Id failed");
}
} |
python | def loads_json(p_str, custom=None, meta=False, verbose=0):
"""
Given a json string it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param meta: bool, if true then also return all ecp meta data in separate dict
:param verbose: int, console output
:return: dict
"""
data = json.loads(p_str)
if meta:
md = {}
for item in data:
if item != "models":
md[item] = data[item]
return ecp_dict_to_objects(data, custom, verbose=verbose), md
else:
return ecp_dict_to_objects(data, custom, verbose=verbose) |
java | public <T extends BaseWrapper<T>> CollectionWrapper<T> createCollection(final Object collection, final Class<?> entityClass,
boolean isRevisionCollection) {
return createCollection((Collection) collection, entityClass, isRevisionCollection);
} |
java | public CodeSigner[] getCodeSigners() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
return mount.getFileSystem().getCodeSigners(mount.getMountPoint(), this);
} |
python | def column(self, key):
"""Iterator over a given column, skipping steps that don't have that key
"""
for row in self.rows:
if key in row:
yield row[key] |
python | def _get_download_url(self):
"""Get the download URL for the current blob.
If the ``media_link`` has been loaded, it will be used, otherwise
the URL will be constructed from the current blob's path (and possibly
generation) to avoid a round trip.
:rtype: str
:returns: The download URL for the current blob.
"""
name_value_pairs = []
if self.media_link is None:
base_url = _DOWNLOAD_URL_TEMPLATE.format(path=self.path)
if self.generation is not None:
name_value_pairs.append(("generation", "{:d}".format(self.generation)))
else:
base_url = self.media_link
if self.user_project is not None:
name_value_pairs.append(("userProject", self.user_project))
return _add_query_parameters(base_url, name_value_pairs) |
java | @Pure
public static <S> S getSreSpecificData(SRESpecificDataContainer container, Class<S> type) {
assert container != null;
return container.$getSreSpecificData(type);
} |
python | def convert_libraries_in_path(config_path, lib_path, target_path=None):
"""
This function resaves all libraries found at the spcified path
:param lib_path: the path to look for libraries
:return:
"""
for lib in os.listdir(lib_path):
if os.path.isdir(os.path.join(lib_path, lib)) and not '.' == lib[0]:
if os.path.exists(os.path.join(os.path.join(lib_path, lib), "statemachine.yaml")) or \
os.path.exists(os.path.join(os.path.join(lib_path, lib), "statemachine.json")):
if not target_path:
convert(config_path, os.path.join(lib_path, lib))
else:
convert(config_path, os.path.join(lib_path, lib), os.path.join(target_path, lib))
else:
if not target_path:
convert_libraries_in_path(config_path, os.path.join(lib_path, lib))
else:
convert_libraries_in_path(config_path, os.path.join(lib_path, lib), os.path.join(target_path, lib))
else:
if os.path.isdir(os.path.join(lib_path, lib)) and '.' == lib[0]:
logger.debug("lib_root_path/lib_path .*-folder are ignored if within lib_path, "
"e.g. -> {0} -> full path is {1}".format(lib, os.path.join(lib_path, lib))) |
java | @Override
public DescribeFleetPortSettingsResult describeFleetPortSettings(DescribeFleetPortSettingsRequest request) {
request = beforeClientExecution(request);
return executeDescribeFleetPortSettings(request);
} |
python | def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10):
"""Indicate whether the given string is a valid email address
according to the 'addr-spec' portion of RFC 2822 (see section
3.4.1). Parts of the spec that are marked obsolete are *not*
included in this test, and certain arcane constructions that
depend on circular definitions in the spec may not pass, but in
general this should correctly identify any email address likely
to be in use as of 2011."""
if debug:
logger = logging.getLogger('validate_email')
logger.setLevel(logging.DEBUG)
else:
logger = None
try:
assert re.match(VALID_ADDRESS_REGEXP, email) is not None
check_mx |= verify
if check_mx:
if not DNS:
raise Exception('For check the mx records or check if the email exists you must '
'have installed pyDNS python package')
hostname = email[email.find('@') + 1:]
mx_hosts = get_mx_ip(hostname)
if mx_hosts is None:
return False
for mx in mx_hosts:
try:
if not verify and mx[1] in MX_CHECK_CACHE:
return MX_CHECK_CACHE[mx[1]]
smtp = smtplib.SMTP(timeout=smtp_timeout)
smtp.connect(mx[1])
MX_CHECK_CACHE[mx[1]] = True
if not verify:
try:
smtp.quit()
except smtplib.SMTPServerDisconnected:
pass
return True
status, _ = smtp.helo()
if status != 250:
smtp.quit()
if debug:
logger.debug(u'%s answer: %s - %s', mx[1], status, _)
continue
smtp.mail('')
status, _ = smtp.rcpt(email)
if status == 250:
smtp.quit()
return True
if debug:
logger.debug(u'%s answer: %s - %s', mx[1], status, _)
smtp.quit()
except smtplib.SMTPServerDisconnected: # Server not permits verify user
if debug:
logger.debug(u'%s disconected.', mx[1])
except smtplib.SMTPConnectError:
if debug:
logger.debug(u'Unable to connect to %s.', mx[1])
return None
except AssertionError:
return False
except (ServerError, socket.error) as e:
if debug:
logger.debug('ServerError or socket.error exception raised (%s).', e)
return None
return True |
java | private Token scanNumber(int c) throws IOException {
int startLine = mSource.getLineNumber();
int startPos = mSource.getStartPosition();
mWord.setLength(0);
int errorPos = -1;
// 0 is decimal int,
// 1 is hex int,
// 2 is decimal long,
// 3 is hex long,
// 4 is float,
// 5 is double,
// 6 is auto-double by decimal
// 7 is auto-double by exponent ('e' or 'E')
int type = 0;
if (c == '0') {
if (mSource.peek() == 'x' || mSource.peek() == 'X') {
type = 1;
mSource.read(); // absorb the 'x'
c = mSource.read(); // get the first digit after the 'x'
}
}
for (; c != -1; c = mSource.read()) {
if (c == '.') {
int peek = mSource.peek();
if (peek == '.') {
mSource.unread();
break;
}
else {
if (peek < '0' || peek > '9') {
error("number.decimal.end");
}
mWord.append((char)c);
if (type == 0) {
type = 6;
}
else if (errorPos < 0) {
errorPos = mSource.getStartPosition();
}
continue;
}
}
if (c >= '0' && c <= '9') {
mWord.append((char)c);
if (type == 2 || type == 3 || type == 4 || type == 5) {
if (errorPos < 0) {
errorPos = mSource.getStartPosition();
}
}
continue;
}
if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
if (type == 1) {
mWord.append((char)c);
continue;
}
if (c == 'f' || c == 'F') {
if (type == 0 || type == 6 || type == 7) {
type = 4;
continue;
}
}
else if (c == 'd' || c == 'D') {
if (type == 0 || type == 6 || type == 7) {
type = 5;
continue;
}
}
else if (c == 'e' || c == 'E') {
if (type == 0 || type == 6) {
mWord.append((char)c);
type = 7;
int peek = mSource.peek();
if (peek == '+' || peek == '-') {
mWord.append((char)mSource.read());
}
continue;
}
}
mWord.append((char)c);
if (errorPos < 0) {
errorPos = mSource.getStartPosition();
}
continue;
}
if (c == 'l' || c == 'L') {
if (type == 0) {
type = 2;
}
else if (type == 1) {
type = 3;
}
else {
mWord.append((char)c);
if (errorPos < 0) {
errorPos = mSource.getStartPosition();
}
}
continue;
}
if (Character.isLetterOrDigit((char)c)) {
mWord.append((char)c);
if (errorPos < 0) {
errorPos = mSource.getStartPosition();
}
}
else {
mSource.unread();
break;
}
}
String str = mWord.toString();
int endPos = mSource.getEndPosition();
Token token;
if (errorPos >= 0) {
token = new StringToken
(startLine, startPos, endPos, errorPos, Token.NUMBER, str);
}
else {
try {
switch (type) {
case 0:
default:
try {
token = new IntToken
(startLine, startPos, endPos,
Integer.parseInt(str));
}
catch (NumberFormatException e) {
token = new LongToken
(startLine, startPos, endPos, Long.parseLong(str));
}
break;
case 1:
try {
token = new IntToken
(startLine, startPos, endPos, parseHexInt(str));
}
catch (NumberFormatException e) {
token = new LongToken
(startLine, startPos, endPos, parseHexLong(str));
}
break;
case 2:
token = new LongToken
(startLine, startPos, endPos, Long.parseLong(str));
break;
case 3:
token = new LongToken
(startLine, startPos, endPos, parseHexLong(str));
break;
case 4:
token = new FloatToken
(startLine, startPos, endPos, Float.parseFloat(str));
break;
case 5:
case 6:
case 7:
token = new DoubleToken
(startLine, startPos, endPos, Double.parseDouble(str));
break;
}
}
catch (NumberFormatException e) {
token = new IntToken(startLine, startPos, endPos, 0);
error("number.range", token.getSourceInfo());
}
}
return token;
} |
java | public static CanCache of(MethodDescription.InDefinedShape methodDescription) {
if (methodDescription.isTypeInitializer()) {
return CanCacheIllegal.INSTANCE;
} else if (methodDescription.isConstructor()) {
return new ForConstructor(methodDescription);
} else {
return new ForMethod(methodDescription);
}
} |
java | private static boolean isLinearRing(LineString lineString) {
if (lineString.coordinates().size() < 4) {
throw new GeoJsonException("LinearRings need to be made up of 4 or more coordinates.");
}
if (!(lineString.coordinates().get(0).equals(
lineString.coordinates().get(lineString.coordinates().size() - 1)))) {
throw new GeoJsonException("LinearRings require first and last coordinate to be identical.");
}
return true;
} |
python | def p_expression_comparison(self, p):
"""
expression : name comparison_number number
| name comparison_string string
| name comparison_equality boolean_value
| name comparison_equality none
| name comparison_in_list const_list_value
"""
p[0] = Expression(left=p[1], operator=p[2], right=p[3]) |
python | def get_tokens_list(self, registry_address: PaymentNetworkID):
"""Returns a list of tokens the node knows about"""
tokens_list = views.get_token_identifiers(
chain_state=views.state_from_raiden(self.raiden),
payment_network_id=registry_address,
)
return tokens_list |
python | def push(self, tx):
"""
Args:
tx: hex of signed transaction
Returns:
pushed transaction
"""
self._service.push_tx(tx)
return bitcoin.txhash(tx) |
java | @Override
public DescribeBundleTasksResult describeBundleTasks(DescribeBundleTasksRequest request) {
request = beforeClientExecution(request);
return executeDescribeBundleTasks(request);
} |
python | def get_id_type_map(id_list: Iterable[str]) -> Dict[str, List[str]]:
"""
Given a list of ids return their types
:param id_list: list of ids
:return: dictionary where the id is the key and the value is a list of types
"""
type_map = {}
filter_out_types = [
'cliqueLeader',
'Class',
'Node',
'Individual',
'quality',
'sequence feature'
]
for node in get_scigraph_nodes(id_list):
type_map[node['id']] = [typ.lower() for typ in node['meta']['types']
if typ not in filter_out_types]
return type_map |
python | def is_installed(self, package):
"""Returns True if the given package (given in pip's package syntax or a
tuple of ('name', 'ver')) is installed in the virtual environment."""
if isinstance(package, tuple):
package = '=='.join(package)
if package.endswith('.git'):
pkg_name = os.path.split(package)[1][:-4]
return pkg_name in self.installed_package_names or \
pkg_name.replace('_', '-') in self.installed_package_names
pkg_tuple = split_package_name(package)
if pkg_tuple[1] is not None:
return pkg_tuple in self.installed_packages
else:
return pkg_tuple[0].lower() in self.installed_package_names |
python | def CreateGRRTempFile(filename=None, lifetime=0, mode="w+b", suffix=""):
"""Open file with GRR prefix in directory to allow easy deletion.
Missing parent dirs will be created. If an existing directory is specified
its permissions won't be modified to avoid breaking system functionality.
Permissions on the destination file will be set to root/SYSTEM rw.
On windows the file is created, then permissions are set. So there is
potentially a race condition where the file is readable by other users. If
the caller doesn't specify a directory on windows we use the directory we are
executing from as a safe default.
If lifetime is specified a housekeeping thread is created to delete the file
after lifetime seconds. Files won't be deleted by default.
Args:
filename: The name of the file to use. Note that setting both filename and
directory name is not allowed.
lifetime: time in seconds before we should delete this tempfile.
mode: The mode to open the file.
suffix: optional suffix to use for the temp file
Returns:
Python file object
Raises:
OSError: on permission denied
ErrorBadPath: if path is not absolute
ValueError: if Client.tempfile_prefix is undefined in the config.
"""
directory = GetDefaultGRRTempDirectory()
EnsureTempDirIsSane(directory)
prefix = config.CONFIG.Get("Client.tempfile_prefix")
if filename is None:
outfile = tempfile.NamedTemporaryFile(
prefix=prefix, suffix=suffix, dir=directory, delete=False)
else:
if filename.startswith("/") or filename.startswith("\\"):
raise ValueError("Filename must be relative")
if suffix:
filename = "%s.%s" % (filename, suffix)
outfile = open(os.path.join(directory, filename), mode)
if lifetime > 0:
cleanup = threading.Timer(lifetime, DeleteGRRTempFile, (outfile.name,))
cleanup.start()
# Fix perms on the file, since this code is used for writing executable blobs
# we apply RWX.
if sys.platform == "win32":
from grr_response_client import client_utils_windows # pylint: disable=g-import-not-at-top
client_utils_windows.WinChmod(outfile.name, ["FILE_ALL_ACCESS"])
else:
os.chmod(outfile.name, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)
return outfile |
java | public String getSubject() {
if (triple.getSubject() instanceof IRI) {
return ((IRI) triple.getSubject()).getIRIString();
}
return triple.getSubject().ntriplesString();
} |
java | public RequestHeader withUri(URI uri) {
return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, principal, headers, lowercaseHeaders);
} |
python | def _getattr(self, attri, fname=None, numtype='cycNum'):
''' Private method for getting an attribute, called from get.'''
if str(fname.__class__)=="<type 'list'>":
isList=True
else:
isList=False
data=[]
if fname==None:
fname=self.files
numtype='file'
isList=True
if isList:
for i in range(len(fname)):
if attri in self.cattrs:
data.append(self.getCycleData(attri,fname[i],numtype))
elif attri in self.dcols:
data.append(self.getColData(attri,fname[i],numtype))
elif attri in self.get('ISOTP',fname,numtype):
data.append(self.getElement(attri,fname[i],numtype))
else:
print('Attribute '+attri+ ' does not exist')
print('Returning none')
return None
else:
if attri in self.cattrs:
return self.getCycleData(attri,fname,numtype)
elif attri in self.dcols:
return self.getColData(attri,fname,numtype)
elif attri in self.get('ISOTP',fname,numtype):
return self.getElement(attri,fname,numtype)
else:
print('Attribute '+attri+ ' does not exist')
print('Returning none')
return None
return data |
java | private static ExtensionAuthentication getAuthenticationExtension() {
if (extensionAuth == null) {
extensionAuth = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAuthentication.class);
}
return extensionAuth;
} |
python | def delete_commit(self, commit):
"""
Deletes a commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
"""
req = proto.DeleteCommitRequest(commit=commit_from(commit))
self.stub.DeleteCommit(req, metadata=self.metadata) |
python | def get_pubmed_record(pmid):
"""Get PubMed record from PubMed ID."""
handle = Entrez.esummary(db="pubmed", id=pmid)
record = Entrez.read(handle)
return record |
python | async def make_transition_register(self, request: 'Request'):
"""
Use all underlying stacks to generate the next transition register.
"""
register = {}
for stack in self._stacks:
register = await stack.patch_register(register, request)
return register |
java | public String generateUniqueId(String prefix, String text)
{
// Verify that the passed prefix contains only alpha characters since the generated id must be a valid HTML id.
if (StringUtils.isEmpty(prefix) || !StringUtils.isAlpha(prefix)) {
throw new IllegalArgumentException(
"The prefix [" + prefix + "] should only contain alphanumerical characters and not be empty.");
}
String idPrefix = prefix + normalizeId(text);
int occurence = 0;
String id = idPrefix;
while (this.generatedIds.contains(id)) {
occurence++;
id = idPrefix + "-" + occurence;
}
// Save the generated id so that the next call to this method will not generate the same id.
this.generatedIds.add(id);
return id;
} |
java | public Matrix4d translationRotateScale(double tx, double ty, double tz,
double qx, double qy, double qz, double qw,
double sx, double sy, double sz) {
double dqx = qx + qx, dqy = qy + qy, dqz = qz + qz;
double q00 = dqx * qx;
double q11 = dqy * qy;
double q22 = dqz * qz;
double q01 = dqx * qy;
double q02 = dqx * qz;
double q03 = dqx * qw;
double q12 = dqy * qz;
double q13 = dqy * qw;
double q23 = dqz * qw;
m00 = sx - (q11 + q22) * sx;
m01 = (q01 + q23) * sx;
m02 = (q02 - q13) * sx;
m03 = 0.0;
m10 = (q01 - q23) * sy;
m11 = sy - (q22 + q00) * sy;
m12 = (q12 + q03) * sy;
m13 = 0.0;
m20 = (q02 + q13) * sz;
m21 = (q12 - q03) * sz;
m22 = sz - (q11 + q00) * sz;
m23 = 0.0;
m30 = tx;
m31 = ty;
m32 = tz;
m33 = 1.0;
boolean one = Math.abs(sx) == 1.0 && Math.abs(sy) == 1.0 && Math.abs(sz) == 1.0;
properties = PROPERTY_AFFINE | (one ? PROPERTY_ORTHONORMAL : 0);
return this;
} |
python | def filter_inconsequential_mods(stmts_in, whitelist=None, **kwargs):
"""Filter out Modifications that modify inconsequential sites
Inconsequential here means that the site is not mentioned / tested
in any other statement. In some cases specific sites should be
preserved, for instance, to be used as readouts in a model.
In this case, the given sites can be passed in a whitelist.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
whitelist : Optional[dict]
A whitelist containing agent modification sites whose
modifications should be preserved even if no other statement
refers to them. The whitelist parameter is a dictionary in which
the key is a gene name and the value is a list of tuples of
(modification_type, residue, position). Example:
whitelist = {'MAP2K1': [('phosphorylation', 'S', '222')]}
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
Returns
-------
stmts_out : list[indra.statements.Statement]
A list of filtered statements.
"""
if whitelist is None:
whitelist = {}
logger.info('Filtering %d statements to remove' % len(stmts_in) +
' inconsequential modifications...')
states_used = whitelist
for stmt in stmts_in:
for agent in stmt.agent_list():
if agent is not None:
if agent.mods:
for mc in agent.mods:
mod = (mc.mod_type, mc.residue, mc.position)
try:
states_used[agent.name].append(mod)
except KeyError:
states_used[agent.name] = [mod]
for k, v in states_used.items():
states_used[k] = list(set(v))
stmts_out = []
for stmt in stmts_in:
skip = False
if isinstance(stmt, Modification):
mod_type = modclass_to_modtype[stmt.__class__]
if isinstance(stmt, RemoveModification):
mod_type = modtype_to_inverse[mod_type]
mod = (mod_type, stmt.residue, stmt.position)
used = states_used.get(stmt.sub.name, [])
if mod not in used:
skip = True
if not skip:
stmts_out.append(stmt)
logger.info('%d statements after filter...' % len(stmts_out))
dump_pkl = kwargs.get('save')
if dump_pkl:
dump_statements(stmts_out, dump_pkl)
return stmts_out |
python | def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_name = service_name.split('.')[0]
if service_name in template_files:
return template_files[service_name]
return None |
java | public void promote(String resourceGroupName, String clusterName, String scriptExecutionId) {
promoteWithServiceResponseAsync(resourceGroupName, clusterName, scriptExecutionId).toBlocking().single().body();
} |
java | static public UpdateSpecifier computeUpdateSpecifier(
Document sourceDoc
,JSONObject targetDoc
) throws Exception {
DigestComputerSha1 digestComputer = new DigestComputerSha1();
DocumentDigest dd = digestComputer.computeDocumentDigest(sourceDoc);
return computeUpdateSpecifier(
sourceDoc
,dd
,targetDoc
,DocumentUpdateProcess.Schedule.UPDATE_UNLESS_MODIFIED
,UpdateObjectComparator.getNunaliitComparator()
);
} |
java | public String createModcaString4FromString(EDataType eDataType, String initialValue) {
return (String)super.createFromString(eDataType, initialValue);
} |
python | def sign_extend(self, new_length):
"""
Unary operation: SignExtend
:param new_length: New length after sign-extension
:return: A new StridedInterval
"""
msb = self.extract(self.bits - 1, self.bits - 1).eval(2)
if msb == [ 0 ]:
# All positive numbers
return self.zero_extend(new_length)
if msb == [ 1 ]:
# All negative numbers
si = self.copy()
si._bits = new_length
mask = (2 ** new_length - 1) - (2 ** self.bits - 1)
si._lower_bound |= mask
si._upper_bound |= mask
else:
# Both positive numbers and negative numbers
numbers = self._nsplit()
# Since there are both positive and negative numbers, there must be two bounds after nsplit
# assert len(numbers) == 2
all_resulting_intervals = list()
assert len(numbers) > 0
for n in numbers:
a, b = n.lower_bound, n.upper_bound
mask_a = 0
mask_b = 0
mask_n = ((1 << (new_length - n.bits)) - 1) << n.bits
if StridedInterval._get_msb(a, n.bits) == 1:
mask_a = mask_n
if StridedInterval._get_msb(b, n.bits) == 1:
mask_b = mask_n
si_ = StridedInterval(bits=new_length, stride=n.stride, lower_bound=a | mask_a, upper_bound=b | mask_b)
all_resulting_intervals.append(si_)
si = StridedInterval.least_upper_bound(*all_resulting_intervals).normalize()
si.uninitialized = self.uninitialized
return si |
java | public static <U, I> void saveDataModel(final DataModelIF<U, I> dm, final String outfile, final boolean overwrite, final String delimiter)
throws FileNotFoundException, UnsupportedEncodingException {
if (new File(outfile).exists() && !overwrite) {
System.out.println("Ignoring " + outfile);
} else {
PrintStream out = new PrintStream(outfile, "UTF-8");
for (U user : dm.getUsers()) {
for (I item : dm.getUserItems(user)) {
Double pref = dm.getUserItemPreference(user, item);
out.println(user + delimiter + item + delimiter + pref);
}
}
out.close();
}
} |
java | @Override
protected String convert(final LoggingEvent event) {
//
// code should be unreachable.
//
final StringBuffer sbuf = new StringBuffer();
format(sbuf, event);
return sbuf.toString();
} |
java | public static void showView(View parentView, int id) {
if (parentView != null) {
View view = parentView.findViewById(id);
if (view != null) {
view.setVisibility(View.VISIBLE);
} else {
Log.e("Caffeine", "View does not exist. Could not show it.");
}
}
} |
java | private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
byte[] buffer = null;
try {
InputStream in = entity.getContent();
if (in == null) {
throw new ServerError();
}
buffer = mPool.getBuf(1024);
int count;
while ((count = in.read(buffer)) != -1) {
bytes.write(buffer, 0, count);
}
return bytes.toByteArray();
} finally {
try {
// Close the InputStream and release the resources by "consuming the content".
entity.consumeContent();
} catch (IOException e) {
// This can happen if there was an exception above that left the entity in
// an invalid state.
VolleyLog.v("Error occured when calling consumingContent");
}
mPool.returnBuf(buffer);
bytes.close();
}
} |
python | def _parameterize_string(raw):
"""Substitute placeholders in a string using CloudFormation references
Args:
raw (`str`): String to be processed. Byte strings are not
supported; decode them before passing them to this function.
Returns:
`str` | :class:`troposphere.GenericHelperFn`: An expression with
placeholders from the input replaced, suitable to be passed to
Troposphere to be included in CloudFormation template. This will
be the input string without modification if no substitutions are
found, and a composition of CloudFormation calls otherwise.
"""
parts = []
s_index = 0
for match in _PARAMETER_PATTERN.finditer(raw):
parts.append(raw[s_index:match.start()])
parts.append({u"Ref": match.group(1)})
s_index = match.end()
if not parts:
return GenericHelperFn(raw)
parts.append(raw[s_index:])
return GenericHelperFn({u"Fn::Join": [u"", parts]}) |
python | def _palette(self):
""" p """
# Loop through available palettes
self.palette_idx += 1
try:
self.loop.screen.register_palette(self.palettes[self.palette_names[self.palette_idx]])
except IndexError:
self.loop.screen.register_palette(self.palettes[self.palette_names[0]])
self.palette_idx = 0
self.loop.screen.clear() |
python | def _ParseEntry(self, key, val):
"""Adds an entry for a configuration setting.
Args:
key: The name of the setting.
val: The value of the setting.
"""
if key in self._repeated:
setting = self.section.setdefault(key, [])
setting.extend(val)
else:
self.section.setdefault(key, val) |
python | def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False,
api_key=False, email=False, **kwargs) -> Optional[EsearchResult]:
"""Search for a query using the Entrez ESearch API.
Parameters
----------
database : str
Entez database to search.
query : str
Query string
userhistory : bool
Tells API to return a WebEnV and query_key.
webenv : str
An Entrez WebEnv to use saved history.
query_key : str
An Entrez query_key to use saved history.
retstart : int
Return values starting at this index.
retmax : int
Return at most this number of values.
api_key : str
A users API key which allows more requests per second
email : str
A users email which is required if not using API.
Returns
-------
EsearchResult
A named tuple with values [ids, count, webenv, query_key]
"""
cleaned_query = urllib.parse.quote_plus(query, safe='/+')
url = BASE_URL + f'esearch.fcgi?db={database}&term={cleaned_query}&retmode=json'
url = check_userhistory(userhistory, url)
url = check_webenv(webenv, url)
url = check_query_key(query_key, url)
url = check_retstart(retstart, url)
url = check_retmax(retmax, url)
url = check_api_key(api_key, url)
url = check_email(email, url)
time.sleep(PAUSE)
resp = requests.get(url)
if resp.status_code != 200:
print('There was a server error')
return
text = resp.json()
time.sleep(.5)
return EsearchResult(
text['esearchresult'].get('idlist', []),
make_number(text['esearchresult'].get('count', ''), int),
text['esearchresult'].get('webenv', ''),
text['esearchresult'].get('querykey', '')
) |
java | @Override
public TableName[] listTableNamesByNamespace(String name) throws IOException {
if (provideWarningsForNamespaces()) {
LOG.warn("listTableNamesByNamespace is a no-op");
return new TableName[0];
} else {
throw new UnsupportedOperationException("listTableNamesByNamespace"); // TODO
}
} |
python | def read_version(version_file):
"Read the `(version-string, version-info)` from `version_file`."
vars = {}
with open(version_file) as f:
exec(f.read(), {}, vars)
return (vars['__version__'], vars['__version_info__']) |
python | def is_json_compat(value):
"""
Check that the value is either a JSON decodable string or a dict
that can be encoded into a JSON.
Raises ValueError when validation fails.
"""
try:
value = json.loads(value)
except ValueError as e:
raise ValueError('JSON decoding error: ' + str(e))
except TypeError:
# Check that the value can be serialized back into json.
try:
json.dumps(value)
except TypeError as e:
raise ValueError(
'must be a JSON serializable object: ' + str(e))
if not isinstance(value, dict):
raise ValueError(
'must be specified as a JSON serializable dict or a '
'JSON deserializable string'
)
return True |
java | @Produces
@LoggedIn
public String extractUsername() {
final KeycloakPrincipal principal = (KeycloakPrincipal) httpServletRequest.getUserPrincipal();
if (principal != null) {
logger.debug("Running with Keycloak context");
KeycloakSecurityContext kcSecurityContext = principal.getKeycloakSecurityContext();
return kcSecurityContext.getToken().getPreferredUsername();
}
logger.debug("Running outside of Keycloak context");
final String basicUsername = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(httpServletRequest)[0];
if (! basicUsername.isEmpty()) {
logger.debug("running HttpBasic auth");
return basicUsername;
}
logger.debug("Running without any Auth context");
return "admin"; // by default, we are admin!
} |
java | public List<Pair> parameterToPair(String name, Object value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params;
params.add(new Pair(name, parameterToString(value)));
return params;
} |
java | public NodeSet<OWLClass> getFillers(OWLClassExpression ce, List<OWLObjectPropertyExpression> propertyList) {
Set<Node<OWLClass>> result = new HashSet<Node<OWLClass>>();
entailmentCheckCount = 0;
computeExistentialFillers(ce, propertyList, getDataFactory().getOWLThing(), result, new HashSet<OWLClass>());
NodeSet<OWLClass> nodeSetResult = new OWLClassNodeSet(result);
if (fillerTreatment == FillerTreatment.ALL) {
return nodeSetResult;
}
Set<Node<OWLClass>> removed = new HashSet<Node<OWLClass>>();
Set<Node<OWLClass>> finalResult = new HashSet<Node<OWLClass>>(nodeSetResult.getNodes());
for (Node<OWLClass> resultCls : result) {
OWLClass resultClsRep = resultCls.getRepresentativeElement();
if (!removed.contains(resultCls)) {
removed.add(resultCls);
NodeSet<OWLClass> supers = reasoner.getSuperClasses(resultClsRep, false);
removed.addAll(supers.getNodes());
finalResult.removeAll(supers.getNodes());
}
}
System.out.printf("For %s and %s, there were %d entailment checks.\n", ce, propertyList, entailmentCheckCount);
return new OWLClassNodeSet(finalResult);
} |
java | public GenericField[] getFields()
{
Collection<GenericField> values = fieldMap.values();
if(values == null || values.isEmpty())
return null;
GenericField[] fieldMirrors = new GenericField[values.size()];
values.toArray(fieldMirrors);
return fieldMirrors;
} |
python | def make(class_name, base, schema):
"""
Create a new schema aware type.
"""
return type(class_name, (base,), dict(SCHEMA=schema)) |
java | public static appqoecustomresp[] get_filtered(nitro_service service, String filter) throws Exception{
appqoecustomresp obj = new appqoecustomresp();
options option = new options();
option.set_filter(filter);
appqoecustomresp[] response = (appqoecustomresp[]) obj.getfiltered(service, option);
return response;
} |
python | def get(self, *, no_ack=False):
"""
Synchronously get a message from the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message.
:return: an :class:`~asynqp.message.IncomingMessage`,
or ``None`` if there were no messages on the queue.
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
self.sender.send_BasicGet(self.name, no_ack)
tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty)
if tag_msg is not None:
consumer_tag, msg = tag_msg
assert consumer_tag is None
else:
msg = None
self.reader.ready()
return msg |
java | public static VersionValues find(byte[] name, int offset, int length) {
return myMatcher.match(name, offset, length, true);
} |
java | public Future<DeleteItemResult> deleteItemAsync(final DeleteItemRequest deleteItemRequest)
throws AmazonServiceException, AmazonClientException {
return executorService.submit(new Callable<DeleteItemResult>() {
public DeleteItemResult call() throws Exception {
return deleteItem(deleteItemRequest);
}
});
} |
python | def get_next_asset_content(self):
"""Gets the next AssetContent in this list.
return: (osid.repository.AssetContent) - the next AssetContent
in this list. The has_next() method should be used to
test that a next AssetContent is available before
calling this method.
raise: IllegalState - no more elements available in this list
raise: OperationFailed - unable to complete request
compliance: mandatory - This method must be implemented.
"""
try:
next_object = next(self)
except StopIteration:
raise IllegalState('no more elements available in this list')
except Exception: # Need to specify exceptions here!
raise OperationFailed()
else:
return next_object |
java | public static clusterinstance_clusternode_binding[] get_filtered(nitro_service service, Long clid, String filter) throws Exception{
clusterinstance_clusternode_binding obj = new clusterinstance_clusternode_binding();
obj.set_clid(clid);
options option = new options();
option.set_filter(filter);
clusterinstance_clusternode_binding[] response = (clusterinstance_clusternode_binding[]) obj.getfiltered(service, option);
return response;
} |
python | def load_friends(self):
"""Fetches the MAL user friends page and sets the current user's friends attributes.
:rtype: :class:`.User`
:return: Current user object.
"""
user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text
self.set(self.parse_friends(utilities.get_clean_dom(user_friends)))
return self |
java | private int computeNearestCoarseIndex(double[] vector) {
int centroidIndex = -1;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < numCoarseCentroids; i++) {
double distance = 0;
for (int j = 0; j < vectorLength; j++) {
distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]);
if (distance >= minDistance) {
break;
}
}
if (distance < minDistance) {
minDistance = distance;
centroidIndex = i;
}
}
return centroidIndex;
} |
java | public static String resolveProperty( Properties props, String value )
{
return PropertyResolver.resolve( props, value );
} |
python | def folderitems(self):
"""TODO: Refactor to non-classic mode
"""
items = super(ServicesView, self).folderitems()
self.categories.sort()
return items |
java | public static Xml exports(SizeConfig config)
{
Check.notNull(config);
final Xml node = new Xml(NODE_SIZE);
node.writeInteger(ATT_WIDTH, config.getWidth());
node.writeInteger(ATT_HEIGHT, config.getHeight());
return node;
} |
java | @Override
public <N extends Number> Expression<N> min(Expression<N> arg0)
{
// TODO Auto-generated method stub
return null;
} |
python | def boot(name=None, kwargs=None, call=None):
'''
Boot a Linode.
name
The name of the Linode to boot. Can be used instead of ``linode_id``.
linode_id
The ID of the Linode to boot. If provided, will be used as an
alternative to ``name`` and reduces the number of API calls to
Linode by one. Will be preferred over ``name``.
config_id
The ID of the Config to boot. Required.
check_running
Defaults to True. If set to False, overrides the call to check if
the VM is running before calling the linode.boot API call. Change
``check_running`` to True is useful during the boot call in the
create function, since the new VM will not be running yet.
Can be called as an action (which requires a name):
.. code-block:: bash
salt-cloud -a boot my-instance config_id=10
...or as a function (which requires either a name or linode_id):
.. code-block:: bash
salt-cloud -f boot my-linode-config name=my-instance config_id=10
salt-cloud -f boot my-linode-config linode_id=1225876 config_id=10
'''
if name is None and call == 'action':
raise SaltCloudSystemExit(
'The boot action requires a \'name\'.'
)
if kwargs is None:
kwargs = {}
linode_id = kwargs.get('linode_id', None)
config_id = kwargs.get('config_id', None)
check_running = kwargs.get('check_running', True)
if call == 'function':
name = kwargs.get('name', None)
if name is None and linode_id is None:
raise SaltCloudSystemExit(
'The boot function requires either a \'name\' or a \'linode_id\'.'
)
if config_id is None:
raise SaltCloudSystemExit(
'The boot function requires a \'config_id\'.'
)
if linode_id is None:
linode_id = get_linode_id_from_name(name)
linode_item = name
else:
linode_item = linode_id
# Check if Linode is running first
if check_running is True:
status = get_linode(kwargs={'linode_id': linode_id})['STATUS']
if status == '1':
raise SaltCloudSystemExit(
'Cannot boot Linode {0}. '
'Linode {0} is already running.'.format(linode_item)
)
# Boot the VM and get the JobID from Linode
response = _query('linode', 'boot',
args={'LinodeID': linode_id,
'ConfigID': config_id})['DATA']
boot_job_id = response['JobID']
if not _wait_for_job(linode_id, boot_job_id):
log.error('Boot failed for Linode %s.', linode_item)
return False
return True |
java | @CanIgnoreReturnValue
public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) {
return delegate().containsExactly(k0, v0, rest);
} |
java | @Override
public DescribeDominantLanguageDetectionJobResult describeDominantLanguageDetectionJob(DescribeDominantLanguageDetectionJobRequest request) {
request = beforeClientExecution(request);
return executeDescribeDominantLanguageDetectionJob(request);
} |
java | public final List<T> findByQuery(String query, Object... params) {
return this.findSortedByQuery(query, null, params);
} |
java | public void mouseExited(MouseEvent evt)
{
JLabel button = (JLabel)evt.getSource();
button.setBorder(oldBorder);
} |
java | public void setCellMerge(final Table table, final String pos,
final int rowMerge, final int columnMerge) throws FastOdsException, IOException {
final Position position = this.positionUtil.getPosition(pos);
final int row = position.getRow();
final int col = position.getColumn();
this.setCellMerge(table, row, col, rowMerge, columnMerge);
} |
python | def _load(self, data):
"""
Internal method that deserializes a ``pybrightcove.playlist.Playlist``
object.
"""
self.raw_data = data
self.id = data['id']
self.reference_id = data['referenceId']
self.name = data['name']
self.short_description = data['shortDescription']
self.thumbnail_url = data['thumbnailURL']
self.videos = []
self.video_ids = data['videoIds']
self.type = data['playlistType']
for video in data.get('videos', []):
self.videos.append(pybrightcove.video.Video(
data=video, connection=self.connection)) |
python | def dst(self, dt):
"""datetime -> DST offset in minutes east of UTC."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstdiff
return _zero |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.