language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | @Override
public ListConnectorDefinitionsResult listConnectorDefinitions(ListConnectorDefinitionsRequest request) {
request = beforeClientExecution(request);
return executeListConnectorDefinitions(request);
} |
python | def _fill_empty_sessions(self, fill_subjects, fill_visits):
"""
Fill in tree with additional empty subjects and/or visits to
allow the study to pull its inputs from external repositories
"""
if fill_subjects is None:
fill_subjects = [s.id for s in self.subjects]
if fill_visits is None:
fill_visits = [v.id for v in self.complete_visits]
for subject_id in fill_subjects:
try:
subject = self.subject(subject_id)
except ArcanaNameError:
subject = self._subjects[subject_id] = Subject(
subject_id, [], [], [])
for visit_id in fill_visits:
try:
subject.session(visit_id)
except ArcanaNameError:
session = Session(subject_id, visit_id, [], [])
subject._sessions[visit_id] = session
try:
visit = self.visit(visit_id)
except ArcanaNameError:
visit = self._visits[visit_id] = Visit(
visit_id, [], [], [])
visit._sessions[subject_id] = session |
java | @Override
protected void putVariables(Map<String, String> variables) {
variables.put(ScopeFormat.SCOPE_OPERATOR_ID, String.valueOf(operatorID));
variables.put(ScopeFormat.SCOPE_OPERATOR_NAME, operatorName);
// we don't enter the subtask_index as the task group does that already
} |
python | def setup_columns(self):
"""Creates the treeview stuff"""
tv = self.view['tv_categories']
# sets the model
tv.set_model(self.model)
# creates the columns
cell = gtk.CellRendererText()
tvcol = gtk.TreeViewColumn('Name', cell)
def cell_data_func(col, cell, mod, it):
if mod[it][0]: cell.set_property('text', mod[it][0].name)
return
tvcol.set_cell_data_func(cell, cell_data_func)
tv.append_column(tvcol)
return |
java | public void setResourceTypes(java.util.Collection<String> resourceTypes) {
if (resourceTypes == null) {
this.resourceTypes = null;
return;
}
this.resourceTypes = new com.amazonaws.internal.SdkInternalList<String>(resourceTypes);
} |
java | public static MetadataTemplate updateMetadataTemplate(BoxAPIConnection api, String scope, String template,
List<FieldOperation> fieldOperations) {
JsonArray array = new JsonArray();
for (FieldOperation fieldOperation : fieldOperations) {
JsonObject jsonObject = getFieldOperationJsonObject(fieldOperation);
array.add(jsonObject);
}
QueryStringBuilder builder = new QueryStringBuilder();
URL url = METADATA_TEMPLATE_URL_TEMPLATE.build(api.getBaseURL(), scope, template);
BoxJSONRequest request = new BoxJSONRequest(api, url, "PUT");
request.setBody(array.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject responseJson = JsonObject.readFrom(response.getJSON());
return new MetadataTemplate(responseJson);
} |
java | public static <T, M> LabeledTextFieldPanel<T, M> newLabeledTextFieldPanel(final String id,
final IModel<M> model, final IModel<String> labelModel)
{
final LabeledTextFieldPanel<T, M> labeledTextField = new LabeledTextFieldPanel<>(id, model,
labelModel);
labeledTextField.setOutputMarkupId(true);
return labeledTextField;
} |
python | def draw_image(self, image, xmin=0, ymin=0, xmax=None, ymax=None):
"""Draw an image.
Do not forget to use :meth:`set_axis_equal` to preserve the
aspect ratio of the image, or change the aspect ratio of the
plot to the aspect ratio of the image.
:param image: Pillow Image object.
:param xmin,ymin,xmax,ymax: the x, y image bounds.
Example::
>>> from PIL import Image
>>> image = Image.open('background.png')
>>> plot = artist.Plot()
>>> plot.set_axis_equal()
>>> plot.draw_image(image)
"""
if xmax is None:
xmax = xmin + image.size[0]
if ymax is None:
ymax = ymin + image.size[1]
self.bitmap_list.append({'image': image,
'xmin': xmin,
'xmax': xmax,
'ymin': ymin,
'ymax': ymax})
# Set limits unless lower/higher limits are already set.
xmin = min(x for x in (xmin, self.limits['xmin'])
if x is not None)
ymin = min(y for y in (ymin, self.limits['ymin'])
if y is not None)
xmax = max(x for x in (xmax, self.limits['xmax'])
if x is not None)
ymax = max(y for y in (ymax, self.limits['ymax'])
if y is not None)
self.set_xlimits(xmin, xmax)
self.set_ylimits(ymin, ymax) |
java | public void deleteComputeNodeUser(String poolId, String nodeId, String userName, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException {
ComputeNodeDeleteUserOptions options = new ComputeNodeDeleteUserOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors);
bhMgr.applyRequestBehaviors(options);
this.parentBatchClient.protocolLayer().computeNodes().deleteUser(poolId, nodeId, userName, options);
} |
java | @SuppressWarnings("WeakerAccess")
public void registerFont(String fontName, File fontFile) {
if (!fontFile.exists())
throw new IllegalArgumentException("Font " + fontFile + " does not exist!");
FontEntry entry = new FontEntry();
entry.overrideName = fontName;
entry.file = fontFile;
fontFiles.add(entry);
} |
python | def transform(self, X):
"""Scikit-learn required: Reduces the feature set down to the top `n_features_to_select` features.
Parameters
----------
X: array-like {n_samples, n_features}
Feature matrix to perform feature selection on
Returns
-------
X_reduced: array-like {n_samples, n_features_to_select}
Reduced feature matrix
"""
if self._num_attributes < self.n_features_to_select:
raise ValueError('Number of features to select is larger than the number of features in the dataset.')
return X[:, self.top_features_[:self.n_features_to_select]] |
python | def __execute_kadmin(cmd):
'''
Execute kadmin commands
'''
ret = {}
auth_keytab = __opts__.get('auth_keytab', None)
auth_principal = __opts__.get('auth_principal', None)
if __salt__['file.file_exists'](auth_keytab) and auth_principal:
return __salt__['cmd.run_all'](
'kadmin -k -t {0} -p {1} -q "{2}"'.format(
auth_keytab, auth_principal, cmd
)
)
else:
log.error('Unable to find kerberos keytab/principal')
ret['retcode'] = 1
ret['comment'] = 'Missing authentication keytab/principal'
return ret |
java | ParseTree toParseTree() {
List<ParseTree> children = new ArrayList<ParseTree>();
for (TreeNode child = latestChild; child != null; child = child.previous) {
children.add(child.toParseTree());
}
Collections.reverse(children);
return new ParseTree(name, beginIndex, endIndex, result, children);
} |
java | public boolean add(E e) {
typeCheck(e);
int eOrdinal = e.ordinal();
int eWordNum = eOrdinal >>> 6;
long oldElements = elements[eWordNum];
elements[eWordNum] |= (1L << eOrdinal);
boolean result = (elements[eWordNum] != oldElements);
if (result)
size++;
return result;
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case SimpleAntlrPackage.OPTIONS__OPTION_VALUES:
return getOptionValues();
}
return super.eGet(featureID, resolve, coreType);
} |
python | def get_kwargs(self):
"""Return kwargs dict for text"""
kwargs = {}
for attr in self.attrs:
val = self.attrs[attr]
if val is not None:
kwargs[attr] = repr(val)
code = ", ".join(repr(key) + ": " + kwargs[key] for key in kwargs)
code = "{" + code + "}"
return code |
python | def get_consumption(self):
"""Get current power consumption in mWh."""
self.get_status()
try:
self.consumption = self.data['power']
except TypeError:
self.consumption = 0
return self.consumption |
java | public void cancelSubscription() throws NotConnectedException, InterruptedException {
Presence unsubscribed = new Presence(item.getJid(), Type.unsubscribed);
connection().sendStanza(unsubscribed);
} |
python | def rms(self, stride=1):
"""Calculate the root-mean-square value of this `TimeSeries`
once per stride.
Parameters
----------
stride : `float`
stride (seconds) between RMS calculations
Returns
-------
rms : `TimeSeries`
a new `TimeSeries` containing the RMS value with dt=stride
"""
stridesamp = int(stride * self.sample_rate.value)
nsteps = int(self.size // stridesamp)
# stride through TimeSeries, recording RMS
data = numpy.zeros(nsteps)
for step in range(nsteps):
# find step TimeSeries
idx = int(stridesamp * step)
idx_end = idx + stridesamp
stepseries = self[idx:idx_end]
rms_ = numpy.sqrt(numpy.mean(numpy.abs(stepseries.value)**2))
data[step] = rms_
name = '%s %.2f-second RMS' % (self.name, stride)
return self.__class__(data, channel=self.channel, t0=self.t0,
name=name, sample_rate=(1/float(stride))) |
java | @Override
public Iterable<Long> ids() {
return new Iterable<Long>() {
/**
* {@inheritDoc}
*/
@Override
public Iterator<Long> iterator() {
return new Iterator<Long>() {
int index = -1;
private Iterator<Long> currentResults = null;
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
boolean hasNext = false;
if (currentResults != null) {
hasNext = currentResults.hasNext();
}
if (!hasNext) {
while (!hasNext && ++index < results.size()) {
// Get an iterator from the next feature index
// results
currentResults = results.get(index).ids()
.iterator();
hasNext = currentResults.hasNext();
}
}
return hasNext;
}
/**
* {@inheritDoc}
*/
@Override
public Long next() {
Long id = null;
if (currentResults != null) {
id = currentResults.next();
}
return id;
}
};
}
};
} |
java | @NonNull
public final List<Router> getChildRouters() {
List<Router> routers = new ArrayList<>(childRouters.size());
routers.addAll(childRouters);
return routers;
} |
java | public static BinaryTypeSignature createObjectTypeSignature(String internalName) {
if (internalName.charAt(internalName.length() - 1) != ';')
return new BinaryObjectTypeSignature(internalName);
return new BinaryGenericTypeSignature(internalName);
} |
java | public void addAtom(IPDBAtom oAtom, IMonomer oMonomer) {
super.addAtom(oAtom, oMonomer);
if (!sequentialListOfMonomers.contains(oMonomer.getMonomerName()))
sequentialListOfMonomers.add(oMonomer.getMonomerName());
} |
python | def add_media(dest, media):
"""
Optimized version of django.forms.Media.__add__() that doesn't create new objects.
"""
if django.VERSION >= (2, 2):
dest._css_lists += media._css_lists
dest._js_lists += media._js_lists
elif django.VERSION >= (2, 0):
combined = dest + media
dest._css = combined._css
dest._js = combined._js
else:
dest.add_css(media._css)
dest.add_js(media._js) |
python | def ImportStopTimes(self, stoptimes_file):
"Imports the lid_fahrzeitart.mdv file."
for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \
ReadCSV(stoptimes_file,
['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',
'FGR_NR', 'FZT_REL', 'HZEIT']):
pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]
stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])
seq = int(seq) - 1
drive_secs = int(drive_secs)
wait_secs = int(wait_secs)
assert len(stoptimes) == seq # fails if seq not in order
stoptimes.append((drive_secs, wait_secs)) |
python | def get_buffer(self):
"""Get buffer which needs to be bulked to elasticsearch"""
# Get sources for documents which are in Elasticsearch
# and they are not in local buffer
if self.doc_to_update:
self.update_sources()
ES_buffer = self.action_buffer
self.clean_up()
return ES_buffer |
java | public JsonPath build(String path) {
String[] strings = splitPath(path);
if (strings.length == 0 || (strings.length == 1 && "".equals(strings[0]))) {
throw new ResourceException("Path is empty");
}
JsonPath previousJsonPath = null, currentJsonPath = null;
PathIds pathIds;
boolean relationshipMark;
String elementName;
String actionName;
int currentElementIdx = 0;
while (currentElementIdx < strings.length) {
elementName = null;
pathIds = null;
actionName = null;
relationshipMark = false;
if (RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
relationshipMark = true;
currentElementIdx++;
}
RegistryEntry entry = null;
if (currentElementIdx < strings.length && !RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
elementName = strings[currentElementIdx];
// support "/" in resource type to group repositories
StringBuilder potentialResourceType = new StringBuilder();
for(int i = 0; currentElementIdx + i < strings.length;i++){
if(potentialResourceType.length() > 0){
potentialResourceType.append("/");
}
potentialResourceType.append(strings[currentElementIdx + i]);
entry = resourceRegistry.getEntry(potentialResourceType.toString());
if(entry != null){
currentElementIdx += i;
elementName = potentialResourceType.toString();
break;
}
}
currentElementIdx++;
}
if (currentElementIdx < strings.length && entry != null && entry.getRepositoryInformation().getActions().containsKey(strings[currentElementIdx])) {
// repository action
actionName = strings[currentElementIdx];
currentElementIdx++;
}else if (currentElementIdx < strings.length && !RELATIONSHIP_MARK.equals(strings[currentElementIdx])) {
// ids
pathIds = createPathIds(strings[currentElementIdx]);
currentElementIdx++;
if(currentElementIdx < strings.length && entry != null && entry.getRepositoryInformation().getActions().containsKey(strings[currentElementIdx])) {
// resource action
actionName = strings[currentElementIdx];
currentElementIdx++;
}
}
if (previousJsonPath != null) {
currentJsonPath = getNonResourcePath(previousJsonPath, elementName, relationshipMark);
if (pathIds != null) {
throw new ResourceException("RelationshipsPath and FieldPath cannot contain ids");
}
} else if (entry != null && !relationshipMark) {
currentJsonPath = new ResourcePath(elementName);
} else {
return null;
}
if (pathIds != null) {
currentJsonPath.setIds(pathIds);
}
if(actionName != null){
ActionPath actionPath = new ActionPath(actionName);
actionPath.setParentResource(currentJsonPath);
currentJsonPath.setChildResource(actionPath);
currentJsonPath = actionPath;
}
if (previousJsonPath != null) {
previousJsonPath.setChildResource(currentJsonPath);
currentJsonPath.setParentResource(previousJsonPath);
}
previousJsonPath = currentJsonPath;
}
return currentJsonPath;
} |
python | def convert_from(self, base):
"""Convert a BOOST_METAPARSE_STRING mode document into one with
this mode"""
if self.identifier == 'bmp':
return base
elif self.identifier == 'man':
result = []
prefix = 'BOOST_METAPARSE_STRING("'
while True:
bmp_at = base.find(prefix)
if bmp_at == -1:
return ''.join(result) + base
else:
result.append(
base[0:bmp_at] + '::boost::metaparse::string<'
)
new_base = ''
was_backslash = False
comma = ''
for i in xrange(bmp_at + len(prefix), len(base)):
if was_backslash:
result.append(
'{0}\'\\{1}\''.format(comma, base[i])
)
was_backslash = False
comma = ','
elif base[i] == '"':
new_base = base[i+2:]
break
elif base[i] == '\\':
was_backslash = True
else:
result.append('{0}\'{1}\''.format(comma, base[i]))
comma = ','
base = new_base
result.append('>') |
python | def parse_discovery_service_response(url="", query="",
returnIDParam="entityID"):
"""
Deal with the response url from a Discovery Service
:param url: the url the user was redirected back to or
:param query: just the query part of the URL.
:param returnIDParam: This is where the identifier of the IdP is
place if it was specified in the query. Default is 'entityID'
:return: The IdP identifier or "" if none was given
"""
if url:
part = urlparse(url)
qsd = parse_qs(part[4])
elif query:
qsd = parse_qs(query)
else:
qsd = {}
try:
return qsd[returnIDParam][0]
except KeyError:
return "" |
java | public List<Integer> getTrackIds() {
ArrayList<Integer> results = new ArrayList<Integer>(trackCount);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().startsWith(CACHE_METADATA_ENTRY_PREFIX)) {
String idPart = entry.getName().substring(CACHE_METADATA_ENTRY_PREFIX.length());
if (idPart.length() > 0) {
results.add(Integer.valueOf(idPart));
}
}
}
return Collections.unmodifiableList(results);
} |
java | public static void set(Message message, ExplicitMessageEncryptionProtocol protocol) {
if (!hasProtocol(message, protocol.namespace)) {
message.addExtension(new ExplicitMessageEncryptionElement(protocol));
}
} |
java | public OvhTask serviceName_account_userPrincipalName_mfa_disable_POST(String serviceName, String userPrincipalName, Long period) throws IOException {
String qPath = "/msServices/{serviceName}/account/{userPrincipalName}/mfa/disable";
StringBuilder sb = path(qPath, serviceName, userPrincipalName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "period", period);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhTask.class);
} |
java | public static byte[] generateSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
} |
python | def facilityMsToNet(SsVersionIndicator_presence=0):
"""FACILITY Section 9.3.9.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x3a) # 00111010
c = Facility()
packet = a / b / c
if SsVersionIndicator_presence is 1:
d = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0)
packet = packet / d
return packet |
python | def _set_autobw_threshold_table_bandwidth(self, v, load=False):
"""
Setter method for autobw_threshold_table_bandwidth, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/autobw_threshold_table/autobw_threshold_table_bandwidth (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_autobw_threshold_table_bandwidth is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_autobw_threshold_table_bandwidth() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("bandwidth_value",autobw_threshold_table_bandwidth.autobw_threshold_table_bandwidth, yang_name="autobw-threshold-table-bandwidth", rest_name="bandwidth", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='bandwidth-value', extensions={u'tailf-common': {u'info': u'Define Autobw Threshold Table Entries', u'cli-no-key-completion': None, u'callpoint': u'MplsAutobwThresholdTableEntries', u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-incomplete-command': None, u'alt-name': u'bandwidth'}}), is_container='list', yang_name="autobw-threshold-table-bandwidth", rest_name="bandwidth", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define Autobw Threshold Table Entries', u'cli-no-key-completion': None, u'callpoint': u'MplsAutobwThresholdTableEntries', u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-incomplete-command': None, u'alt-name': u'bandwidth'}}, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """autobw_threshold_table_bandwidth must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("bandwidth_value",autobw_threshold_table_bandwidth.autobw_threshold_table_bandwidth, yang_name="autobw-threshold-table-bandwidth", rest_name="bandwidth", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='bandwidth-value', extensions={u'tailf-common': {u'info': u'Define Autobw Threshold Table Entries', u'cli-no-key-completion': None, u'callpoint': u'MplsAutobwThresholdTableEntries', u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-incomplete-command': None, u'alt-name': u'bandwidth'}}), is_container='list', yang_name="autobw-threshold-table-bandwidth", rest_name="bandwidth", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define Autobw Threshold Table Entries', u'cli-no-key-completion': None, u'callpoint': u'MplsAutobwThresholdTableEntries', u'cli-suppress-list-no': None, u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-mode': None, u'cli-incomplete-command': None, u'alt-name': u'bandwidth'}}, namespace='urn:brocade.com:mgmt:brocade-mpls', defining_module='brocade-mpls', yang_type='list', is_config=True)""",
})
self.__autobw_threshold_table_bandwidth = t
if hasattr(self, '_set'):
self._set() |
java | public static BaasResult<BaasDocument> fetchSync(String collection, String id,boolean withAcl) {
if (collection == null) throw new IllegalArgumentException("collection cannot be null");
if (id == null) throw new IllegalArgumentException("id cannot be null");
BaasDocument doc = new BaasDocument(collection);
doc.id = id;
return doc.refreshSync(withAcl);
} |
python | def draw_dithered_color(cb, x, y, palette, dither, n, n_max, crosshairs_coord=None):
"""
Draws a dithered color block on the terminal, given a palette.
:type cb: cursebox.CurseBox
"""
i = n * (len(palette) - 1) / n_max
c1 = palette[int(math.floor(i))]
c2 = palette[int(math.ceil(i))]
value = i - int(math.floor(i))
symbol = dither_symbol(value, dither)
if crosshairs_coord is not None:
old_symbol = symbol
symbol, crosshairs = get_crosshairs_symbol(x, y, old_symbol, crosshairs_coord)
if crosshairs:
sorted_palette = sort_palette(palette)
if old_symbol == DITHER_TYPES[dither][1][0]:
c2 = c1
sorted_index = sorted_palette.index(c2)
if sorted_index > len(sorted_palette) // 2:
c1 = sorted_palette[0]
else:
c1 = sorted_palette[-1]
cb.put(x, y, symbol, c1(), c2()) |
java | void copyOngoingCreates(Block block) throws CloneNotSupportedException {
ActiveFile af = ongoingCreates.get(block);
if (af == null) {
return;
}
ongoingCreates.put(block, af.getClone());
} |
java | public void addSurface(Se3_F64 rectToWorld , double widthWorld , GrayF32 texture ) {
SurfaceRect s = new SurfaceRect();
s.texture = texture.clone();
s.width3D = widthWorld;
s.rectToWorld = rectToWorld;
ImageMiscOps.flipHorizontal(s.texture);
scene.add(s);
} |
java | public Iterator<Map.Entry<G,Integer>> iterator() {
List<Iterator<Map.Entry<G,Integer>>> iters =
new ArrayList<Iterator<Map.Entry<G,Integer>>>(orderAndSizeToGraphs.size());
for (Map<G,Integer> m : orderAndSizeToGraphs.values())
iters.add(m.entrySet().iterator());
return new CombinedIterator<Map.Entry<G,Integer>>(iters);
} |
java | public ResultSet runSelect(String logMessage, String query, Object[] arguments) throws SQLException {
long before = System.currentTimeMillis();
try {
return runSelect(query, arguments);
}
finally {
if (logger.isDebugEnabled()) {
long after = System.currentTimeMillis();
logger.debug(logMessage + " (" + (after - before) + " ms): " + DbAccess.substitute(query, arguments));
}
}
} |
java | @Override
public Tree generateListenerDescriptor(String service) {
LinkedHashMap<String, Object> descriptor = new LinkedHashMap<>();
readLock.lock();
try {
for (HashMap<String, Strategy<ListenerEndpoint>> groups : listeners.values()) {
for (Strategy<ListenerEndpoint> strategy : groups.values()) {
for (ListenerEndpoint endpoint : strategy.getAllEndpoints()) {
if (endpoint.isLocal() && endpoint.serviceName.equals(service)) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
descriptor.put(endpoint.subscribe, map);
map.put("name", endpoint.subscribe);
map.put("group", endpoint.group);
}
}
}
}
} finally {
readLock.unlock();
}
return new CheckedTree(descriptor);
} |
java | private void insertNewLease(String recoveryIdentity, String recoveryGroup, Connection conn) throws SQLException
{
if (tc.isEntryEnabled())
Tr.entry(tc, "insertNewLease", this);
short serviceId = (short) 1;
String insertString = "INSERT INTO " +
_leaseTableName +
" (SERVER_IDENTITY, RECOVERY_GROUP, LEASE_OWNER, LEASE_TIME)" +
" VALUES (?,?,?,?)";
PreparedStatement specStatement = null;
long fir1 = System.currentTimeMillis();
Tr.audit(tc, "WTRN0108I: Insert New Lease for server with recovery identity " + recoveryIdentity);
try
{
if (tc.isDebugEnabled())
Tr.debug(tc, "Need to setup new row using - " + insertString + ", and time: " + fir1);
specStatement = conn.prepareStatement(insertString);
specStatement.setString(1, recoveryIdentity);
specStatement.setString(2, recoveryGroup);
specStatement.setString(3, recoveryIdentity);
specStatement.setLong(4, fir1);
int ret = specStatement.executeUpdate();
if (tc.isDebugEnabled())
Tr.debug(tc, "Have inserted Server row with return: " + ret);
} finally
{
if (specStatement != null && !specStatement.isClosed())
specStatement.close();
}
if (tc.isEntryEnabled())
Tr.exit(tc, "insertNewLease");
} |
java | public List<Invocation> find(List<?> mocks) {
List<Invocation> unused = new LinkedList<Invocation>();
for (Object mock : mocks) {
List<Stubbing> fromSingleMock = MockUtil.getInvocationContainer(mock).getStubbingsDescending();
for(Stubbing s : fromSingleMock) {
if (!s.wasUsed()) {
unused.add(s.getInvocation());
}
}
}
return unused;
} |
python | def diversity(layer):
"""Encourage diversity between each batch element.
A neural net feature often responds to multiple things, but naive feature
visualization often only shows us one. If you optimize a batch of images,
this objective will encourage them all to be different.
In particular, it caculuates the correlation matrix of activations at layer
for each image, and then penalizes cossine similarity between them. This is
very similar to ideas in style transfer, except we're *penalizing* style
similarity instead of encouraging it.
Args:
layer: layer to evaluate activation correlations on.
Returns:
Objective.
"""
def inner(T):
layer_t = T(layer)
batch_n, _, _, channels = layer_t.get_shape().as_list()
flattened = tf.reshape(layer_t, [batch_n, -1, channels])
grams = tf.matmul(flattened, flattened, transpose_a=True)
grams = tf.nn.l2_normalize(grams, axis=[1,2], epsilon=1e-10)
return sum([ sum([ tf.reduce_sum(grams[i]*grams[j])
for j in range(batch_n) if j != i])
for i in range(batch_n)]) / batch_n
return inner |
java | public boolean isNewerThan(SetElement other) {
if (other == null) {
return true;
}
return this.timestamp.isNewerThan(other.timestamp);
} |
python | def largest_rotated_rect(w, h, angle):
"""
Get largest rectangle after rotation.
http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
"""
angle = angle / 180.0 * math.pi
if w <= 0 or h <= 0:
return 0, 0
width_is_longer = w >= h
side_long, side_short = (w, h) if width_is_longer else (h, w)
# since the solutions for angle, -angle and 180-angle are all the same,
# if suffices to look at the first quadrant and the absolute values of sin,cos:
sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle))
if side_short <= 2. * sin_a * cos_a * side_long:
# half constrained case: two crop corners touch the longer side,
# the other two corners are on the mid-line parallel to the longer line
x = 0.5 * side_short
wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a)
else:
# fully constrained case: crop touches all 4 sides
cos_2a = cos_a * cos_a - sin_a * sin_a
wr, hr = (w * cos_a - h * sin_a) / cos_2a, (h * cos_a - w * sin_a) / cos_2a
return int(np.round(wr)), int(np.round(hr)) |
python | def resid_dev(self, endog, mu, scale=1.):
r"""
Binomial deviance residuals
Parameters
-----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
scale : float, optional
An optional argument to divide the residuals by scale. The default
is 1.
Returns
-------
resid_dev : array
Deviance residuals as defined below
"""
mu = self.link._clean(mu)
if np.shape(self.n) == () and self.n == 1:
one = np.equal(endog, 1)
return np.sign(endog-mu)*np.sqrt(-2 *
np.log(one * mu + (1 - one) *
(1 - mu)))/scale
else:
return (np.sign(endog - mu) *
np.sqrt(2 * self.n *
(endog * np.log(endog/mu + 1e-200) +
(1 - endog) * np.log((1 - endog)/(1 - mu) + 1e-200)))/scale) |
python | def _show_popup(self, index=0):
"""
Shows the popup at the specified index.
:param index: index
:return:
"""
full_prefix = self._helper.word_under_cursor(
select_whole_word=False).selectedText()
if self._case_sensitive:
self._completer.setCaseSensitivity(QtCore.Qt.CaseSensitive)
else:
self._completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
# set prefix
self._completer.setCompletionPrefix(self.completion_prefix)
cnt = self._completer.completionCount()
selected = self._completer.currentCompletion()
if (full_prefix == selected) and cnt == 1:
debug('user already typed the only completion that we '
'have')
self._hide_popup()
else:
# show the completion list
if self.editor.isVisible():
if self._completer.widget() != self.editor:
self._completer.setWidget(self.editor)
self._completer.complete(self._get_popup_rect())
self._completer.popup().setCurrentIndex(
self._completer.completionModel().index(index, 0))
debug(
"popup shown: %r" % self._completer.popup().isVisible())
else:
debug('cannot show popup, editor is not visible') |
java | public void performOperation(Object resource, String operation,
Object[] args) {
CompensatingTransactionOperationRecorder recorder = operationFactory
.createRecordingOperation(resource, operation);
CompensatingTransactionOperationExecutor executor = recorder
.recordOperation(args);
executor.performOperation();
// Don't push the executor until the actual operation passed.
operationExecutors.push(executor);
} |
java | public InputStream getResourceAsStream(final String name) {
for ( final ClassLoader classLoader : this.classLoaders ) {
InputStream stream = classLoader.getResourceAsStream( name );
if ( stream != null ) {
return stream;
}
}
return null;
} |
python | def forward_inference(self, variables, evidence=None, args=None):
"""
Forward inference method using belief propagation.
Parameters:
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
Examples:
--------
>>> from pgmpy.factors.discrete import TabularCPD
>>> from pgmpy.models import DynamicBayesianNetwork as DBN
>>> from pgmpy.inference import DBNInference
>>> dbnet = DBN()
>>> dbnet.add_edges_from([(('Z', 0), ('X', 0)), (('X', 0), ('Y', 0)),
... (('Z', 0), ('Z', 1))])
>>> z_start_cpd = TabularCPD(('Z', 0), 2, [[0.5, 0.5]])
>>> x_i_cpd = TabularCPD(('X', 0), 2, [[0.6, 0.9],
... [0.4, 0.1]],
... evidence=[('Z', 0)],
... evidence_card=[2])
>>> y_i_cpd = TabularCPD(('Y', 0), 2, [[0.2, 0.3],
... [0.8, 0.7]],
... evidence=[('X', 0)],
... evidence_card=[2])
>>> z_trans_cpd = TabularCPD(('Z', 1), 2, [[0.4, 0.7],
... [0.6, 0.3]],
... evidence=[('Z', 0)],
... evidence_card=[2])
>>> dbnet.add_cpds(z_start_cpd, z_trans_cpd, x_i_cpd, y_i_cpd)
>>> dbnet.initialize_initial_state()
>>> dbn_inf = DBNInference(dbnet)
>>> dbn_inf.forward_inference([('X', 2)], {('Y', 0):1, ('Y', 1):0, ('Y', 2):1})[('X', 2)].values
array([ 0.76738736, 0.23261264])
"""
variable_dict = defaultdict(list)
for var in variables:
variable_dict[var[1]].append(var)
time_range = max(variable_dict)
if evidence:
evid_time_range = max([time_slice for var, time_slice in evidence.keys()])
time_range = max(time_range, evid_time_range)
start_bp = BeliefPropagation(self.start_junction_tree)
mid_bp = BeliefPropagation(self.one_and_half_junction_tree)
evidence_0 = self._get_evidence(evidence, 0, 0)
interface_nodes_dict = {}
potential_dict = {}
if evidence:
interface_nodes_dict = {k: v for k, v in evidence_0.items() if k in self.interface_nodes_0}
initial_factor = self._get_factor(start_bp, evidence_0)
marginalized_factor = self._marginalize_factor(self.interface_nodes_0, initial_factor)
potential_dict[0] = marginalized_factor
self._update_belief(mid_bp, self.in_clique, marginalized_factor)
if variable_dict[0]:
factor_values = start_bp.query(variable_dict[0], evidence=evidence_0, joint=False)
else:
factor_values = {}
for time_slice in range(1, time_range + 1):
evidence_time = self._get_evidence(evidence, time_slice, 1)
if interface_nodes_dict:
evidence_time.update(interface_nodes_dict)
if variable_dict[time_slice]:
variable_time = self._shift_nodes(variable_dict[time_slice], 1)
new_values = mid_bp.query(variable_time, evidence=evidence_time, joint=False)
changed_values = {}
for key in new_values.keys():
new_key = (key[0], time_slice)
new_factor = DiscreteFactor([new_key], new_values[key].cardinality, new_values[key].values)
changed_values[new_key] = new_factor
factor_values.update(changed_values)
clique_phi = self._get_factor(mid_bp, evidence_time)
out_clique_phi = self._marginalize_factor(self.interface_nodes_1, clique_phi)
new_factor = self._shift_factor(out_clique_phi, 0)
potential_dict[time_slice] = new_factor
mid_bp = BeliefPropagation(self.one_and_half_junction_tree)
self._update_belief(mid_bp, self.in_clique, new_factor)
if evidence_time:
interface_nodes_dict = {(k[0], 0): v for k, v in evidence_time.items() if k in self.interface_nodes_1}
else:
interface_nodes_dict = {}
if args == 'potential':
return potential_dict
return factor_values |
python | def get_token_accuracy(targets, outputs, ignore_index=None):
""" Get the accuracy token accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
ignore_index (int, optional): Specifies a target index that is ignored
Returns:
:class:`tuple` consisting of accuracy (:class:`float`), number correct (:class:`int`) and
total (:class:`int`)
Example:
>>> import torch
>>> from torchnlp.metrics import get_token_accuracy
>>> targets = torch.LongTensor([[1, 1], [2, 2], [3, 3]])
>>> outputs = torch.LongTensor([[1, 1], [2, 3], [4, 4]])
>>> accuracy, n_correct, n_total = get_token_accuracy(targets, outputs, ignore_index=3)
>>> accuracy
0.75
>>> n_correct
3.0
>>> n_total
4.0
"""
n_correct = 0.0
n_total = 0.0
for target, output in zip(targets, outputs):
if not torch.is_tensor(target) or is_scalar(target):
target = torch.LongTensor([target])
if not torch.is_tensor(output) or is_scalar(output):
output = torch.LongTensor([[output]])
if len(target.size()) != len(output.size()):
prediction = output.max(dim=0)[0].view(-1)
else:
prediction = output
if ignore_index is not None:
mask = target.ne(ignore_index)
n_correct += prediction.eq(target).masked_select(mask).sum().item()
n_total += mask.sum().item()
else:
n_total += len(target)
n_correct += prediction.eq(target).sum().item()
return n_correct / n_total, n_correct, n_total |
python | def scalars_route(self, request):
"""Given a tag regex and single run, return ScalarEvents.
This route takes 2 GET params:
run: A run string to find tags for.
tag: A string that is a regex used to find matching tags.
The response is a JSON object:
{
// Whether the regular expression is valid. Also false if empty.
regexValid: boolean,
// An object mapping tag name to a list of ScalarEvents.
payload: Object<string, ScalarEvent[]>,
}
"""
# TODO: return HTTP status code for malformed requests
tag_regex_string = request.args.get('tag')
run = request.args.get('run')
mime_type = 'application/json'
try:
body = self.scalars_impl(run, tag_regex_string)
except ValueError as e:
return http_util.Respond(
request=request,
content=str(e),
content_type='text/plain',
code=500)
# Produce the response.
return http_util.Respond(request, body, mime_type) |
java | public void releaseResources(List<ResourceRequest> released)
throws IOException {
if (failException != null) {
throw failException;
}
List<Integer> releasedIds = new ArrayList<Integer>();
for (ResourceRequest req : released) {
releasedIds.add(req.getId());
}
cmNotifier.addCall(
new ClusterManagerService.releaseResource_args(sessionId, releasedIds));
} |
java | private Map<String, Object> cloneAttributes(Map<String, Object> attrs) {
Map<String, Object> result = new HashMap<String, Object>();
for (Entry<String, Object> entry : attrs.entrySet()) {
if (entry.getValue() instanceof CmsJspStandardContextBean) {
result.put(entry.getKey(), ((CmsJspStandardContextBean)entry.getValue()).createCopy());
} else if (entry.getValue() instanceof Cloneable) {
Object clone = null;
try {
clone = ObjectUtils.clone(entry.getValue());
} catch (Exception e) {
LOG.info(e.getMessage(), e);
}
result.put(entry.getKey(), clone != null ? clone : entry.getValue());
} else {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
} |
python | def alias_proficiency(self, proficiency_id, alias_id):
"""Adds an ``Id`` to a ``Proficiency`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Proficiency`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another proficiency, it is
reassigned to the given proficiency ``Id``.
arg: proficiency_id (osid.id.Id): the ``Id`` of a
``Proficiency``
arg: alias_id (osid.id.Id): the alias ``Id``
raise: AlreadyExists - ``alias_id`` is already assigned
raise: NotFound - ``proficiency_id`` not found
raise: NullArgument - ``proficiency_id`` or ``alias_id`` is
``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for
# osid.resource.ResourceAdminSession.alias_resources_template
self._alias_id(primary_id=proficiency_id, equivalent_id=alias_id) |
java | private static String checkDisplayName(final FormItemList formItemList,
final CreateUserResponse createUserResponse) {
final String displayName = formItemList
.getField(ProtocolConstants.Parameters.Create.User.DISPLAY_NAME);
if (displayName != null) {
return displayName;
} else {
createUserResponse.displayNameMissing();
}
return null;
} |
python | def jwk_wrap(key, use="", kid=""):
"""
Instantiate a Key instance with the given key
:param key: The keys to wrap
:param use: What the key are expected to be use for
:param kid: A key id
:return: The Key instance
"""
if isinstance(key, rsa.RSAPublicKey) or isinstance(key, rsa.RSAPrivateKey):
kspec = RSAKey(use=use, kid=kid).load_key(key)
elif isinstance(key, str):
kspec = SYMKey(key=key, use=use, kid=kid)
elif isinstance(key, ec.EllipticCurvePublicKey):
kspec = ECKey(use=use, kid=kid).load_key(key)
else:
raise Exception("Unknown key type:key=" + str(type(key)))
kspec.serialize()
return kspec |
java | private Jedis getAndSetConnection()
{
Jedis conn = factory.getConnection();
this.connection = conn;
// If resource is not null means a transaction in progress.
if (settings != null)
{
for (String key : settings.keySet())
{
conn.configSet(key, settings.get(key).toString());
}
}
return conn;
} |
python | def add(self, path):
"""Adds a new resource with the given path to the resource set.
Parameters:
* **path (str, unicode):** path of the resource to be protected
Raises:
TypeError when the path is not a string or a unicode string
"""
if not isinstance(path, str) and not isinstance(path, unicode):
raise TypeError('The value passed for parameter path is not a str'
' or unicode')
resource = Resource(path)
self.resources[path] = resource
return resource |
java | public void addDerivedSipSessions(MobicentsSipSession derivedSession) {
if(derivedSipSessions == null) {
this.derivedSipSessions = new ConcurrentHashMap<String, MobicentsSipSession>();
}
derivedSipSessions.putIfAbsent(derivedSession.getKey().getToTag(), derivedSession);
} |
java | public static <T extends Client<I, O>, R extends Client<I, O>, I extends Request, O extends Response>
ClientDecoration of(Class<I> requestType, Class<O> responseType, Function<T, R> decorator) {
return new ClientDecorationBuilder().add(requestType, responseType, decorator).build();
} |
java | static SafeHtml roleItem(final String css, final Role role) {
if (role.isStandard()) {
return ITEMS.item(css, role.getName(), role.getName());
} else {
return ITEMS.scopedRole(css, role.getName(), baseAndScope(role), shortBaseAndScope(role));
}
} |
python | def chu_liu_edmonds(length: int,
score_matrix: numpy.ndarray,
current_nodes: List[bool],
final_edges: Dict[int, int],
old_input: numpy.ndarray,
old_output: numpy.ndarray,
representatives: List[Set[int]]):
"""
Applies the chu-liu-edmonds algorithm recursively
to a graph with edge weights defined by score_matrix.
Note that this function operates in place, so variables
will be modified.
Parameters
----------
length : ``int``, required.
The number of nodes.
score_matrix : ``numpy.ndarray``, required.
The score matrix representing the scores for pairs
of nodes.
current_nodes : ``List[bool]``, required.
The nodes which are representatives in the graph.
A representative at it's most basic represents a node,
but as the algorithm progresses, individual nodes will
represent collapsed cycles in the graph.
final_edges: ``Dict[int, int]``, required.
An empty dictionary which will be populated with the
nodes which are connected in the maximum spanning tree.
old_input: ``numpy.ndarray``, required.
old_output: ``numpy.ndarray``, required.
representatives : ``List[Set[int]]``, required.
A list containing the nodes that a particular node
is representing at this iteration in the graph.
Returns
-------
Nothing - all variables are modified in place.
"""
# Set the initial graph to be the greedy best one.
parents = [-1]
for node1 in range(1, length):
parents.append(0)
if current_nodes[node1]:
max_score = score_matrix[0, node1]
for node2 in range(1, length):
if node2 == node1 or not current_nodes[node2]:
continue
new_score = score_matrix[node2, node1]
if new_score > max_score:
max_score = new_score
parents[node1] = node2
# Check if this solution has a cycle.
has_cycle, cycle = _find_cycle(parents, length, current_nodes)
# If there are no cycles, find all edges and return.
if not has_cycle:
final_edges[0] = -1
for node in range(1, length):
if not current_nodes[node]:
continue
parent = old_input[parents[node], node]
child = old_output[parents[node], node]
final_edges[child] = parent
return
# Otherwise, we have a cycle so we need to remove an edge.
# From here until the recursive call is the contraction stage of the algorithm.
cycle_weight = 0.0
# Find the weight of the cycle.
index = 0
for node in cycle:
index += 1
cycle_weight += score_matrix[parents[node], node]
# For each node in the graph, find the maximum weight incoming
# and outgoing edge into the cycle.
cycle_representative = cycle[0]
for node in range(length):
if not current_nodes[node] or node in cycle:
continue
in_edge_weight = float("-inf")
in_edge = -1
out_edge_weight = float("-inf")
out_edge = -1
for node_in_cycle in cycle:
if score_matrix[node_in_cycle, node] > in_edge_weight:
in_edge_weight = score_matrix[node_in_cycle, node]
in_edge = node_in_cycle
# Add the new edge score to the cycle weight
# and subtract the edge we're considering removing.
score = (cycle_weight +
score_matrix[node, node_in_cycle] -
score_matrix[parents[node_in_cycle], node_in_cycle])
if score > out_edge_weight:
out_edge_weight = score
out_edge = node_in_cycle
score_matrix[cycle_representative, node] = in_edge_weight
old_input[cycle_representative, node] = old_input[in_edge, node]
old_output[cycle_representative, node] = old_output[in_edge, node]
score_matrix[node, cycle_representative] = out_edge_weight
old_output[node, cycle_representative] = old_output[node, out_edge]
old_input[node, cycle_representative] = old_input[node, out_edge]
# For the next recursive iteration, we want to consider the cycle as a
# single node. Here we collapse the cycle into the first node in the
# cycle (first node is arbitrary), set all the other nodes not be
# considered in the next iteration. We also keep track of which
# representatives we are considering this iteration because we need
# them below to check if we're done.
considered_representatives: List[Set[int]] = []
for i, node_in_cycle in enumerate(cycle):
considered_representatives.append(set())
if i > 0:
# We need to consider at least one
# node in the cycle, arbitrarily choose
# the first.
current_nodes[node_in_cycle] = False
for node in representatives[node_in_cycle]:
considered_representatives[i].add(node)
if i > 0:
representatives[cycle_representative].add(node)
chu_liu_edmonds(length, score_matrix, current_nodes, final_edges, old_input, old_output, representatives)
# Expansion stage.
# check each node in cycle, if one of its representatives
# is a key in the final_edges, it is the one we need.
found = False
key_node = -1
for i, node in enumerate(cycle):
for cycle_rep in considered_representatives[i]:
if cycle_rep in final_edges:
key_node = node
found = True
break
if found:
break
previous = parents[key_node]
while previous != key_node:
child = old_output[parents[previous], previous]
parent = old_input[parents[previous], previous]
final_edges[child] = parent
previous = parents[previous] |
python | def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the vertical force
HISTORY:
2010-07-10 - Written - Bovy (NYU)
"""
return -z/(R**2.+z**2.)**(self.alpha/2.) |
java | public <T extends DObject> void unsubscribeFromObject (int oid, Subscriber<T> target)
{
// queue up an access object event
postEvent(new AccessObjectEvent<T>(oid, target, AccessObjectEvent.UNSUBSCRIBE));
} |
python | def loadFromFile(self, path):
"""
Load JSON config file from disk at the given path
:param str path: path to config file
"""
if '~' in path:
path = os.path.expanduser(path)
f = open(path)
body = f.read()
f.close()
self._path = path
self.loadFromString(body) |
python | def setbridgeprio(self, prio):
""" Set bridge priority value. """
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)],
"Could not set bridge priority in %s." % self.name) |
python | def SetDefaultAgency(self, agency, validate=True):
"""Make agency the default and add it to the schedule if not already added"""
assert isinstance(agency, self._gtfs_factory.Agency)
self._default_agency = agency
if agency.agency_id not in self._agencies:
self.AddAgencyObject(agency, validate=validate) |
python | def _create_spreadsheet(name, title, path, settings):
"""
Create Google spreadsheet.
"""
if not settings.client_secrets:
return None
create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ")
if create and not create.lower() == "y":
return puts("Not creating spreadsheet.")
email_message = (
"What Google account(s) should have access to this "
"this spreadsheet? (Use a full email address, such as "
"[email protected]. Separate multiple addresses with commas.)")
if settings.config.get("google_account"):
emails = raw_input("\n{0}(Default: {1}) ".format(email_message,
settings.config.get("google_account")
))
if not emails:
emails = settings.config.get("google_account")
else:
emails = None
while not emails:
emails = raw_input(email_message)
try:
media_body = _MediaFileUpload(os.path.join(path, '_blueprint/_spreadsheet.xlsx'),
mimetype='application/vnd.ms-excel')
except IOError:
show_error("_blueprint/_spreadsheet.xlsx doesn't exist!")
return None
service = get_drive_api()
body = {
'title': '{0} (Tarbell)'.format(title),
'description': '{0} ({1})'.format(title, name),
'mimeType': 'application/vnd.ms-excel',
}
try:
newfile = service.files()\
.insert(body=body, media_body=media_body, convert=True).execute()
for email in emails.split(","):
_add_user_to_file(newfile['id'], service, user_email=email.strip())
puts("\n{0!s}! View the spreadsheet at {1!s}".format(
colored.green("Success"),
colored.yellow("https://docs.google.com/spreadsheet/ccc?key={0}"
.format(newfile['id']))
))
return newfile['id']
except errors.HttpError as error:
show_error('An error occurred creating spreadsheet: {0}'.format(error))
return None |
java | private static final void swap(double[] data, int a, int b) {
double tmp = data[a];
data[a] = data[b];
data[b] = tmp;
} |
python | def block_count(self):
"""
Reports the number of blocks in the ledger and unchecked synchronizing
blocks
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.block_count()
{
"count": 1000,
"unchecked": 10
}
"""
resp = self.call('block_count')
for k, v in resp.items():
resp[k] = int(v)
return resp |
python | def email_confirm(request, confirmation_key,
template_name='userena/email_confirm_fail.html',
success_url=None, extra_context=None):
"""
Confirms an email address with a confirmation key.
Confirms a new email address by running :func:`User.objects.confirm_email`
method. If the method returns an :class:`User` the user will have his new
e-mail address set and redirected to ``success_url``. If no ``User`` is
returned the user will be represented with a fail message from
``template_name``.
:param confirmation_key:
String with a SHA1 representing the confirmation key used to verify a
new email address.
:param template_name:
String containing the template name which should be rendered when
confirmation fails. When confirmation is successful, no template is
needed because the user will be redirected to ``success_url``.
:param success_url:
String containing the URL which is redirected to after a successful
confirmation. Supplied argument must be able to be rendered by
``reverse`` function.
:param extra_context:
Dictionary of variables that are passed on to the template supplied by
``template_name``.
"""
user = UserenaSignup.objects.confirm_email(confirmation_key)
if user:
if userena_settings.USERENA_USE_MESSAGES:
messages.success(request, _('Your email address has been changed.'),
fail_silently=True)
if success_url: redirect_to = success_url
else: redirect_to = reverse('userena_email_confirm_complete',
kwargs={'username': user.username})
return redirect(redirect_to)
else:
if not extra_context: extra_context = dict()
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request) |
python | def _update_control_section(self):
""" private method to synchronize the control section counters with the
various parts of the control file. This is usually called during the
Pst.write() method.
"""
self.control_data.npar = self.npar
self.control_data.nobs = self.nobs
self.control_data.npargp = self.parameter_groups.shape[0]
self.control_data.nobsgp = self.observation_data.obgnme.\
value_counts().shape[0] + self.prior_information.obgnme.\
value_counts().shape[0]
self.control_data.nprior = self.prior_information.shape[0]
self.control_data.ntplfle = len(self.template_files)
self.control_data.ninsfle = len(self.instruction_files)
self.control_data.numcom = len(self.model_command) |
java | public C4Replicator createReplicator(
C4Socket openSocket,
int push, int pull,
byte[] options,
C4ReplicatorListener listener,
Object replicatorContext)
throws LiteCoreException {
return new C4Replicator(handle, openSocket.handle, push, pull,
options, listener, replicatorContext);
} |
python | def export(self, top=True):
"""Exports object to its string representation.
Args:
top (bool): if True appends `internal_name` before values.
All non list objects should be exported with value top=True,
all list objects, that are embedded in as fields inlist objects
should be exported with `top`=False
Returns:
str: The objects string representation
"""
out = []
if top:
out.append(self._internal_name)
out.append(self._to_str(self.ground_temperature_depth))
out.append(self._to_str(self.depth_soil_conductivity))
out.append(self._to_str(self.depth_soil_density))
out.append(self._to_str(self.depth_soil_specific_heat))
out.append(self._to_str(self.depth_january_average_ground_temperature))
out.append(
self._to_str(
self.depth_february_average_ground_temperature))
out.append(self._to_str(self.depth_march_average_ground_temperature))
out.append(self._to_str(self.depth_april_average_ground_temperature))
out.append(self._to_str(self.depth_may_average_ground_temperature))
out.append(self._to_str(self.depth_june_average_ground_temperature))
out.append(self._to_str(self.depth_july_average_ground_temperature))
out.append(self._to_str(self.depth_august_average_ground_temperature))
out.append(
self._to_str(
self.depth_september_average_ground_temperature))
out.append(self._to_str(self.depth_october_average_ground_temperature))
out.append(
self._to_str(
self.depth_november_average_ground_temperature))
out.append(
self._to_str(
self.depth_december_average_ground_temperature))
return ",".join(out) |
python | def write_loudest_events(page, bins, onsource=False):
"""
Write injection chisq plots to markup.page object page
"""
th = ['']+['Mchirp %s - %s' % tuple(bin) for bin in bins]
td = []
plots = ['BestNR','SNR']
if onsource:
trial = 'ONSOURCE'
else:
trial = 'OFFTRIAL_1'
for pTag in plots:
row = pTag.lower()
d = [pTag]
for bin in bins:
b = '%s_%s' % tuple(bin)
plot = markup.page()
p = "%s/efficiency/%s_vs_fap_%s.png" % (trial, row, b)
plot.a(href=p, title="FAP versus %s" % pTag)
plot.img(src=p)
plot.a.close()
d.append(plot())
td.append(d)
row = 'snruncut'
d = ['SNR after cuts <br> have been applied']
for bin in bins:
b = '%s_%s' % tuple(bin)
plot = markup.page()
p = "%s/efficiency/%s_vs_fap_%s.png" % (trial, row, b)
plot.a(href=p, title="FAP versus %s" % pTag)
plot.img(src=p)
plot.a.close()
d.append(plot())
td.append(d)
page = write_table(page, th, td)
page.add('For more details on the loudest offsource events see')
page.a(href='%s/efficiency/loudest_offsource_trigs.html' % (trial))
page.add('here.')
page.a.close()
return page |
java | public void setHandler(IScopeHandler handler) {
log.debug("setHandler: {} on {}", handler, name);
this.handler = handler;
if (handler instanceof IScopeAware) {
((IScopeAware) handler).setScope(this);
}
} |
python | def handle_exec(args):
"""usage: cosmic-ray exec <session-file>
Perform the remaining work to be done in the specified session.
This requires that the rest of your mutation testing
infrastructure (e.g. worker processes) are already running.
"""
session_file = get_db_name(args.get('<session-file>'))
cosmic_ray.commands.execute(session_file)
return ExitCode.OK |
python | def _get_attribute_dimension(trait_name, mark_type=None):
"""Returns the dimension for the name of the trait for the specified mark.
If `mark_type` is `None`, then the `trait_name` is returned
as is.
Returns `None` if the `trait_name` is not valid for `mark_type`.
"""
if(mark_type is None):
return trait_name
scale_metadata = mark_type.class_traits()['scales_metadata']\
.default_args[0]
return scale_metadata.get(trait_name, {}).get('dimension', None) |
python | def truncate(self, percentage):
"""
Truncate ``percentage`` / 2 [%] of whole time from first and last time.
:param float percentage: Percentage of truncate.
:Sample Code:
.. code:: python
from datetimerange import DateTimeRange
time_range = DateTimeRange(
"2015-03-22T10:00:00+0900", "2015-03-22T10:10:00+0900")
time_range.is_output_elapse = True
print(time_range)
time_range.truncate(10)
print(time_range)
:Output:
.. parsed-literal::
2015-03-22T10:00:00+0900 - 2015-03-22T10:10:00+0900 (0:10:00)
2015-03-22T10:00:30+0900 - 2015-03-22T10:09:30+0900 (0:09:00)
"""
self.validate_time_inversion()
if percentage < 0:
raise ValueError("discard_percent must be greater or equal to zero: " + str(percentage))
if percentage == 0:
return
discard_time = self.timedelta // int(100) * int(percentage / 2)
self.__start_datetime += discard_time
self.__end_datetime -= discard_time |
java | public TransformersSubRegistration registerSubsystemTransformers(final String name, final ModelVersionRange range, final ResourceTransformer subsystemTransformer, final OperationTransformer operationTransformer, boolean placeholder) {
final PathAddress subsystemAddress = PathAddress.EMPTY_ADDRESS.append(PathElement.pathElement(SUBSYSTEM, name));
for(final ModelVersion version : range.getVersions()) {
subsystem.createChildRegistry(subsystemAddress, version, subsystemTransformer, operationTransformer, placeholder);
}
return new TransformersSubRegistrationImpl(range, subsystem, subsystemAddress);
} |
python | def get(self):
"""Reads the remote file from Gist and save it locally"""
if self.gist:
content = self.github.read_gist_file(self.gist)
self.local.save(content) |
java | private void validateExpr(SqlNode expr, SqlValidatorScope scope) {
if (expr instanceof SqlCall) {
final SqlOperator op = ((SqlCall) expr).getOperator();
if (op.isAggregator() && op.requiresOver()) {
throw newValidationError(expr,
RESOURCE.absentOverClause());
}
}
// Call on the expression to validate itself.
expr.validateExpr(this, scope);
// Perform any validation specific to the scope. For example, an
// aggregating scope requires that expressions are valid aggregations.
scope.validateExpr(expr);
} |
java | public boolean concatenateAligned(BitOutputStream src) {
int bitsToAdd = src.totalBits - src.totalConsumedBits;
if (bitsToAdd == 0) return true;
if (outBits != src.consumedBits) return false;
if (!ensureSize(bitsToAdd)) return false;
if (outBits == 0) {
System.arraycopy(src.buffer, src.consumedBlurbs, buffer, outBlurbs,
(src.outBlurbs - src.consumedBlurbs + ((src.outBits != 0) ? 1 : 0)));
} else if (outBits + bitsToAdd > BITS_PER_BLURB) {
buffer[outBlurbs] <<= (BITS_PER_BLURB - outBits);
buffer[outBlurbs] |= (src.buffer[src.consumedBlurbs] & ((1 << (BITS_PER_BLURB - outBits)) - 1));
System.arraycopy(src.buffer, src.consumedBlurbs + 1, buffer, outBlurbs + 11,
(src.outBlurbs - src.consumedBlurbs - 1 + ((src.outBits != 0) ? 1 : 0)));
} else {
buffer[outBlurbs] <<= bitsToAdd;
buffer[outBlurbs] |= (src.buffer[src.consumedBlurbs] & ((1 << bitsToAdd) - 1));
}
outBits = src.outBits;
totalBits += bitsToAdd;
outBlurbs = totalBits / BITS_PER_BLURB;
return true;
} |
java | public List<T> sortTopologically(Set<T> payloads) {
List<T> result = new ArrayList<>();
Set<T> input = new HashSet<>(payloads);
Deque<DirectedAcyclicGraphNode<T>> toVisit = new ArrayDeque<>(mRoots);
while (!toVisit.isEmpty()) {
DirectedAcyclicGraphNode<T> visit = toVisit.removeFirst();
T payload = visit.getPayload();
if (input.remove(payload)) {
result.add(visit.getPayload());
}
toVisit.addAll(visit.getChildren());
}
Preconditions.checkState(input.isEmpty(), "Not all the given payloads are in the DAG: ",
input);
return result;
} |
java | @Override
public String[] getFileSuffixes() {
String[] suffixes = filterEmptyStrings(settings.getStringArray(GroovyPlugin.FILE_SUFFIXES_KEY));
if (suffixes.length == 0) {
suffixes = StringUtils.split(GroovyPlugin.DEFAULT_FILE_SUFFIXES, ",");
}
return addDot(suffixes);
} |
python | def genms(self, scans=[]):
""" Generate an MS that contains all calibrator scans with 1 s integration time.
"""
if len(scans):
scanstr = string.join([str(ss) for ss in sorted(scans)], ',')
else:
scanstr = self.allstr
print 'Splitting out all cal scans (%s) with 1s int time' % scanstr
newname = ps.sdm2ms(self.sdmfile, self.sdmfile.rstrip('/')+'.ms', scanstr, inttime='1') # integrate down to 1s during split
return newname |
java | @Override
public Deque<MutablePair<DeltaType, Object>> getByKey(String key) {
lock.readLock().lock();
try {
Deque<MutablePair<DeltaType, Object>> deltas = this.items.get(key);
if (deltas != null) {
// returning a shallow copy
return new LinkedList<>(deltas);
}
} finally {
lock.readLock().unlock();
}
return null;
} |
java | public List<String> extractSuffixByWords(int length, int size, boolean extend)
{
TFDictionary suffixTreeSet = new TFDictionary();
for (String key : tfDictionary.keySet())
{
List<Term> termList = StandardTokenizer.segment(key);
if (termList.size() > length)
{
suffixTreeSet.add(combine(termList.subList(termList.size() - length, termList.size())));
if (extend)
{
for (int l = 1; l < length; ++l)
{
suffixTreeSet.add(combine(termList.subList(termList.size() - l, termList.size())));
}
}
}
}
return extract(suffixTreeSet, size);
} |
python | def deref(data, spec: dict):
"""
Return dereference data
:param data:
:param spec:
:return:
"""
if isinstance(data, Sequence):
is_dict = False
gen = enumerate(data)
elif not isinstance(data, Mapping):
return data
elif '$ref' in data:
return deref(get_ref(spec, data['$ref']), spec)
else:
is_dict = True
gen = data.items() # type: ignore
result = None
for k, v in gen:
new_v = deref(v, spec)
if new_v is not v:
if result is not None:
pass
elif is_dict:
result = data.copy()
else:
result = data[:]
result[k] = new_v
return result or data |
java | public base_response loginchallengeresponse(String response) throws Exception
{
loginchallengeresponse logincr = new loginchallengeresponse(response);
base_response result = logincr.perform_operation(this);
if (result.errorcode == 0)
this.sessionid = result.sessionid;
return result;
} |
python | def _new_device_id(self, key):
"""
Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int
"""
device_id = Id.SERVER + 1
if key in self._key2deviceId:
return self._key2deviceId[key]
while device_id in self._clients:
device_id += 1
return device_id |
java | @Override
public final void execute() throws MojoExecutionException, MojoFailureException {
if (skipTests) {
if (session.getGoals().contains("jmeter:gui")) {
if (!"default-cli".equals(mojoExecution.getExecutionId()) && !"compile".equals(mojoExecution.getLifecyclePhase())) {
getLog().info("Performance tests are skipped.");
return;
}
} else {
getLog().info("Performance tests are skipped.");
return;
}
}
if (useMavenProxy && proxyConfig == null) {
loadMavenProxy();
}
doExecute();
} |
java | private void resetDefaults( TableView tView ) {
Object[] colNames = tView.getColNames();
Object[][] tableValues = tView.getCalcdValues();
// dumpObjs( tableValues, System.out);
JTable table = new JTable( tableValues, colNames );
tView.setViewColumnsWidth( table );
setTitle( tView.getViewTitle() );
//
if ( mainSP != null ) getContentPane().remove( mainSP );
mainSP = new JScrollPane( table );
getContentPane().add( mainSP, "Center" );
validate();
} |
java | public void addClause(final Literal... literals) {
if (this.miniSat == null && this.cleaneLing == null)
this.result.add(this.f.clause(literals));
else if (this.miniSat != null) {
final LNGIntVector clauseVec = new LNGIntVector(literals.length);
for (final Literal lit : literals) {
int index = this.miniSat.underlyingSolver().idxForName(lit.name());
if (index == -1) {
index = this.miniSat.underlyingSolver().newVar(!this.miniSat.initialPhase(), true);
this.miniSat.underlyingSolver().addName(lit.name(), index);
}
final int litNum;
if (lit instanceof EncodingAuxiliaryVariable)
litNum = !((EncodingAuxiliaryVariable) lit).negated ? index * 2 : (index * 2) ^ 1;
else
litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
}
this.miniSat.underlyingSolver().addClause(clauseVec, null);
this.miniSat.setSolverToUndef();
} else {
for (final Literal lit : literals) {
final int index = this.cleaneLing.getOrCreateVarIndex(lit.variable());
if (lit instanceof EncodingAuxiliaryVariable)
this.cleaneLing.underlyingSolver().addlit(!((EncodingAuxiliaryVariable) lit).negated ? index : -index);
else
this.cleaneLing.underlyingSolver().addlit(lit.phase() ? index : -index);
}
this.cleaneLing.underlyingSolver().addlit(CleaneLing.CLAUSE_TERMINATOR);
this.cleaneLing.setSolverToUndef();
}
} |
python | def unique_ordered(data):
"""
Returns the same as np.unique, but ordered as per the
first occurrence of the unique value in data.
Examples
---------
In [1]: a = [0, 3, 3, 4, 1, 3, 0, 3, 2, 1]
In [2]: np.unique(a)
Out[2]: array([0, 1, 2, 3, 4])
In [3]: trimesh.grouping.unique_ordered(a)
Out[3]: array([0, 3, 4, 1, 2])
"""
data = np.asanyarray(data)
order = np.sort(np.unique(data, return_index=True)[1])
result = data[order]
return result |
java | public static void main(String[] args)
throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException {
try {
/* play.min.io for test and development. */
MinioClient minioClient = new MinioClient("https://play.min.io:9000", "Q3AM3UQ867SPQQA43P2F",
"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
/* Amazon S3: */
// MinioClient minioClient = new MinioClient("https://s3.amazonaws.com", "YOUR-ACCESSKEYID",
// "YOUR-SECRETACCESSKEY");
class TestBucketListener implements BucketEventListener {
@Override
public void updateEvent(NotificationInfo info) {
System.out.println(info.records[0].s3.bucket.name + "/"
+ info.records[0].s3.object.key + " has been created");
}
}
minioClient.listenBucketNotification("my-bucketname", "", "",
new String[]{"s3:ObjectCreated:*"}, new TestBucketListener());
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
}
} |
java | public <T extends InvocationMarshaller<?>> T registerDispatcher (
InvocationDispatcher<T> dispatcher, String group)
{
_omgr.requireEventThread(); // sanity check
// get the next invocation code
int invCode = nextInvCode();
// create the marshaller and initialize it
T marsh = dispatcher.createMarshaller();
marsh.init(_invoid, invCode, _standaloneClient == null ?
null : _standaloneClient.getInvocationDirector());
// register the dispatcher
_dispatchers.put(invCode, dispatcher);
// if it's a bootstrap service, slap it in the list
if (group != null) {
_bootlists.put(group, marsh);
}
_recentRegServices.put(Integer.valueOf(invCode), marsh.getClass().getName());
log.debug("Registered service", "code", invCode, "marsh", marsh);
return marsh;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.